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//active [HttpGet("active")] public async Task Get() { return NotFound(); } // POST api//login [HttpPost("login")] public async Task> 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//register [HttpPost("register")] public async Task 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"); } } }