Added a way to login and register and a tools project

This commit is contained in:
2019-05-06 13:12:35 -04:00
parent 8e4e504fd8
commit a4cf928fe0
15 changed files with 231 additions and 31 deletions

View File

@@ -4,10 +4,6 @@
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Folder Include="Interfaces\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MediatR" Version="6.0.0" />
</ItemGroup>

View File

@@ -0,0 +1,14 @@
using BrightGlimmer.Domain.Auth;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace BrightGlimmer.Service.Interfaces
{
public interface IUserService
{
string Login(string username, string password);
Task<string> RegisterAsync(User user, string password);
}
}

View File

@@ -0,0 +1,55 @@
using BrightGlimmer.Data;
using BrightGlimmer.Domain.Auth;
using BrightGlimmer.Service.Interfaces;
using BrightGlimmer.Tools;
using Microsoft.Extensions.Configuration;
using System.Linq;
using System.Threading.Tasks;
namespace BrightGlimmer.Service.Services
{
public class UserService : IUserService
{
private readonly IConfiguration configuration;
private readonly AuthContext context;
public UserService(IConfiguration configuration, AuthContext context)
{
this.configuration = configuration;
this.context = context;
}
public string Login(string username, string password)
{
var user = context.Users.SingleOrDefault(x => x.Username == username);
var hasher = new PasswordHasher();
if (user == null || hasher.Verify(password, user.PasswordHash))
{
return CreateAuthToken(username, user.Email);
}
return null;
}
public async Task<string> RegisterAsync(User user, string password)
{
/* TODO: Perform validation on user */
var hasher = new PasswordHasher();
var hash = hasher.GetHash(password);
user.PasswordHash = hash;
context.Users.Add(user);
await context.SaveChangesAsync();
return CreateAuthToken(user.Username, user.Email);
}
private string CreateAuthToken(string username, string email)
{
var tokenCreator = new JwtTokenCreator(configuration.GetSection("Keys")["JwtPrivateKey"]);
return tokenCreator.CreateToken(username, email);
}
}
}