93 lines
2.3 KiB
C#
93 lines
2.3 KiB
C#
using API.DTO.Base;
|
|
using API.DTO.Login;
|
|
using API.Errors;
|
|
using API.Services;
|
|
using API.Services.Interfaces;
|
|
using DAL.Models;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using System.Security.Claims;
|
|
|
|
namespace API.Controllers
|
|
{
|
|
[ApiController]
|
|
[Route("api/v1/[controller]")]
|
|
public class AuthController : ControllerBase
|
|
{
|
|
private readonly ILogger<AuthController> _logger;
|
|
private readonly IUserManager _userManager;
|
|
private readonly UserService _userService;
|
|
|
|
public AuthController(ILogger<AuthController> logger, IUserManager userManager, UserService userService)
|
|
{
|
|
_logger = logger;
|
|
_userManager = userManager;
|
|
_userService = userService;
|
|
}
|
|
|
|
[HttpPost("login")]
|
|
public ActionResult<UserDTO> login(UserLoginDTO userLogin)
|
|
{
|
|
UserDTO? user = _userManager.authenticateUser(userLogin);
|
|
if (user == null)
|
|
return new UnauthorizedResult();
|
|
|
|
Claim[] claims =
|
|
{
|
|
new Claim(ClaimTypes.NameIdentifier, user.id.ToString())
|
|
};
|
|
|
|
ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
|
|
|
|
//todo confirm if this is accurate
|
|
AuthenticationProperties authProperties = new AuthenticationProperties();
|
|
|
|
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
|
|
|
|
return Ok(user);
|
|
}
|
|
|
|
[HttpPost("register")]
|
|
public ActionResult<UserDTO> register(UserRegisterDTO registerDTO, ulong? permissionId = null)
|
|
{
|
|
if (registerDTO.password == null)
|
|
registerDTO.password = registerDTO.phoneNumber;
|
|
|
|
if (permissionId != null)
|
|
{
|
|
User? user = getUser(User);
|
|
if (user == null)
|
|
return Unauthorized();
|
|
|
|
UserDTO? createdUser = _userManager.registerUser(registerDTO, user, permissionId);
|
|
if (createdUser == null)
|
|
return Conflict(Strings.UserExists);
|
|
|
|
return Ok(createdUser);
|
|
}
|
|
else {
|
|
UserDTO? user = _userManager.registerUser(registerDTO);
|
|
|
|
if (user == null)
|
|
{
|
|
return Conflict(Strings.UserExists);
|
|
}
|
|
|
|
return Ok(user);
|
|
}
|
|
}
|
|
|
|
[NonAction]
|
|
public User? getUser(ClaimsPrincipal user)
|
|
{
|
|
Claim? idClaim = user.FindFirst(ClaimTypes.NameIdentifier);
|
|
|
|
if (idClaim == null)
|
|
return null;
|
|
|
|
return _userService.getNoAuthentication(UInt64.Parse(idClaim.Value));
|
|
}
|
|
}
|
|
}
|