-
Notifications
You must be signed in to change notification settings - Fork 0
T3: Identity API controller + JWT auth #63
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: devin/identity-t2-persistence
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,29 +1,63 @@ | ||
| using Microsoft.AspNetCore.Authorization; | ||
| using Microsoft.AspNetCore.Mvc; | ||
| using Identity.Domain.DTOs; | ||
| using Identity.Domain.Interfaces; | ||
|
|
||
| namespace Identity.API.Controllers; | ||
|
|
||
| [ApiController] | ||
| [Route("api/[controller]")] | ||
| public class IdentityController : ControllerBase | ||
| { | ||
| private readonly ILogger<IdentityController> _logger; | ||
| private readonly IIdentityService _identityService; | ||
|
|
||
| public IdentityController(ILogger<IdentityController> logger) | ||
| public IdentityController(IIdentityService identityService) | ||
| { | ||
| _logger = logger; | ||
| _identityService = identityService; | ||
| } | ||
|
|
||
| [HttpGet] | ||
| public IActionResult GetAll() | ||
| [HttpPost("register")] | ||
| [ProducesResponseType(typeof(AppUserDto), StatusCodes.Status201Created)] | ||
| [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
| public async Task<IActionResult> Register([FromBody] RegisterRequest request) | ||
| { | ||
| // TODO: Implement — migrate logic from monolith's IdentityController | ||
| return Ok(new { service = "Identity", status = "scaffold" }); | ||
| var result = await _identityService.RegisterAsync(request); | ||
| if (!result.Success) | ||
| return BadRequest(new { error = result.ErrorMessage }); | ||
| return CreatedAtAction(nameof(GetById), new { id = result.User!.Id }, result.User); | ||
| } | ||
|
|
||
| [HttpGet("{id}")] | ||
| public IActionResult GetById(int id) | ||
| [HttpPost("login")] | ||
| [ProducesResponseType(StatusCodes.Status200OK)] | ||
| [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||
| public async Task<IActionResult> Login([FromBody] LoginRequest request) | ||
| { | ||
| // TODO: Implement — migrate logic from monolith | ||
| return Ok(new { service = "Identity", id }); | ||
| var result = await _identityService.LoginAsync(request); | ||
| if (!result.Success) | ||
| return Unauthorized(new { error = result.ErrorMessage }); | ||
| return Ok(new { token = result.Token }); | ||
| } | ||
|
|
||
| [HttpGet("users")] | ||
| [Authorize] | ||
| [ProducesResponseType(typeof(IEnumerable<AppUserDto>), StatusCodes.Status200OK)] | ||
| [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||
| public async Task<IActionResult> GetUsers() | ||
| { | ||
| var users = await _identityService.GetAllUsersAsync(); | ||
| return Ok(users); | ||
| } | ||
|
|
||
| [HttpGet("users/{id:guid}")] | ||
| [Authorize] | ||
| [ProducesResponseType(typeof(AppUserDto), StatusCodes.Status200OK)] | ||
| [ProducesResponseType(StatusCodes.Status404NotFound)] | ||
| [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||
| public async Task<IActionResult> GetById(Guid id) | ||
| { | ||
| var user = await _identityService.GetUserByIdAsync(id); | ||
| if (user == null) | ||
| return NotFound(); | ||
| return Ok(user); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| using System.IdentityModel.Tokens.Jwt; | ||
| using System.Security.Claims; | ||
| using System.Text; | ||
| using Identity.Domain.DTOs; | ||
| using Identity.Domain.Entities; | ||
| using Identity.Domain.Interfaces; | ||
| using Identity.Infrastructure.Data; | ||
| using Microsoft.EntityFrameworkCore; | ||
| using Microsoft.Extensions.Configuration; | ||
| using Microsoft.IdentityModel.Tokens; | ||
|
|
||
| namespace Identity.Infrastructure.Services; | ||
|
|
||
| public class IdentityService : IIdentityService | ||
| { | ||
| private readonly IdentityDbContext _context; | ||
| private readonly IConfiguration _configuration; | ||
|
|
||
| public IdentityService(IdentityDbContext context, IConfiguration configuration) | ||
| { | ||
| _context = context; | ||
| _configuration = configuration; | ||
| } | ||
|
|
||
| public async Task<RegisterResult> RegisterAsync(RegisterRequest request) | ||
| { | ||
| if (await _context.Users.AnyAsync(u => u.UserName == request.UserName)) | ||
| { | ||
| return new RegisterResult { Success = false, ErrorMessage = "Username is already taken." }; | ||
| } | ||
|
|
||
| if (await _context.Users.AnyAsync(u => u.Email == request.Email)) | ||
| { | ||
| return new RegisterResult { Success = false, ErrorMessage = "Email is already registered." }; | ||
| } | ||
|
|
||
| var user = new AppUser | ||
| { | ||
| Id = Guid.NewGuid(), | ||
| UserName = request.UserName, | ||
| Email = request.Email, | ||
| PasswordHash = BCrypt.Net.BCrypt.HashPassword(request.Password), | ||
| FullName = request.FullName, | ||
| JobTitle = request.JobTitle, | ||
| IsEnabled = true, | ||
| CreatedAt = DateTime.UtcNow, | ||
| UpdatedAt = DateTime.UtcNow | ||
| }; | ||
|
|
||
| _context.Users.Add(user); | ||
| await _context.SaveChangesAsync(); | ||
|
|
||
| return new RegisterResult | ||
| { | ||
| Success = true, | ||
| User = MapToDto(user) | ||
| }; | ||
| } | ||
|
|
||
| public async Task<LoginResult> LoginAsync(LoginRequest request) | ||
| { | ||
| var user = await _context.Users.FirstOrDefaultAsync(u => u.UserName == request.UserName); | ||
|
|
||
| if (user == null || !BCrypt.Net.BCrypt.Verify(request.Password, user.PasswordHash)) | ||
| { | ||
| return new LoginResult { Success = false, ErrorMessage = "Invalid username or password." }; | ||
| } | ||
|
|
||
| if (!user.IsEnabled) | ||
| { | ||
| return new LoginResult { Success = false, ErrorMessage = "This account has been disabled." }; | ||
| } | ||
|
Comment on lines
+64
to
+72
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🚩 Login verifies password before checking if account is disabled In Was this helpful? React with 👍 or 👎 to provide feedback.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is intentional UX — a legitimate user whose account was disabled should see a clear "account disabled" message rather than a generic credentials error (which would lead them to think they mistyped their password). The information disclosure tradeoff is acceptable here since username enumeration is already possible via the register endpoint's uniqueness check. The BCrypt cost on disabled accounts is negligible in practice. |
||
|
|
||
| var token = GenerateJwtToken(user); | ||
|
|
||
| return new LoginResult { Success = true, Token = token }; | ||
| } | ||
|
|
||
| public async Task<AppUserDto?> GetUserByIdAsync(Guid id) | ||
| { | ||
| var user = await _context.Users.FindAsync(id); | ||
| return user == null ? null : MapToDto(user); | ||
| } | ||
|
|
||
| public async Task<IEnumerable<AppUserDto>> GetAllUsersAsync() | ||
| { | ||
| var users = await _context.Users.ToListAsync(); | ||
| return users.Select(MapToDto); | ||
| } | ||
|
Comment on lines
+85
to
+89
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🚩 GetAllUsersAsync loads entire user table into memory without pagination The Was this helpful? React with 👍 or 👎 to provide feedback.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Acknowledged — this is a known limitation for now. Pagination would require changes to the |
||
|
|
||
| private string GenerateJwtToken(AppUser user) | ||
| { | ||
| var secret = _configuration["Jwt:Secret"]!; | ||
| var issuer = _configuration["Jwt:Issuer"]; | ||
| var audience = _configuration["Jwt:Audience"]; | ||
| var expirationMinutes = int.Parse(_configuration["Jwt:ExpirationMinutes"]!); | ||
|
|
||
| var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)); | ||
| var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); | ||
|
|
||
| var claims = new[] | ||
| { | ||
| new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()), | ||
| new Claim(JwtRegisteredClaimNames.Name, user.UserName), | ||
| new Claim(JwtRegisteredClaimNames.Email, user.Email), | ||
| new Claim(ClaimTypes.Role, "User") | ||
| }; | ||
|
|
||
| var token = new JwtSecurityToken( | ||
| issuer: issuer, | ||
| audience: audience, | ||
| claims: claims, | ||
| expires: DateTime.UtcNow.AddMinutes(expirationMinutes), | ||
| signingCredentials: credentials); | ||
|
|
||
| return new JwtSecurityTokenHandler().WriteToken(token); | ||
| } | ||
|
|
||
| private static AppUserDto MapToDto(AppUser user) | ||
| { | ||
| return new AppUserDto | ||
| { | ||
| Id = user.Id, | ||
| UserName = user.UserName, | ||
| Email = user.Email, | ||
| FullName = user.FullName, | ||
| JobTitle = user.JobTitle, | ||
| IsEnabled = user.IsEnabled | ||
| }; | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.