Auth endpoints are now functional
This commit is contained in:
77
src/IO.Swagger/Repositories/UserRepository.cs
Normal file
77
src/IO.Swagger/Repositories/UserRepository.cs
Normal file
@ -0,0 +1,77 @@
|
||||
using IO.Swagger.Models.db;
|
||||
using System.Security.Cryptography;
|
||||
using System;
|
||||
using IO.Swagger.Services;
|
||||
using IO.Swagger.Models.dto;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Linq;
|
||||
|
||||
namespace IO.Swagger.Repositories
|
||||
{
|
||||
public class UserRepository : IUserRepository
|
||||
{
|
||||
private readonly BankDbContext bankDbContext;
|
||||
|
||||
public UserRepository(BankDbContext bankDbContext)
|
||||
{
|
||||
this.bankDbContext = bankDbContext;
|
||||
}
|
||||
|
||||
public async Task<User> RegisterUser(AuthRegisterBody request)
|
||||
{
|
||||
request.Email = request.Email.ToLower();
|
||||
if (await bankDbContext.Users.CountAsync((User u) => u.Email == request.Email) > 0)
|
||||
return null;
|
||||
|
||||
// Generate a random salt
|
||||
byte[] saltBytes = new byte[16];
|
||||
new RNGCryptoServiceProvider().GetBytes(saltBytes);
|
||||
string salt = Convert.ToBase64String(saltBytes);
|
||||
|
||||
// Hash the password along with the salt
|
||||
string password = request.Password;
|
||||
string saltedPassword = password + salt;
|
||||
byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(saltedPassword);
|
||||
byte[] hashedBytes = new SHA256Managed().ComputeHash(passwordBytes);
|
||||
string hashedPassword = Convert.ToBase64String(hashedBytes);
|
||||
|
||||
// Create and insert the user
|
||||
var newUser = new User
|
||||
{
|
||||
PasswordHash = hashedPassword,
|
||||
Salt = salt,
|
||||
Email = request.Email,
|
||||
FirstName = request.FirstName,
|
||||
LastName = request.LastName
|
||||
};
|
||||
|
||||
await bankDbContext.Users.AddAsync(newUser);
|
||||
await bankDbContext.SaveChangesAsync();
|
||||
return newUser;
|
||||
}
|
||||
|
||||
public async Task<User> LoginUser(AuthLoginBody request)
|
||||
{
|
||||
request.Email = request.Email.ToLower();
|
||||
var user = await bankDbContext.Users.FirstOrDefaultAsync(u => u.Email.Equals(request.Email));
|
||||
if (user == null)
|
||||
return null;
|
||||
|
||||
// Hash the supplied password with the retrieved salt
|
||||
string password = request.Password;
|
||||
string saltedPassword = password + user.Salt;
|
||||
byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(saltedPassword);
|
||||
byte[] hashedBytes = new SHA256Managed().ComputeHash(passwordBytes);
|
||||
string hashedPassword = Convert.ToBase64String(hashedBytes);
|
||||
if (hashedPassword != user.PasswordHash)
|
||||
return null;
|
||||
return user;
|
||||
}
|
||||
|
||||
public async Task<User> RetrieveUser(int userId)
|
||||
{
|
||||
return await bankDbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user