public async Task <User?> MakeJwt(User user) { const int hoursUntilExpires = 4; var tokenHandler = new JwtSecurityTokenHandler(); var secretKey = Environment.GetEnvironmentVariable("COMBINE_JWT_SECRET_KEY") !; var key = Encoding.ASCII.GetBytes(secretKey); // Fetch the projects Id and the roles for each Id var projectPermissionMap = new List <ProjectPermissions>(); foreach (var(projectRoleKey, projectRoleValue) in user.ProjectRoles) { // Convert each userRoleId to its respective role and add to the mapping var userRole = await _userRoleRepo.GetUserRole(projectRoleKey, projectRoleValue); if (userRole is null) { return(null); } var validEntry = new ProjectPermissions(projectRoleKey, userRole.Permissions); projectPermissionMap.Add(validEntry); } var claimString = projectPermissionMap.ToJson(); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim("UserId", user.Id), new Claim("UserRoleInfo", claimString) }), Expires = DateTime.UtcNow.AddHours(hoursUntilExpires), SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); // Sanitize user to remove password, avatar path, and old token // Then add updated token. user.Sanitize(); user.Token = tokenHandler.WriteToken(token); if (await _userRepo.Update(user.Id, user) != ResultOfUpdate.Updated) { return(null); } return(user); }
public async Task <User> MakeJwt(User user) { const int tokenExpirationMinutes = 60 * 4; var tokenHandler = new JwtSecurityTokenHandler(); var secretKey = Environment.GetEnvironmentVariable("ASPNETCORE_JWT_SECRET_KEY"); var key = Encoding.ASCII.GetBytes(secretKey); // Fetch the projects Id and the roles for each Id var projectPermissionMap = new List <ProjectPermissions>(); foreach (var(projectRoleKey, projectRoleValue) in user.ProjectRoles) { // Convert each userRoleId to its respective role and add to the mapping var permissions = _userRole.GetUserRole(projectRoleKey, projectRoleValue).Result.Permissions; var validEntry = new ProjectPermissions(projectRoleKey, permissions); projectPermissionMap.Add(validEntry); } var claimString = projectPermissionMap.ToJson(); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim("UserId", user.Id), new Claim("UserRoleInfo", claimString) }), Expires = DateTime.UtcNow.AddMinutes(tokenExpirationMinutes), SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); user.Token = tokenHandler.WriteToken(token); if (await Update(user.Id, user) != ResultOfUpdate.Updated) { return(null); } // Remove password and avatar filepath before returning user.Password = ""; user.Avatar = ""; return(user); }