Files
mixtape/zero.Core/Identity/Services/UserService.cs
T

303 lines
7.7 KiB
C#
Raw Normal View History

2021-11-23 22:56:22 +01:00
using Microsoft.AspNetCore.Identity;
using Raven.Client.Documents;
using Raven.Client.Documents.Linq;
namespace zero.Identity;
2021-11-26 11:21:49 +01:00
public class UserService : IUserService
2021-11-23 22:56:22 +01:00
{
protected UserManager<ZeroUser> UserManager { get; private set; }
2021-11-26 11:21:49 +01:00
protected IStoreOperations Operations { get; private set; }
protected IZeroContext Context { get; private set; }
public UserService(IStoreContext store, IStoreOperations operations, IZeroContext context, UserManager<ZeroUser> userManager)
2021-11-23 22:56:22 +01:00
{
UserManager = userManager;
2021-11-26 11:21:49 +01:00
Operations = operations;
Context = context;
2021-11-23 22:56:22 +01:00
}
/// <inheritdoc />
public async Task<ZeroUser> GetUserById(string id)
{
ZeroUser user = await UserManager.FindByIdAsync(id);
return user;
}
/// <inheritdoc />
public async Task<ZeroUser> GetUserByEmail(string email)
{
ZeroUser user = await UserManager.FindByEmailAsync(email);
return user;
}
/// <inheritdoc />
public async Task<Dictionary<string, ZeroUser>> GetByIds(params string[] ids)
{
2021-11-26 11:21:49 +01:00
return await Operations.Load<ZeroUser>(ids);
2021-11-23 22:56:22 +01:00
}
/// <inheritdoc />
2021-11-26 11:21:49 +01:00
public async Task<Paged<ZeroUser>> GetAll(int pageNumber, int pageSize)
2021-11-23 22:56:22 +01:00
{
2021-11-26 11:21:49 +01:00
return await Operations.Load<ZeroUser>(pageNumber, pageSize, q => q.OrderByDescending(x => x.CreatedDate));
2021-11-23 22:56:22 +01:00
}
/// <inheritdoc />
2021-11-26 15:47:11 +01:00
public async Task<Result<ZeroUser>> Save(ZeroUser model)
2021-11-23 22:56:22 +01:00
{
bool updateSecurityStamp = false;
2021-11-26 11:21:49 +01:00
bool isUpdate = false;
2021-11-23 22:56:22 +01:00
if (!model.Id.IsNullOrEmpty())
{
ZeroUser origin = await GetUserById(model.Id);
2021-11-26 11:21:49 +01:00
isUpdate = origin != null;
2021-11-23 22:56:22 +01:00
updateSecurityStamp = origin != null && model.PasswordHash != origin.PasswordHash;
}
2021-11-26 15:47:11 +01:00
Result<ZeroUser> result = isUpdate ? await Operations.Update(model) : await Operations.Create(model);
2021-11-23 22:56:22 +01:00
if (updateSecurityStamp)
{
await UserManager.UpdateSecurityStampAsync(model);
}
return result;
}
/// <inheritdoc />
2021-11-26 15:47:11 +01:00
public async Task<Result<ZeroUser>> Delete(string id)
2021-11-23 22:56:22 +01:00
{
2021-11-26 11:21:49 +01:00
return await Operations.Delete<ZeroUser>(id);
2021-11-23 22:56:22 +01:00
}
/// <inheritdoc />
2021-11-26 15:47:11 +01:00
public async Task<Result<string>> HashPassword(ZeroUser user, string currentPassword, string newPassword, string confirmNewPassword)
2021-11-23 22:56:22 +01:00
{
if (newPassword != confirmNewPassword)
{
2021-11-26 15:47:11 +01:00
return Result<string>.Fail(nameof(newPassword), "@errors.changepassword.newpasswordsnotmatching");
2021-11-23 22:56:22 +01:00
}
if (currentPassword.IsNullOrWhiteSpace() || newPassword.IsNullOrWhiteSpace())
{
2021-11-26 15:47:11 +01:00
return Result<string>.Fail(nameof(currentPassword), "@errors.changepassword.emptyfields");
2021-11-23 22:56:22 +01:00
}
if (user == null)
{
2021-11-26 15:47:11 +01:00
return Result<string>.Fail("@errors.changepassword.nouser");
2021-11-23 22:56:22 +01:00
}
if (UserManager.PasswordHasher.VerifyHashedPassword(user, user.PasswordHash, currentPassword) != PasswordVerificationResult.Success)
{
2021-11-26 15:47:11 +01:00
return Result<string>.Fail("@errors.changepassword.passwordincorrect");
2021-11-23 22:56:22 +01:00
}
// validate new password
List<IdentityError> errors = new();
bool isValid = true;
foreach (var v in UserManager.PasswordValidators)
{
var result = await v.ValidateAsync(UserManager, user, newPassword);
if (!result.Succeeded)
{
if (result.Errors.Any())
{
errors.AddRange(result.Errors);
}
isValid = false;
}
}
if (!isValid)
{
2021-11-26 15:47:11 +01:00
Result<string> result = Result<string>.Fail();
2021-11-23 22:56:22 +01:00
foreach (IdentityError error in errors)
{
result.AddError(error.Description);
}
return result;
}
2021-11-26 15:47:11 +01:00
return Result<string>.Success(UserManager.PasswordHasher.HashPassword(user, newPassword));
2021-11-23 22:56:22 +01:00
}
/// <inheritdoc />
2021-11-26 15:47:11 +01:00
public async Task<Result<ZeroUser>> UpdatePassword(ZeroUser user, string currentPassword, string newPassword)
2021-11-23 22:56:22 +01:00
{
if (currentPassword.IsNullOrWhiteSpace() || newPassword.IsNullOrWhiteSpace())
{
2021-11-26 15:47:11 +01:00
return Result<ZeroUser>.Fail(nameof(currentPassword), "@errors.changepassword.emptyfields");
2021-11-23 22:56:22 +01:00
}
if (user == null)
{
2021-11-26 15:47:11 +01:00
return Result<ZeroUser>.Fail("@errors.changepassword.nouser");
2021-11-23 22:56:22 +01:00
}
IdentityResult identityResult = await UserManager.ChangePasswordAsync(user as ZeroUser, currentPassword, newPassword);
if (!identityResult.Succeeded)
{
2021-11-26 15:47:11 +01:00
Result<ZeroUser> result = Result<ZeroUser>.Fail();
2021-11-23 22:56:22 +01:00
foreach (IdentityError error in identityResult.Errors)
{
result.AddError(error.Description);
}
return result;
}
2021-11-26 15:47:11 +01:00
return Result<ZeroUser>.Success(user);
2021-11-23 22:56:22 +01:00
}
/// <inheritdoc />
2021-11-26 15:47:11 +01:00
public async Task<Result<ZeroUser>> Enable(ZeroUser user)
2021-11-23 22:56:22 +01:00
{
return await UpdateActiveState(user, true);
}
/// <inheritdoc />
2021-11-26 15:47:11 +01:00
public async Task<Result<ZeroUser>> Disable(ZeroUser user)
2021-11-23 22:56:22 +01:00
{
return await UpdateActiveState(user, false);
}
/// <summary>
/// Updates the active state of user.
/// If IsActive=false, the user cannot login anymore
/// </summary>
2021-11-26 15:47:11 +01:00
async Task<Result<ZeroUser>> UpdateActiveState(ZeroUser user, bool isActive)
2021-11-23 22:56:22 +01:00
{
user.IsActive = isActive;
IdentityResult identityResult = await UserManager.UpdateAsync(user as ZeroUser);
if (!identityResult.Succeeded)
{
2021-11-26 15:47:11 +01:00
Result<ZeroUser> result = Result<ZeroUser>.Fail();
2021-11-23 22:56:22 +01:00
foreach (IdentityError error in identityResult.Errors)
{
result.AddError(error.Description);
}
return result;
}
await UserManager.UpdateSecurityStampAsync(user as ZeroUser);
2021-11-26 15:47:11 +01:00
return Result<ZeroUser>.Success(user);
2021-11-23 22:56:22 +01:00
}
2021-11-24 15:49:25 +01:00
/// <inheritdoc />
public async Task<bool> TrySwitchApp(string appId)
{
2021-11-26 11:21:49 +01:00
IZeroDocumentSession session = Context.Store.Session(global: true);
ZeroUser user = await UserManager.GetUserAsync(Context.BackofficeUser);
2021-11-24 15:49:25 +01:00
if (user == null || appId.IsNullOrEmpty())
{
return false;
}
string[] allowedAppIds = user.GetAllowedAppIds();
bool isMainId = appId.Equals(user.AppId, StringComparison.InvariantCultureIgnoreCase);
bool isAllowedId = allowedAppIds.Contains(appId, StringComparer.InvariantCultureIgnoreCase);
if (user.IsSuper || isMainId || isAllowedId)
{
user.CurrentAppId = appId;
//byte[] bytes = new byte[20];
//RandomNumberGenerator.Fill(bytes);
//user.SecurityStamp = Base32.ToBase32(bytes); // TODO update security stamp but Base32 is .net core internal
await session.StoreAsync(user);
await session.SaveChangesAsync();
return true;
}
return false;
}
2021-11-23 22:56:22 +01:00
}
2021-11-26 11:21:49 +01:00
public interface IUserService
2021-11-23 22:56:22 +01:00
{
/// <summary>
/// Find user by id
/// </summary>
Task<ZeroUser> GetUserById(string id);
/// <summary>
/// Find user by email
/// </summary>
Task<ZeroUser> GetUserByEmail(string email);
/// <summary>
/// Get users by ids
/// </summary>
Task<Dictionary<string, ZeroUser>> GetByIds(params string[] ids);
/// <summary>
2021-11-26 11:21:49 +01:00
/// Get all users for the current application
2021-11-23 22:56:22 +01:00
/// </summary>
2021-11-26 11:21:49 +01:00
Task<Paged<ZeroUser>> GetAll(int pageNumber, int pageSize);
2021-11-23 22:56:22 +01:00
/// <summary>
/// Creates or updates a user
/// </summary>
2021-11-26 15:47:11 +01:00
Task<Result<ZeroUser>> Save(ZeroUser model);
2021-11-23 22:56:22 +01:00
/// <summary>
/// Deletes a user
/// </summary>
2021-11-26 15:47:11 +01:00
Task<Result<ZeroUser>> Delete(string id);
2021-11-23 22:56:22 +01:00
/// <summary>
/// Changes the password of the current user.
/// User is logged out if this operation succeeds.
/// </summary>
2021-11-26 15:47:11 +01:00
Task<Result<ZeroUser>> UpdatePassword(ZeroUser user, string currentPassword, string newPassword);
2021-11-23 22:56:22 +01:00
/// <summary>
/// Tries to hash a new password
/// </summary>
2021-11-26 15:47:11 +01:00
Task<Result<string>> HashPassword(ZeroUser user, string currentPassword, string newPassword, string confirmNewPassword);
2021-11-23 22:56:22 +01:00
/// <summary>
/// Enables a user
/// </summary>
2021-11-26 15:47:11 +01:00
Task<Result<ZeroUser>> Enable(ZeroUser user);
2021-11-23 22:56:22 +01:00
/// <summary>
/// Disables a user
/// </summary>
2021-11-26 15:47:11 +01:00
Task<Result<ZeroUser>> Disable(ZeroUser user);
2021-11-24 15:49:25 +01:00
/// <summary>
/// Tries to switch the currently loaded backoffice application for the current user
/// </summary>
Task<bool> TrySwitchApp(string appId);
2021-11-23 22:56:22 +01:00
}