source: ChapterX.API/Controllers/StoriesController.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.9 KB
Line 
1using ChapterX.Application.Story.Commands;
2using ChapterX.Application.Story.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 StoriesController : ControllerBase
15 {
16 private readonly IMediator _mediator;
17 private readonly ILogger<StoriesController> _logger;
18
19 public StoriesController(IMediator mediator, ILogger<StoriesController> logger)
20 {
21 _mediator = mediator;
22 _logger = logger;
23 }
24
25 // GET: api/Stories
26 [HttpGet]
27 [AllowAnonymous]
28 public async Task<ActionResult> GetAll([FromQuery] GetAllRequest request)
29 {
30 _logger.LogInformation("Fetching all stories");
31 var response = await _mediator.Send(request);
32 return Ok(response);
33 }
34
35 // GET: api/Stories/5
36 [HttpGet("{id:int}")]
37 [AllowAnonymous]
38 public async Task<ActionResult> GetById([FromRoute] int id)
39 {
40 _logger.LogInformation("Fetching story with ID: {StoryId}", id);
41 var response = await _mediator.Send(new GetRequest(id));
42 return Ok(response);
43 }
44
45 // POST: api/Stories
46 [HttpPost]
47 [Authorize]
48 public async Task<ActionResult> Add([FromBody] AddRequest request)
49 {
50 var callerId = int.Parse(User.FindFirstValue(JwtRegisteredClaimNames.Sub)!);
51 _logger.LogInformation("Adding a new story for UserId: {UserId}", callerId);
52 var response = await _mediator.Send(request with { UserId = callerId });
53 return Ok(response);
54 }
55
56 // PUT: api/Stories/5
57 [HttpPut("{id:int}")]
58 [Authorize]
59 public async Task<ActionResult> Update([FromRoute] int id, [FromBody] UpdateRequest request)
60 {
61 _logger.LogInformation("Updating story with ID: {StoryId}", id);
62 if (id != request.Id)
63 {
64 return BadRequest("Route ID and body ID must match.");
65 }
66
67 var callerId = int.Parse(User.FindFirstValue(JwtRegisteredClaimNames.Sub)!);
68 var response = await _mediator.Send(request with { CallerId = callerId });
69 return Ok(response);
70 }
71
72 // DELETE: api/Stories/5
73 [HttpDelete("{id:int}")]
74 [Authorize]
75 public async Task<ActionResult> Delete([FromRoute] int id)
76 {
77 _logger.LogInformation("Deleting story with ID: {StoryId}", id);
78 var callerId = int.Parse(User.FindFirstValue(JwtRegisteredClaimNames.Sub)!);
79 var response = await _mediator.Send(new DeleteRequest(id, callerId));
80 return Ok(response);
81 }
82 }
83}
84
Note: See TracBrowser for help on using the repository browser.