Add user service and controller
All checks were successful
Game Ideas build for PR / build_blazor_app (pull_request) Successful in 50s
All checks were successful
Game Ideas build for PR / build_blazor_app (pull_request) Successful in 50s
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user