-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthController.cs
More file actions
66 lines (60 loc) · 2.24 KB
/
Copy pathAuthController.cs
File metadata and controls
66 lines (60 loc) · 2.24 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
using GameCollectionAPI.DTOs;
using GameCollectionAPI.Exceptions;
using GameCollectionAPI.Services;
using Microsoft.AspNetCore.Mvc;
namespace GameCollectionAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private IAuthService _authService;
public AuthController(IAuthService authService)
{
_authService = authService;
}
/// <summary>
/// Registers a new user.
/// </summary>
/// <param name="authDto">Authentication DTO containing user details.</param>
/// <returns>The created user.</returns>
[HttpPost("Register")]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<IActionResult> Register([FromBody] AuthDto authDto)
{
if (authDto == null) { return BadRequest(); }
try
{
var createdUser = await _authService.RegisterUserAsync(authDto);
return CreatedAtRoute("GetUserById", new { id = createdUser.Id }, createdUser);
}
catch (DuplicateUsernameException ex)
{
return Conflict(new { message = ex.Message });
}
}
/// <summary>
/// Logs in a user and returns a JWT token.
/// </summary>
/// <param name="authDto">Authentication DTO containing user credentials.</param>
/// <returns>A JWT token if credentials are valid; Unauthorized otherwise.</returns>
[HttpPost("Login")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Login([FromBody] AuthDto authDto)
{
if (authDto == null) { return BadRequest(); }
try
{
var token = await _authService.LoginUserAsync(authDto);
return Ok(new { jwt = token });
}
catch (InvalidDataException)
{
return Unauthorized(new { message = "Invalid credentials" });
}
}
}
}