· 4 years ago · Jul 20, 2021, 08:32 PM
1using Microsoft.AspNetCore.Http;
2using Microsoft.AspNetCore.Identity;
3using Microsoft.AspNetCore.Mvc;
4using Microsoft.EntityFrameworkCore;
5using Microsoft.IdentityModel.Tokens;
6using MyLibrus.Entities;
7using MyLibrus.Entities.DTO.CreateDTO;
8using MyLibrus.Tables;
9using System;
10using System.Collections.Generic;
11using System.IdentityModel.Tokens.Jwt;
12using System.Linq;
13using System.Security.Claims;
14using System.Text;
15using System.Threading.Tasks;
16
17namespace MyLibrus.Controllers
18{
19 [Route("api/account")]
20 [ApiController]
21 public class AccountController : ControllerBase
22 {
23 private readonly MyLibrusDbContext _myLibrusDbContext;
24 private readonly IPasswordHasher<User> _hasher;
25 private readonly AuthenticationSettins _authenticationSettins;
26
27 public AccountController(MyLibrusDbContext myLibrusDbContext, IPasswordHasher<User> hasher, AuthenticationSettins authenticationSettings)
28 {
29 _myLibrusDbContext = myLibrusDbContext;
30 _hasher = hasher;
31 _authenticationSettins = authenticationSettings;
32 }
33
34 [HttpPost("login")]
35 public string Login([FromBody] LoginDTO loginDTO)
36 {
37 //this logic has to be move into service
38 var user = _myLibrusDbContext.Users
39 .Include(x => x.Role)
40 .FirstOrDefault(x => x.Mail == loginDTO.Email);
41
42
43 // logic if user exist
44
45 //check if password is okey
46 var result = _hasher.VerifyHashedPassword(user, user.PasswordHashed, loginDTO.Password);
47 if(result == PasswordVerificationResult.Failed)
48 {
49 throw new BadHttpRequestException("Bad password or username");
50 }
51
52 var claims = new List<Claim>()
53 {
54 new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
55 new Claim(ClaimTypes.Name, $"{user.FirstName} {user.LastName}"),
56 new Claim(ClaimTypes.Role, user.Role.RoleName),
57 new Claim("email", user.Mail.ToString()),
58 };
59
60 //here we generate private key
61 var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_authenticationSettins.JwtKey));
62 //here we generate credencials
63 var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
64 //here we generate expires time of token
65 var expires = DateTime.Now.AddDays(_authenticationSettins.JwtExpireDays);
66 // issuer, audience( clients of api)
67 var token = new JwtSecurityToken(
68 _authenticationSettins.JwtIssuer,
69 _authenticationSettins.JwtIssuer,
70 claims,
71 expires: expires,
72 signingCredentials: cred);
73
74 var tokenHandler = new JwtSecurityTokenHandler();
75
76 return tokenHandler.WriteToken(token);
77 }
78
79 [HttpPost]
80 public void CreateUser([FromBody] CreateUserDTO createUserDTO)
81 {
82 var user = new User
83 {
84 FirstName = createUserDTO.FirstName,
85 LastName = createUserDTO.LastName,
86 Mail = createUserDTO.Mail,
87 RoleId = createUserDTO.RoleId
88 };
89
90 // here we hash our password, which comes from DTO
91 var passwordAfterHashed = _hasher.HashPassword(user, createUserDTO.Password);
92 // here we assign this password to orginal user entity
93 user.PasswordHashed = passwordAfterHashed;
94
95 _myLibrusDbContext.Users.Add(user);
96 _myLibrusDbContext.SaveChanges();
97 }
98 }
99}
100