aboutsummaryrefslogtreecommitdiff
path: root/src/DevHive.Services/Services/UserService.cs
diff options
context:
space:
mode:
authorDanail Dimitrov <danaildimitrov321@gmail.com>2020-12-18 13:17:46 +0200
committerDanail Dimitrov <danaildimitrov321@gmail.com>2020-12-18 13:17:46 +0200
commit844ee0cba02d245ba5c8ba77282235066549ce8d (patch)
treefe91e87d76a8a20049e57645709619a323d40098 /src/DevHive.Services/Services/UserService.cs
parent13cdc46cbe5ebe1aa607f90e554de5f222adce8d (diff)
parentf22f708a3b98dbee905786e076bb0d171316bae8 (diff)
downloadDevHive-844ee0cba02d245ba5c8ba77282235066549ce8d.tar
DevHive-844ee0cba02d245ba5c8ba77282235066549ce8d.tar.gz
DevHive-844ee0cba02d245ba5c8ba77282235066549ce8d.zip
Merge branch 'dev' of github.com:Team-Kaleidoscope/DevHive into dev
Diffstat (limited to 'src/DevHive.Services/Services/UserService.cs')
-rw-r--r--src/DevHive.Services/Services/UserService.cs47
1 files changed, 47 insertions, 0 deletions
diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs
index d3c0d0d..b2d5aee 100644
--- a/src/DevHive.Services/Services/UserService.cs
+++ b/src/DevHive.Services/Services/UserService.cs
@@ -105,6 +105,42 @@ namespace DevHive.Services.Services
throw new InvalidOperationException("Unable to delete user!");
}
+ /// <summary>
+ /// Checks wether the given token's UserName and Roles are the same as these of the user with the given id.
+ /// </summary>
+ public async Task<bool> ValidJWT(Guid id, string rawTokenData)
+ {
+ // There is authorization name in the beginning, i.e. "Bearer eyJh..."
+ var jwt = new JwtSecurityTokenHandler().ReadJwtToken(rawTokenData.Remove(0, 7));
+
+ User user = await this._userRepository.GetByIdAsync(id)
+ ?? throw new ArgumentException("User does not exist!");
+
+ /* Check username */
+ string jwtUserName = this.GetClaimTypeValues("unique_name", jwt.Claims)[0];
+
+ if (jwtUserName != user.UserName)
+ return false;
+
+ /* Check roles */
+ List<string> jwtRoleNames = this.GetClaimTypeValues("role", jwt.Claims);
+
+ // Check if jwt contains all user roles (if it doesn't, jwt is either old or tampered with)
+ foreach(var role in user.Roles)
+ {
+ if (!jwtRoleNames.Contains(role.Name))
+ return false;
+
+ jwtRoleNames.Remove(role.Name);
+ }
+
+ // Check if jwt contains only roles of user
+ if (jwtRoleNames.Count > 0)
+ return false;
+
+ return true;
+ }
+
private string GeneratePasswordHash(string password)
{
return string.Join(string.Empty, SHA512.HashData(Encoding.ASCII.GetBytes(password)));
@@ -137,5 +173,16 @@ namespace DevHive.Services.Services
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
+
+ private List<string> GetClaimTypeValues(string type, IEnumerable<Claim> claims)
+ {
+ List<string> toReturn = new();
+
+ foreach(var claim in claims)
+ if (claim.Type == type)
+ toReturn.Add(claim.Value);
+
+ return toReturn;
+ }
}
}