using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using eprintServer.Entities; using eprintServer.Requests; using eprintServer.Services; using System.Security.Claims; namespace vendorApproverBackend.Controllers { [ApiController] [Route("api/v1/user")] public class UsersController : ControllerBase { private readonly UserService _userService; public UsersController(UserService userService) { _userService = userService; } [HttpGet("current_user")] [Authorize(Roles = "ADMIN,USER,SUB_ADMIN")] public async Task> GetCurrentUser() { var username = User.FindFirstValue(ClaimTypes.Name); if (string.IsNullOrEmpty(username)) { return Unauthorized("Username claim not found in token."); } var user = await _userService.FindByUsernameAsync(username); if (user == null) { return NotFound("User not found."); } return Ok(user); } [HttpPatch("update_User_profile/{userId}")] [Authorize(Roles = "ADMIN,USER,SUB_ADMIN")] public async Task> UpdateEmployeeProfile(long userId, [FromBody] UpdateProfileRequest request) { try { var updatedUser = await _userService.UpdateUserProfileAsync(userId, request); if (updatedUser == null) { return NotFound($"User with ID {userId} not found."); } return Ok(updatedUser); } catch (Exception e) { return StatusCode(StatusCodes.Status406NotAcceptable, $"An error occurred while updating the profile: {e.Message}"); } } [HttpPatch("update_password/{userId}")] [Authorize(Roles = "ADMIN,USER,SUB_ADMIN")] public async Task UpdatePassword(long userId, [FromBody] UpdatePasswordRequest request) { try { var updatedUser = await _userService.UpdateUserPasswordAsync(userId, request); if (updatedUser == null) { return NotFound($"User with ID {userId} not found."); } return Ok(new { Message = "Password updated successfully." }); } catch (InvalidOperationException ex) when (ex.Message == "Old password is not correct.") { return StatusCode(StatusCodes.Status406NotAcceptable, "Old password is not correct."); } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, $"An error occurred while updating the password: {e.Message}"); } } } }