source: ChapterX.API/Controllers/ChaptersController.cs@ b373fea

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

Fixes for authentication and auhtorization\

  • Property mode set to 100644
File size: 2.6 KB
Line 
1using ChapterX.Application.Chapter.Commands;
2using ChapterX.Application.Chapter.Queries;
3using MediatR;
4using Microsoft.AspNetCore.Authorization;
5using Microsoft.AspNetCore.Mvc;
6using Microsoft.Extensions.Logging;
7using System.IdentityModel.Tokens.Jwt;
8using System.Security.Claims;
9
10namespace ChapterX.API.Controllers
11{
12 [Route("api/[controller]")]
13 [ApiController]
14 public class ChaptersController : ControllerBase
15 {
16 private readonly IMediator _mediator;
17 private readonly ILogger<ChaptersController> _logger;
18
19 public ChaptersController(IMediator mediator, ILogger<ChaptersController> logger)
20 {
21 _mediator = mediator;
22 _logger = logger;
23 }
24
25 [HttpGet]
26 [AllowAnonymous]
27 public async Task<ActionResult> GetAll()
28 {
29 _logger.LogInformation("Fetching all chapters");
30 var response = await _mediator.Send(new GetAllRequest());
31 return Ok(response);
32 }
33
34 [HttpGet("{id:int}")]
35 [AllowAnonymous]
36 public async Task<ActionResult> GetById(int id)
37 {
38 _logger.LogInformation("Fetching chapter with ID: {ChapterId}", id);
39 var response = await _mediator.Send(new GetRequest(id));
40 return Ok(response);
41 }
42
43 [HttpPost]
44 [Authorize]
45 public async Task<ActionResult> Add([FromBody] AddRequest request)
46 {
47 _logger.LogInformation("Adding a new chapter with Number: {Number}", request.Number);
48 var response = await _mediator.Send(request);
49 return Ok(response);
50 }
51
52 [HttpPut("{id:int}")]
53 [Authorize]
54 public async Task<ActionResult> Update(int id, [FromBody] UpdateRequest request)
55 {
56 _logger.LogInformation("Updating chapter with ID: {ChapterId}", id);
57 if (id != request.Id)
58 {
59 return BadRequest("Route ID and body ID must match.");
60 }
61
62 var callerId = int.Parse(User.FindFirstValue(JwtRegisteredClaimNames.Sub)!);
63 var response = await _mediator.Send(request with { CallerId = callerId });
64 return Ok(response);
65 }
66
67 [HttpDelete("{id:int}")]
68 [Authorize]
69 public async Task<ActionResult> Delete(int id)
70 {
71 _logger.LogInformation("Deleting chapter with ID: {ChapterId}", id);
72 var callerId = int.Parse(User.FindFirstValue(JwtRegisteredClaimNames.Sub)!);
73 var response = await _mediator.Send(new DeleteRequest(id, callerId));
74 return Ok(response);
75 }
76 }
77}
78
Note: See TracBrowser for help on using the repository browser.