Add user service and controller
All checks were successful
Game Ideas build for PR / build_blazor_app (pull_request) Successful in 50s

This commit is contained in:
2025-04-27 17:09:15 +02:00
parent 9f0b43d10c
commit 63622bd299
12 changed files with 208 additions and 10 deletions

View File

@@ -0,0 +1,83 @@
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));
}
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;
}
}