|
5 | 5 | using exercise.wwwapi.DTOs.Posts; |
6 | 6 | using exercise.wwwapi.Models; |
7 | 7 | using exercise.wwwapi.Repository; |
| 8 | +using Microsoft.AspNetCore.Authorization; |
8 | 9 | using Microsoft.AspNetCore.Mvc; |
9 | 10 | using Microsoft.EntityFrameworkCore; |
| 11 | +using System.Security.Claims; |
10 | 12 |
|
11 | 13 | namespace exercise.wwwapi.Endpoints |
12 | 14 | { |
@@ -79,18 +81,35 @@ public static IResult GetAllPosts(IRepository<Post> service, IMapper mapper) |
79 | 81 | return TypedResults.Ok(response); |
80 | 82 | } |
81 | 83 |
|
| 84 | + [Authorize] |
82 | 85 | [ProducesResponseType(StatusCodes.Status200OK)] |
83 | 86 | [ProducesResponseType(StatusCodes.Status400BadRequest)] |
84 | | - public static IResult UpdatePost(IRepository<Post> service, IMapper mapper, int id, UpdatePostDTO request) |
| 87 | + public static IResult UpdatePost(IRepository<Post> service, IMapper mapper, ClaimsPrincipal user, int id, UpdatePostDTO request) |
85 | 88 | { |
86 | 89 | if (string.IsNullOrWhiteSpace(request.Content)) return TypedResults.BadRequest(new ResponseDTO<object>{ |
87 | 90 | Message = "Content cannot be empty" |
88 | 91 | }); |
89 | 92 |
|
90 | 93 | Post? post = service.GetById(id, q=>q.Include(p => p.User)); |
91 | 94 |
|
| 95 | + |
| 96 | + |
92 | 97 | if (post == null) return TypedResults.NotFound(new ResponseDTO<Object> { Message = "Post not found" }); |
93 | 98 |
|
| 99 | + var currentUserId = user.FindFirstValue(ClaimTypes.NameIdentifier); |
| 100 | + if (post.UserId.ToString() != currentUserId) |
| 101 | + { |
| 102 | + // Create your custom response object |
| 103 | + var forbiddenResponse = new ResponseDTO<object> |
| 104 | + { |
| 105 | + Message = "You are not authorized to edit this post." |
| 106 | + }; |
| 107 | + |
| 108 | + // Return it as JSON with a 403 Forbidden status code |
| 109 | + return TypedResults.Json(forbiddenResponse, statusCode: StatusCodes.Status403Forbidden); |
| 110 | + } |
| 111 | + |
| 112 | + |
94 | 113 | post.Content = request.Content; |
95 | 114 | post.UpdatedAt = DateTime.UtcNow; |
96 | 115 |
|
|
0 commit comments