Repository navigation
Expand file tree
/
Copy pathAuthController.cs
More file actions
92 lines (76 loc) · 3.36 KB
/
Copy pathAuthController.cs
File metadata and controls
92 lines (76 loc) · 3.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using csvLinter.Api.Data;
using csvLinter.Api.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
namespace csvLinter.Api.Controllers
{
/// <summary>
/// Handles user registration and login, issuing JWTs for authenticated users.
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private static readonly PasswordHasher<User> PasswordHasher = new();
private readonly AppDbContext _dbContext;
private readonly IConfiguration _configuration;
public AuthController(AppDbContext dbContext, IConfiguration configuration)
{
_dbContext = dbContext;
_configuration = configuration;
}
[HttpPost("register")]
public async Task<IActionResult> Register(RegisterRequest request)
{
if (string.IsNullOrWhiteSpace(request.Username) || string.IsNullOrWhiteSpace(request.Password))
{
return BadRequest("Username and password are required.");
}
bool usernameTaken = await _dbContext.Users.AnyAsync(u => u.Username == request.Username);
if (usernameTaken)
{
return Conflict("Username is already taken.");
}
var user = new User { Username = request.Username, PasswordHash = string.Empty };
user.PasswordHash = PasswordHasher.HashPassword(user, request.Password);
_dbContext.Users.Add(user);
await _dbContext.SaveChangesAsync();
return Created(string.Empty, new { user.Id, user.Username });
}
[HttpPost("login")]
public async Task<IActionResult> Login(LoginRequest request)
{
if (string.IsNullOrWhiteSpace(request.Username) || string.IsNullOrWhiteSpace(request.Password))
{
return BadRequest("Username and password are required.");
}
var user = await _dbContext.Users.SingleOrDefaultAsync(u => u.Username == request.Username);
if (user == null)
{
return Unauthorized("Invalid username or password.");
}
var verificationResult = PasswordHasher.VerifyHashedPassword(user, user.PasswordHash, request.Password);
if (verificationResult == PasswordVerificationResult.Failed)
{
return Unauthorized("Invalid username or password.");
}
var expires = DateTime.UtcNow.AddHours(1);
var jwtSection = _configuration.GetSection("Jwt");
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSection["Key"]!));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: jwtSection["Issuer"],
audience: jwtSection["Audience"],
claims: new[] { new Claim(ClaimTypes.Name, user.Username) },
expires: expires,
signingCredentials: credentials);
return Ok(new LoginResponse(new JwtSecurityTokenHandler().WriteToken(token), expires));
}
}
}