User profile service #2

Merged
Jiri merged 16 commits from 250809_UserProfile into main 2025-08-11 20:10:50 +00:00
4 changed files with 82 additions and 0 deletions
Showing only changes of commit c0860b05d1 - Show all commits

View file

@ -0,0 +1,38 @@
using DrinkRateAPI.Requests;
using DrinkRateAPI.Services;
using Microsoft.AspNetCore.Mvc;
namespace DrinkRateAPI.Controllers;
[ApiController]
[Route("[controller]")]
public class AdminController : ControllerBase
{
private readonly ILogger<AdminController> _logger;
private readonly ApplicationUserService _applicationUserService;
private readonly UserProfileService _userProfileService;
public AdminController(ILogger<AdminController> logger, ApplicationUserService applicationUserService,
UserProfileService userProfileService)
{
_logger = logger;
_applicationUserService = applicationUserService;
_userProfileService = userProfileService;
}
[HttpPut]
[Route("[action]")]
[Produces("application/json")]
public async Task<IActionResult> PutUserAdminStatus([FromBody] ChangeUserAdminStatusRequest request)
{
var userProfile = await _applicationUserService.UserProfileByApplicationUserAsync(User);
if (!_userProfileService.IsUserProfileAdmin(userProfile))
{
return Unauthorized();
}
var changedProfile = _userProfileService.ChangeUserAdminStatus(request.UserId, request.ChangeStatusTo);
return Ok(changedProfile);
}
}

View file

@ -1,5 +1,6 @@
using DrinkRateAPI.Contexts;
using DrinkRateAPI.DbEntities;
using DrinkRateAPI.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.OpenApi.Models;
@ -50,6 +51,8 @@ builder.Services.AddSwaggerGen(c =>
});
builder.Services.AddDbContext<ApplicationDbContext>();
builder.Services.AddScoped<ApplicationUserService>();
builder.Services.AddScoped<UserProfileService>();
var app = builder.Build();

View file

@ -0,0 +1,7 @@
namespace DrinkRateAPI.Requests;
public class ChangeUserAdminStatusRequest
{
public required string UserId { get; set; }
public bool ChangeStatusTo { get; set; }
}

View file

@ -0,0 +1,34 @@
using System.Security.Claims;
using DrinkRateAPI.Contexts;
using DrinkRateAPI.DbEntities;
using DrinkRateAPI.Exceptions;
using Microsoft.EntityFrameworkCore;
namespace DrinkRateAPI.Services;
public class UserProfileService(ApplicationDbContext context)
{
private ApplicationDbContext _context = context;
public bool IsUserProfileAdmin(DbUserProfile userProfile)
{
return userProfile.IsAdmin;
}
public DbUserProfile ChangeUserAdminStatus(string userId, bool changeStatusTo)
{
var userProfile = GetUserProfileById(userId);
userProfile.IsAdmin = changeStatusTo;
_context.UserProfiles.Update(userProfile);
_context.SaveChanges();
return userProfile;
}
public DbUserProfile GetUserProfileById(string userId)
{
var userProfile = _context.UserProfiles.FirstOrDefault(x => x.Id.ToString() == userId);
return userProfile ?? throw new KeyNotFoundException($"User with ID {userId} not found");
}
}