void.cat/VoidCat/Services/Users/UserManager.cs

59 lines
1.9 KiB
C#
Raw Normal View History

2022-02-21 22:35:06 +00:00
using VoidCat.Model;
using VoidCat.Services.Abstractions;
namespace VoidCat.Services.Users;
public class UserManager : IUserManager
{
private readonly IUserStore _store;
private readonly IEmailVerification _emailVerification;
2022-02-24 12:00:28 +00:00
private static bool _checkFirstRegister;
2022-02-21 22:35:06 +00:00
public UserManager(IUserStore store, IEmailVerification emailVerification)
2022-02-21 22:35:06 +00:00
{
_store = store;
_emailVerification = emailVerification;
2022-02-21 22:35:06 +00:00
}
2022-02-24 12:00:28 +00:00
public async ValueTask<InternalVoidUser> Login(string email, string password)
2022-02-21 22:35:06 +00:00
{
var userId = await _store.LookupUser(email);
if (!userId.HasValue) throw new InvalidOperationException("User does not exist");
2022-02-27 13:54:25 +00:00
var user = await _store.Get<InternalVoidUser>(userId.Value);
2022-02-21 22:35:06 +00:00
if (!(user?.CheckPassword(password) ?? false)) throw new InvalidOperationException("User does not exist");
2022-02-24 12:00:28 +00:00
user.LastLogin = DateTimeOffset.UtcNow;
2022-03-07 13:38:53 +00:00
await _store.Set(user.Id, user);
2022-02-24 12:00:28 +00:00
2022-02-21 22:35:06 +00:00
return user;
}
2022-02-24 12:00:28 +00:00
public async ValueTask<InternalVoidUser> Register(string email, string password)
2022-02-21 22:35:06 +00:00
{
var existingUser = await _store.LookupUser(email);
2022-02-22 14:20:31 +00:00
if (existingUser != Guid.Empty) throw new InvalidOperationException("User already exists");
2022-02-21 22:35:06 +00:00
2022-02-27 13:54:25 +00:00
var newUser = new InternalVoidUser(Guid.NewGuid(), email, password.HashPassword())
2022-02-24 12:00:28 +00:00
{
Created = DateTimeOffset.UtcNow,
LastLogin = DateTimeOffset.UtcNow
};
// automatically set first user to admin
if (!_checkFirstRegister)
{
_checkFirstRegister = true;
var users = await _store.ListUsers(new(0, 1));
if (users.TotalResults == 0)
{
newUser.Roles.Add(Roles.Admin);
}
}
2022-03-07 13:38:53 +00:00
await _store.Set(newUser.Id, newUser);
await _emailVerification.SendNewCode(newUser);
2022-02-21 22:35:06 +00:00
return newUser;
}
}