Add controller for login

This commit is contained in:
2025-04-20 18:51:13 +02:00
parent 9696d53114
commit bcb641d430
8 changed files with 71 additions and 21 deletions

View File

@@ -0,0 +1,54 @@
using GameIdeas.Resources;
using GameIdeas.Shared.Constants;
using GameIdeas.Shared.Dto;
using GameIdeas.Shared.Model;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace GameIdeas.WebAPI.Controllers;
public class UserController(UserManager<User> userManager) : Controller
{
[HttpPost("login")]
public async Task<ActionResult<TokenDto>> Login([FromBody] UserDto model)
{
if (model.Username == null || model.Password == null)
throw new ArgumentNullException(paramName: nameof(model), ResourcesKey.UserArgumentsNull);
var user = await userManager.FindByNameAsync(model.Username);
if (user != null && await userManager.CheckPasswordAsync(user, model.Password))
{
List<Claim> authClaims =
[
new Claim(ClaimTypes.Name, user.UserName ?? string.Empty),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
];
var jwtKey = Environment.GetEnvironmentVariable("JWT_KEY")
?? throw new ArgumentNullException(message: ResourcesKey.InvalidToken, null);
var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey));
var token = new JwtSecurityToken(
issuer: Environment.GetEnvironmentVariable("JWT_ISSUER"),
audience: Environment.GetEnvironmentVariable("JWT_AUDIENCE"),
expires: DateTime.Now.AddHours(GlobalConstants.JWT_DURATION_HOUR),
claims: authClaims,
signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
);
return Ok(new TokenDto
{
Token = new JwtSecurityTokenHandler().WriteToken(token),
Expiration = token.ValidTo
});
}
return Unauthorized();
}
}