Advertisement
onzulin

Registro de usuarios en ASP.NET 5 Web Api

Oct 29th, 2021
890
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.92 KB | None | 0 0
  1. /* Estoy registrando usuarios con este código y bueno lo que no funciona es las fechas con DateTime.Now y ademas me lo registra el usuario
  2.    Desde el Id 2 cosa que no entiendo pero eso es menos importante.
  3. */
  4. AuthRepository.cs
  5. using JWTGymApi.Datos.Data.Repository.Interfaces;
  6. using JWTGymApi.Models;
  7. using Microsoft.EntityFrameworkCore;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13.  
  14. namespace JWTGymApi.Datos.Data.Repository
  15. {
  16.     public class AuthRepository : IAuthRepository
  17.     {
  18.         private readonly GymDbContext _context;
  19.         public AuthRepository(GymDbContext context)
  20.         {
  21.             _context = context;
  22.         }
  23.         public async Task<User> Login(string email, string password)
  24.         {
  25.             var user = await _context.Users.FirstOrDefaultAsync(x => x.Email == email);
  26.             if (user == null)
  27.                 return null;
  28.             //quiero poner para verificar el hash pero bueno necesito tal vez un salt para el usuario
  29.             //if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
  30.             return user;
  31.         }
  32.         private bool VerifyPasswordHash(string password, byte[] passwordhash, byte[] passwordSalt)
  33.         {
  34.             using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
  35.             {
  36.                 var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
  37.                 for (int i = 0; i< computedHash.Length; i++)
  38.                 {
  39.                     if (computedHash[i] != passwordhash[i]) return false;
  40.                 }
  41.                 return true;
  42.             }
  43.         }
  44.         public async Task<User> Register(User user, string password)
  45.         {
  46.             byte[] passwordHash;
  47.             byte[] passwordSalt;
  48.             DateTime CreateAt = DateTime.Now;
  49.             DateTime UpdateAt = DateTime.Now;
  50.             CreatePasswordHash(password, out passwordHash, out passwordSalt);
  51.             user.PasswordHash = passwordHash;
  52.             user.PasswordSalt = passwordSalt;
  53.             //ponemos lo de las fechas
  54.             user.CreationDateTime = CreateAt;
  55.             user.LastUpdateDateTime = UpdateAt;
  56.  
  57.             await _context.Users.AddAsync(user);
  58.             await _context.SaveChangesAsync();
  59.             return user;
  60.         }
  61.         /// <summary>
  62.         /// Create a password hash with own password.
  63.         /// Crea un password hash con nuestro password.
  64.         /// </summary>
  65.         /// <param name="password"></param>
  66.         /// <param name="passwordHash"></param>
  67.         /// <param name="passwordSalt"></param>
  68.         private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
  69.         {
  70.             using (var hmac = new System.Security.Cryptography.HMACSHA512())
  71.             {
  72.                 passwordSalt = hmac.Key;
  73.                 passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
  74.             }
  75.         }
  76.  
  77.         public async Task<bool> UserExist(string email)
  78.         {
  79.             if (await _context.Users.AnyAsync(x => x.Email == email))
  80.             {
  81.                 return true;
  82.             }
  83.             else
  84.             {
  85.                 return false;
  86.             }
  87.         }
  88.  
  89.         public Task<User> Register(UserDto user, string password)
  90.         {
  91.             throw new NotImplementedException();
  92.         }
  93.     }
  94. }
  95.  
  96. AuthController.cs
  97. using AutoMapper;
  98. using JWTGymApi.Datos;
  99. using JWTGymApi.Datos.Data.Repository.Interfaces;
  100. using JWTGymApi.Datos.Data.Services.Interfaces;
  101. using JWTGymApi.Models;
  102. using Microsoft.AspNetCore.Http;
  103. using Microsoft.AspNetCore.Mvc;
  104. using System;
  105. using System.Collections.Generic;
  106. using System.Linq;
  107. using System.Threading.Tasks;
  108.  
  109. namespace JWTGymApi.Controllers
  110. {
  111.     [Route("api/[controller]")]
  112.     [ApiController]
  113.     public class AuthController : ControllerBase
  114.     {
  115.         private readonly IAuthRepository _repo;
  116.         private readonly ITokenService _tokenService;
  117.         private readonly IMapper _mapper;
  118.         private readonly GymDbContext _context;
  119.  
  120.         //Esto lo voy a hacer posteriormente el mapeo de las Dto que las pienso configurar
  121.         //private readonly IMapper _mapper;
  122.         //Las variables puestas en AuthController son para realizar la inyeccion de los servicios que necesitamos
  123.         public AuthController(IAuthRepository repo, ITokenService tokenService, IMapper mapper, GymDbContext context)
  124.         {
  125.             _repo = repo;
  126.             _tokenService = tokenService;
  127.             _mapper = mapper;
  128.             _context = context;
  129.  
  130.         }
  131.         //la idea de los Dto es para este método según el curso tutorial de cacmis que estoy desarrollando, pero
  132.         //a mi no me convence la verdad.
  133.         [HttpPost("Register")]
  134.         public async Task<IActionResult> Register(UserDto user)
  135.         {
  136.             //poner el email del usuario en minuscula
  137.             user.Email = user.Email.ToLower();
  138.             if (await _repo.UserExist(user.Email))
  139.                 return BadRequest("Usuario con ese email ya esta registrado");
  140.             var userNew = _mapper.Map<User>(user);
  141.             var userCreate = await _repo.Register(userNew, user.Password);
  142.             var userReturn = _mapper.Map<User>(userCreate);
  143.             return Ok(userReturn);        
  144.         }
  145.         [HttpPost("Login")]
  146.         public async Task<IActionResult> Login(UserLoginDto userLogin)
  147.         {
  148.             var userRepo = await _repo.Login(userLogin.Email, userLogin.Password);
  149.             if (userRepo == null)
  150.                 return Unauthorized();
  151.             var user = _mapper.Map<User>(userRepo);
  152.  
  153.             var token = _tokenService.CreateToken(userRepo);
  154.  
  155.             return Ok(new
  156.             {
  157.                 token = token,
  158.                 user = userRepo
  159.             });
  160.         }
  161.     }
  162. }
  163.  
  164.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement