add auth files
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
This commit is contained in:
62
api/src/Controllers/AuthController.cs
Normal file
62
api/src/Controllers/AuthController.cs
Normal file
@@ -0,0 +1,62 @@
|
||||
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
using agologumApi.Models;
|
||||
using agologumApi.Services;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class AuthController : ControllerBase {
|
||||
|
||||
private readonly UserService users_;
|
||||
private readonly JwtService jwt_;
|
||||
|
||||
public AuthController(UserService users, JwtService jwt)
|
||||
{
|
||||
users_ = users;
|
||||
jwt_ = jwt;
|
||||
}
|
||||
|
||||
[HttpPost("register")]
|
||||
public async Task<ActionResult> Register(RegisterDto dto) {
|
||||
var user = new User {
|
||||
Name = dto.Username,
|
||||
PasswordHash = BCrypt.Net.BCrypt.HashPassword(dto.Password) // TODO: hashing stage in client
|
||||
};
|
||||
|
||||
var newUser = await users_.Create(user);
|
||||
return CreatedAtAction(
|
||||
nameof(Register),
|
||||
new { id = newUser.Id },
|
||||
user
|
||||
);
|
||||
}
|
||||
|
||||
[HttpPost("login")]
|
||||
public async Task<ActionResult> Login(LoginDto dto)
|
||||
{
|
||||
var user = await users_.Get(dto.Username);
|
||||
|
||||
if (user == null || !BCrypt.Net.BCrypt.Verify(dto.Password, user.PasswordHash)) {
|
||||
return Unauthorized();
|
||||
}
|
||||
|
||||
var token = jwt_.GenerateJwt(user);
|
||||
|
||||
return Ok(new { token });
|
||||
}
|
||||
|
||||
[Authorize] // authorize is handled by middleware
|
||||
[HttpPost("logout")]
|
||||
public ActionResult Logout() {
|
||||
// dummy endpoint
|
||||
// logout happens upon client-side jwt removal
|
||||
return Ok();
|
||||
}
|
||||
|
||||
// TODO
|
||||
// refresh tokens
|
||||
// email verification
|
||||
// password reset
|
||||
}
|
||||
Reference in New Issue
Block a user