| | 1 | | using System.Text; |
| | 2 | | using System.Security.Claims; |
| | 3 | | using Microsoft.IdentityModel.Tokens; |
| | 4 | | using System.IdentityModel.Tokens.Jwt; |
| | 5 | | using Syki.Back.Features.Cross.CreateUser; |
| | 6 | |
|
| | 7 | | namespace Syki.Back.Features.Cross.GenerateJWT; |
| | 8 | |
|
| 394 | 9 | | public class GenerateJWTService(AuthSettings settings, UserManager<SykiUser> userManager, SykiDbContext ctx) : ICrossSer |
| | 10 | | { |
| | 11 | | public async Task<string> Generate(string email) |
| | 12 | | { |
| 383 | 13 | | var user = (await userManager.FindByEmailAsync(email))!; |
| 383 | 14 | | var role = (await userManager.GetRolesAsync(user))[0]; |
| | 15 | |
|
| 383 | 16 | | var claims = new List<Claim> |
| 383 | 17 | | { |
| 383 | 18 | | new("jti", Guid.NewGuid().ToString()), |
| 383 | 19 | | new("sub", user.Id.ToString()), |
| 383 | 20 | | new("role", role), |
| 383 | 21 | | new("name", user.Name), |
| 383 | 22 | | new("email", user.Email!), |
| 383 | 23 | | new("institution", user.InstitutionId.ToString()), |
| 383 | 24 | | }; |
| 383 | 25 | | claims.AddRange(await GetDbClaims(user.Id, role)); |
| | 26 | |
|
| 383 | 27 | | var identityClaims = new ClaimsIdentity(); |
| 383 | 28 | | identityClaims.AddClaims(claims); |
| | 29 | |
|
| 383 | 30 | | var key = Encoding.ASCII.GetBytes(settings.SecurityKey); |
| 383 | 31 | | var expirationTime = settings.ExpirationTimeInMinutes; |
| 383 | 32 | | var signingCredentials = new SigningCredentials( |
| 383 | 33 | | new SymmetricSecurityKey(key), |
| 383 | 34 | | SecurityAlgorithms.HmacSha256Signature |
| 383 | 35 | | ); |
| | 36 | |
|
| 383 | 37 | | var tokenDescriptor = new SecurityTokenDescriptor |
| 383 | 38 | | { |
| 383 | 39 | | Issuer = settings.Issuer, |
| 383 | 40 | | Subject = identityClaims, |
| 383 | 41 | | Audience = settings.Audience, |
| 383 | 42 | | SigningCredentials = signingCredentials, |
| 383 | 43 | | Expires = DateTime.UtcNow.AddMinutes(expirationTime), |
| 383 | 44 | | }; |
| | 45 | |
|
| 383 | 46 | | var tokenHandler = new JwtSecurityTokenHandler(); |
| 383 | 47 | | var token = tokenHandler.CreateToken(tokenDescriptor); |
| | 48 | |
|
| 383 | 49 | | return tokenHandler.WriteToken(token); |
| 383 | 50 | | } |
| | 51 | |
|
| | 52 | | private async Task<List<Claim>> GetDbClaims(Guid userId, string role) |
| | 53 | | { |
| 383 | 54 | | if (role.ToEnum<UserRole>() is UserRole.Student) |
| | 55 | | { |
| 80 | 56 | | var courseOfferingId = await ctx.Students.Where(a => a.Id == userId) |
| 80 | 57 | | .Select(a => a.CourseOfferingId).FirstAsync(); |
| 80 | 58 | | var courseCurriculumId = await ctx.CourseOfferings.Where(o => o.Id == courseOfferingId) |
| 80 | 59 | | .Select(o => o.CourseCurriculumId).FirstAsync(); |
| | 60 | |
|
| 80 | 61 | | return [ new("CourseCurriculumId", courseCurriculumId.ToString()) ]; |
| | 62 | | } |
| | 63 | |
|
| 303 | 64 | | return []; |
| 383 | 65 | | } |
| | 66 | | } |