75 lines
2.5 KiB
C#
75 lines
2.5 KiB
C#
using Metrolog_API.Models;
|
|
using Metrolog_API.Services;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
|
|
|
|
namespace Metrolog_API.Controllers
|
|
{
|
|
[Route("api/[controller]")]
|
|
[ApiController]
|
|
public class AuthController : ControllerBase
|
|
{
|
|
private UserService _UserService;
|
|
private RoleService _RoleService;
|
|
private PasswordService _PasswordService;
|
|
private JWTService _JwtService;
|
|
private int _JwtExpirationMinutes;
|
|
|
|
public AuthController(UserService userService, RoleService roleService, PasswordService passwordService, JWTService jwtService)
|
|
{
|
|
_UserService = userService;
|
|
_RoleService = roleService;
|
|
_PasswordService = passwordService;
|
|
_JwtService = jwtService;
|
|
_JwtExpirationMinutes = int.Parse(System.Environment.GetEnvironmentVariable("JWT_EXPIRATION_MINUTES"));
|
|
}
|
|
|
|
// POST api/<AuthController>/active
|
|
[HttpGet("active")]
|
|
public async Task<ActionResult> Get()
|
|
{
|
|
return NotFound();
|
|
}
|
|
|
|
// POST api/<AuthController>/login
|
|
[HttpPost("login")]
|
|
public async Task<ActionResult<LoginResponseModel>> LoginPost([FromBody] LoginModel login)
|
|
{
|
|
UserModel? user = await _UserService.GetByEmailAsync(login.Email);
|
|
|
|
if (user == null || !_PasswordService.VerifyPassword(user.Password, login.Password)) //Verify user
|
|
return NotFound(); //If user not exist or provide bad password return NotFound(404)
|
|
|
|
return Ok(new LoginResponseModel{ Token = await _JwtService.GenerateUserJwtToken(user), TokenExpire = DateTime.Now.AddMinutes(_JwtExpirationMinutes) });
|
|
}
|
|
|
|
// POST api/<AuthController>/register
|
|
[HttpPost("register")]
|
|
public async Task<ActionResult> RegisterPost([FromBody] RegisterModel register)
|
|
{
|
|
if (register == null || string.IsNullOrEmpty(register.Name) || string.IsNullOrEmpty(register.Surname) || string.IsNullOrEmpty(register.Email) || string.IsNullOrEmpty(register.Password))
|
|
return BadRequest("Input data Error");
|
|
|
|
if (await _UserService.GetByEmailAsync(register.Email) != null)
|
|
return BadRequest("Email is already used");
|
|
|
|
UserModel user = new UserModel()
|
|
{
|
|
TitlesFrontName = "",
|
|
TitlesBehindName = "",
|
|
Name = register.Name,
|
|
Surname = register.Surname,
|
|
Email = register.Email,
|
|
Password = _PasswordService.HashPassword(register.Password),
|
|
Roles = await _RoleService.GetDefaultsAsync()
|
|
};
|
|
|
|
await _UserService.CreateAsync(user);
|
|
|
|
return Ok("Register succes, Please login");
|
|
}
|
|
|
|
}
|
|
}
|