All checks were successful
Game Ideas build for PR / build_blazor_app (pull_request) Successful in 52s
84 lines
2.4 KiB
C#
84 lines
2.4 KiB
C#
using AutoMapper;
|
|
using GameIdeas.Resources;
|
|
using GameIdeas.Shared.Dto;
|
|
using GameIdeas.Shared.Model;
|
|
using GameIdeas.WebAPI.Exceptions;
|
|
using Microsoft.AspNetCore.Identity;
|
|
|
|
namespace GameIdeas.WebAPI.Services.Users;
|
|
|
|
public class UserWriteService(
|
|
UserManager<User> userManager) : IUserWriteService
|
|
{
|
|
public async Task<string> CreateUser(UserDto user)
|
|
{
|
|
if (user.Username == null ||
|
|
user.Password == null ||
|
|
user.Role == null)
|
|
{
|
|
throw new UserInvalidException(ResourcesKey.MissingField);
|
|
}
|
|
|
|
User userToCreate = new() { UserName = user.Username };
|
|
|
|
var result = await userManager.CreateAsync(userToCreate, user.Password);
|
|
|
|
if (result.Succeeded)
|
|
{
|
|
await userManager.AddToRoleAsync(userToCreate, user.Role.Name);
|
|
}
|
|
else
|
|
{
|
|
throw new UserInvalidException(string.Join("; ", result.Errors.Select(e => $"{e.Code} {e.Description}")));
|
|
}
|
|
|
|
return userToCreate.Id;
|
|
}
|
|
|
|
public async Task<string> DeleteUser(string userId)
|
|
{
|
|
if (userId == null)
|
|
{
|
|
throw new ArgumentNullException(ResourcesKey.MissingField);
|
|
}
|
|
|
|
var user = await userManager.FindByIdAsync(userId)
|
|
?? throw new UserInvalidException("User not found");
|
|
|
|
await userManager.DeleteAsync(user);
|
|
return userId;
|
|
}
|
|
|
|
public async Task<string> UpdateUser(string userId, UserDto user)
|
|
{
|
|
if (userId == null)
|
|
{
|
|
throw new ArgumentNullException(ResourcesKey.MissingField);
|
|
}
|
|
|
|
var userToUpdate = await userManager.FindByIdAsync(userId)
|
|
?? throw new UserInvalidException("User not found");
|
|
|
|
if (user.Username != null)
|
|
{
|
|
userToUpdate.UserName = user.Username;
|
|
await userManager.UpdateAsync(userToUpdate);
|
|
}
|
|
|
|
if (user.Password != null)
|
|
{
|
|
await userManager.RemovePasswordAsync(userToUpdate);
|
|
await userManager.AddPasswordAsync(userToUpdate, user.Password);
|
|
}
|
|
|
|
if (user.Role != null)
|
|
{
|
|
var roles = await userManager.GetRolesAsync(userToUpdate);
|
|
await userManager.RemoveFromRolesAsync(userToUpdate, roles);
|
|
await userManager.AddToRoleAsync(userToUpdate, user.Role.Name);
|
|
}
|
|
|
|
return userToUpdate.Id;
|
|
}
|
|
}
|