Build auth API

This commit is contained in:
Robert Marshall 2020-04-12 13:50:39 +01:00
commit dafe603a06
43 changed files with 1153 additions and 0 deletions

View file

@ -0,0 +1,31 @@
using System;
using System.Threading.Tasks;
namespace Robware.Auth {
public class Authenticator : IAuthenticator {
private readonly IUsers _users;
private readonly ICryptographyProvider _crypto;
public Authenticator(IUsers users, ICryptographyProvider crypto) {
_users = users;
_crypto = crypto;
}
public async Task<(AuthenticationResult Result, User User)> Authenticate(string username, string password) {
try {
var user = await _users.GetByEmail(username);
return _crypto.Encrypt(password) == user.Password ? (AuthenticationResult.Success, user) : (AuthenticationResult.IncorrectPassword, null);
}
catch (UserNotFoundException) {
return (AuthenticationResult.NotFound, null);
}
}
}
public enum AuthenticationResult {
Unknown,
Success,
NotFound,
IncorrectPassword
}
}

View file

@ -0,0 +1,19 @@
using System.Security.Cryptography;
using System.Text;
namespace Robware.Auth {
public class CryptographyProvider : ICryptographyProvider {
public string Encrypt(string input) {
using (var sha256 = SHA256.Create()) {
var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(input));
var builder = new StringBuilder();
foreach (var b in hash)
builder.Append(b.ToString("x2"));
var hashString = builder.ToString();
return hashString;
}
}
}
}

View file

@ -0,0 +1,7 @@
using System.Threading.Tasks;
namespace Robware.Auth {
public interface IAuthenticator {
Task<(AuthenticationResult Result, User User)> Authenticate(string username, string password);
}
}

View file

@ -0,0 +1,5 @@
namespace Robware.Auth {
public interface ICryptographyProvider {
string Encrypt(string input);
}
}

View file

@ -0,0 +1,7 @@
using System.Threading.Tasks;
namespace Robware.Auth {
public interface IUsers {
Task<User> GetByEmail(string email);
}
}

View file

@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
</Project>

6
src/Robware.Auth/User.cs Normal file
View file

@ -0,0 +1,6 @@
namespace Robware.Auth {
public class User {
public string Username { get; protected set; }
public string Password { get; protected set; }
}
}

View file

@ -0,0 +1,9 @@
using System;
namespace Robware.Auth {
public class UserNotFoundException : Exception {
public UserNotFoundException(string username) : base("Could not find user " + username) {
}
}
}