Skip to content

Commit c749147

Browse files
committed
Started adding authentication in the updatepost
1 parent df54bf7 commit c749147

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

exercise.wwwapi/Endpoints/PostEndpoints.cs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55
using exercise.wwwapi.DTOs.Posts;
66
using exercise.wwwapi.Models;
77
using exercise.wwwapi.Repository;
8+
using Microsoft.AspNetCore.Authorization;
89
using Microsoft.AspNetCore.Mvc;
910
using Microsoft.EntityFrameworkCore;
11+
using System.Security.Claims;
1012

1113
namespace exercise.wwwapi.Endpoints
1214
{
@@ -79,18 +81,35 @@ public static IResult GetAllPosts(IRepository<Post> service, IMapper mapper)
7981
return TypedResults.Ok(response);
8082
}
8183

84+
[Authorize]
8285
[ProducesResponseType(StatusCodes.Status200OK)]
8386
[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)
8588
{
8689
if (string.IsNullOrWhiteSpace(request.Content)) return TypedResults.BadRequest(new ResponseDTO<object>{
8790
Message = "Content cannot be empty"
8891
});
8992

9093
Post? post = service.GetById(id, q=>q.Include(p => p.User));
9194

95+
96+
9297
if (post == null) return TypedResults.NotFound(new ResponseDTO<Object> { Message = "Post not found" });
9398

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+
94113
post.Content = request.Content;
95114
post.UpdatedAt = DateTime.UtcNow;
96115

0 commit comments

Comments
 (0)