-
Notifications
You must be signed in to change notification settings - Fork 0
/
CommentController.cs
66 lines (54 loc) · 2.15 KB
/
CommentController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using AutoMapper;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SeeSay.Exceptions;
using SeeSay.Models.Dto.Comments;
using SeeSay.Models.Entities;
using SeeSay.Services.Abstractions;
using SeeSay.Utils.Extensions;
namespace SeeSay.Controllers;
[Route(template: "api/[controller]/[action]")]
[ApiController]
[Authorize]
public class CommentController : ControllerBase
{
private readonly ICommentRepository commentRepository;
private readonly IMapper mapper;
private readonly UserManager<User> userManager;
public CommentController(ICommentRepository commentRepository, UserManager<User> userManager, IMapper mapper)
{
this.commentRepository = commentRepository;
this.userManager = userManager;
this.mapper = mapper;
}
[HttpPost]
public async Task<IActionResult> AddComment([FromBody] CommentCreateDto commentCreateDto)
{
var comment = mapper.Map<CommentCreateDto, Comment>(commentCreateDto);
await commentRepository.AddCommentAsync(comment);
var user = await userManager.FindByIdAsync(comment.UserId);
if (user is null)
throw new EntityNotFoundException();
comment.User = user;
return Created($"Post/GetPost/{comment.PostId}", comment);
}
[HttpPut("{id:int}")]
public async Task<IActionResult> EditComment([FromRoute] int id, [FromBody] CommentEditDto commentEditDto)
{
var comment = await commentRepository.GetCommentAsync(id);
if (comment.UserId != User.GetCurrentUserId())
return Forbid();
comment = await commentRepository.EditCommentAsync(id, mapper.Map<CommentEditDto, Comment>(commentEditDto));
return Ok(comment);
}
[HttpDelete("{id:int}")]
public async Task<IActionResult> DeleteComment([FromRoute] int id)
{
var comment = await commentRepository.GetCommentAsync(id);
if (comment.UserId != User.GetCurrentUserId() && !User.IsInRole("Moderator"))
return Forbid();
await commentRepository.DeleteCommentAsync(id);
return NoContent();
}
}