public async Task <ActionResult <LoginRegisterUserOutputDTO> > Login(LoginUserDTO loginUser) { AppUser appUser = await _context.Users .Include(user => user.Photos) .FirstOrDefaultAsync(user => user.UserName == loginUser.UserName.ToLower()); if (appUser == null) { return(Unauthorized("User doesn't exist!!")); } using var hmac = new HMACSHA512(appUser.PasswordSalt); byte[] computedHash = await hmac.ComputeHashAsync(new MemoryStream(Encoding.UTF8.GetBytes(loginUser.Password))); for (int i = 0; i < computedHash.Length; i++) { if (computedHash[i] != appUser.PasswordHash[i]) { return(Unauthorized("Incorrect password!!")); } } return(new LoginRegisterUserOutputDTO { UserName = appUser.UserName, Token = _tokenService.CreateToken(appUser), PhotoUrl = appUser.Photos.FirstOrDefault(x => x.IsMain)?.Url, KnownAs = appUser.KnownAs, Gender = appUser.Gender }); }
public async Task <ActionResult <LoginRegisterUserOutputDTO> > Register(RegisterUserDTO registerUser) { if (await ExistsUser(registerUser.UserName)) { return(BadRequest("Username has been already used")); } using var hmac = new HMACSHA512(); AppUser appUser = _mapper.Map <AppUser>(registerUser); appUser.UserName = registerUser.UserName.ToLower(); appUser.PasswordHash = await hmac.ComputeHashAsync(new MemoryStream(Encoding.UTF8.GetBytes(registerUser.Password))); appUser.PasswordSalt = hmac.Key; _context.Add(appUser); await _context.SaveChangesAsync(); return(new LoginRegisterUserOutputDTO { UserName = appUser.UserName, Token = _tokenService.CreateToken(appUser), KnownAs = appUser.KnownAs, Gender = appUser.Gender }); }
public static async Task SeedUsers(DataContext context) { if (await context.Users.AnyAsync()) { return; } var userData = await System.IO.File.ReadAllTextAsync("Data/UserSeedData.json"); var users = JsonSerializer.Deserialize <List <AppUser> >(userData); foreach (AppUser user in users) { using var hmac = new HMACSHA512(); user.UserName = user.UserName.ToLower(); user.PasswordHash = await hmac.ComputeHashAsync(new MemoryStream(Encoding.UTF8.GetBytes("123456"))); user.PasswordSalt = hmac.Key; await context.AddAsync(user); } await context.SaveChangesAsync(); }
public Task <byte[]> Hash(string password, byte[] salt) { var bytes = Encoding.UTF8.GetBytes(password); var allBytes = new byte[bytes.Length + salt.Length]; Buffer.BlockCopy(bytes, 0, allBytes, 0, bytes.Length); Buffer.BlockCopy(salt, 0, allBytes, bytes.Length, salt.Length); return(x.ComputeHashAsync(new MemoryStream(allBytes))); }