|
| 1 | +namespace NorthwindCRUD.Controllers |
| 2 | +{ |
| 3 | + using AutoMapper; |
| 4 | + using Microsoft.AspNetCore.Authorization; |
| 5 | + using Microsoft.AspNetCore.Mvc; |
| 6 | + using NorthwindCRUD.Models.DbModels; |
| 7 | + using NorthwindCRUD.Models.InputModels; |
| 8 | + using NorthwindCRUD.Services; |
| 9 | + |
| 10 | + [ApiController] |
| 11 | + [Route("[controller]")] |
| 12 | + public class AuthController : Controller |
| 13 | + { |
| 14 | + private readonly IConfiguration configuration; |
| 15 | + private readonly AuthService authService; |
| 16 | + private readonly IMapper mapper; |
| 17 | + private readonly ILogger logger; |
| 18 | + |
| 19 | + public AuthController(IConfiguration configuration, AuthService authService, IMapper mapper, ILogger logger) |
| 20 | + { |
| 21 | + this.configuration = configuration; |
| 22 | + this.authService = authService; |
| 23 | + this.mapper = mapper; |
| 24 | + this.logger = logger; |
| 25 | + } |
| 26 | + |
| 27 | + [AllowAnonymous] |
| 28 | + [HttpPost("Login")] |
| 29 | + public ActionResult<string> Login(LoginInputModel userModel) |
| 30 | + { |
| 31 | + try |
| 32 | + { |
| 33 | + if (ModelState.IsValid) |
| 34 | + { |
| 35 | + if (this.authService.IsAuthenticated(userModel.Email, userModel.Password)) |
| 36 | + { |
| 37 | + var token = this.authService.GenerateJwtToken(userModel.Email); |
| 38 | + |
| 39 | + return Ok(token); |
| 40 | + } |
| 41 | + return BadRequest("Email or password are not correct!"); |
| 42 | + } |
| 43 | + |
| 44 | + return BadRequest(ModelState); |
| 45 | + } |
| 46 | + catch (Exception error) |
| 47 | + { |
| 48 | + logger.LogError(error.Message); |
| 49 | + return StatusCode(500); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + [AllowAnonymous] |
| 54 | + [HttpPost("Register")] |
| 55 | + public ActionResult<string> Register(RegisterInputModel userModel) |
| 56 | + { |
| 57 | + try |
| 58 | + { |
| 59 | + if (ModelState.IsValid) |
| 60 | + { |
| 61 | + if (userModel.Password != userModel.ConfirmedPassword) |
| 62 | + { |
| 63 | + return BadRequest("Passwords does not match!"); |
| 64 | + } |
| 65 | + |
| 66 | + if (this.authService.DoesUserExists(userModel.Email)) |
| 67 | + { |
| 68 | + return BadRequest("User does not exists!"); |
| 69 | + } |
| 70 | + |
| 71 | + var mappedModel = this.mapper.Map<RegisterInputModel, UserDb>(userModel); |
| 72 | + var user = this.authService.RegisterUser(mappedModel); |
| 73 | + |
| 74 | + if (user != null) |
| 75 | + { |
| 76 | + var token = this.authService.GenerateJwtToken(user.Email); |
| 77 | + return Ok(token); |
| 78 | + |
| 79 | + } |
| 80 | + |
| 81 | + return BadRequest("Email or password are not correct!"); |
| 82 | + } |
| 83 | + |
| 84 | + return BadRequest(ModelState); |
| 85 | + } |
| 86 | + catch (Exception error) |
| 87 | + { |
| 88 | + logger.LogError(error.Message); |
| 89 | + return StatusCode(500); |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | +} |
0 commit comments