source: ChapterX.API/Controllers/UsersController.cs@ 0b502c2

main
Last change on this file since 0b502c2 was 0b502c2, checked in by kikisrbinoska <srbinoskakristina07@…>, 12 days ago

Fixed user profile and reading lists

  • Property mode set to 100644
File size: 3.0 KB
Line 
1using ChapterX.Application.User.Commands;
2using ChapterX.Application.User.Queries;
3using MediatR;
4using Microsoft.AspNetCore.Authorization;
5using Microsoft.AspNetCore.Mvc;
6using Microsoft.Extensions.Logging;
7using System.Security.Claims;
8
9namespace ChapterX.API.Controllers
10{
11 [Route("api/[controller]")]
12 [ApiController]
13 public class UsersController : ControllerBase
14 {
15 private readonly IMediator _mediator;
16 private readonly ILogger<UsersController> _logger;
17
18 public UsersController(IMediator mediator, ILogger<UsersController> logger)
19 {
20 _mediator = mediator;
21 _logger = logger;
22 }
23
24 [HttpGet]
25 [AllowAnonymous]
26 public async Task<ActionResult> GetAll()
27 {
28 _logger.LogInformation("Fetching all users");
29 var response = await _mediator.Send(new GetAllRequest());
30 var result = response.Users.Select(u => new
31 {
32 id = u.Id,
33 username = u.Username,
34 name = u.Name,
35 surname = u.Surname,
36 email = u.Email,
37 role = u.Admin != null ? "admin" : u.Writer != null ? "writer" : "regular",
38 });
39 return Ok(result);
40 }
41
42 [HttpGet("{id:int}")]
43 [AllowAnonymous]
44 public async Task<ActionResult> GetById(int id)
45 {
46 _logger.LogInformation("Fetching user with ID: {UserId}", id);
47 var response = await _mediator.Send(new GetRequest(id));
48 return Ok(response);
49 }
50
51 [HttpPost]
52 [Authorize]
53 public async Task<ActionResult> Add([FromBody] AddRequest request)
54 {
55 _logger.LogInformation("Adding a new user with username: {Username}", request.Username);
56 var response = await _mediator.Send(request);
57 return Ok(response);
58 }
59
60 [HttpPut("{id:int}")]
61 [Authorize]
62 public async Task<ActionResult> Update(int id, [FromBody] UpdateRequest request)
63 {
64 _logger.LogInformation("Updating user with ID: {UserId}", id);
65 if (id != request.Id)
66 {
67 return BadRequest("Route ID and body ID must match.");
68 }
69
70 var callerId = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
71 var isAdmin = User.IsInRole("Admin");
72 if (callerId != id && !isAdmin)
73 return Forbid();
74
75 var response = await _mediator.Send(request);
76 return Ok(response);
77 }
78
79 [HttpDelete("{id:int}")]
80 [Authorize]
81 public async Task<ActionResult> Delete(int id)
82 {
83 _logger.LogInformation("Deleting user with ID: {UserId}", id);
84 var callerId = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
85 var isAdmin = User.IsInRole("Admin");
86 if (callerId != id && !isAdmin)
87 return Forbid();
88
89 var response = await _mediator.Send(new DeleteRequest(id));
90 return Ok(response);
91 }
92 }
93}
94
Note: See TracBrowser for help on using the repository browser.