Skip to content

Commit

Permalink
Add CreatedBy field to identity user who created comment
Browse files Browse the repository at this point in the history
  • Loading branch information
vectorNull committed Jun 26, 2024
1 parent cb27f26 commit bee2958
Show file tree
Hide file tree
Showing 9 changed files with 555 additions and 8 deletions.
23 changes: 21 additions & 2 deletions api/Controllers/CommentController.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using api.DTOs.Comment;
using api.Extensions;
using api.Interfaces;
using api.Mappers;
using api.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace api.Controllers
Expand All @@ -11,11 +14,13 @@ public class CommentController : ControllerBase
{
private readonly ICommentRepo _commentRepo;
private readonly IStockRepo _stockRepo;
private readonly UserManager<AppUser> _userManager;

public CommentController(ICommentRepo commentRepo, IStockRepo stockRepo)
public CommentController(ICommentRepo commentRepo, IStockRepo stockRepo, UserManager<AppUser> userManager)
{
_commentRepo = commentRepo;
_stockRepo = stockRepo;
_userManager = userManager;
}

[HttpGet]
Expand Down Expand Up @@ -71,7 +76,21 @@ public async Task<IActionResult> CreateComment([FromRoute] int stockId, [FromBod
return BadRequest("Stock does not exist.");
}

var commentModel = commentDto.FromCreatedDtoToComment(stockId);
var username = User.GetUsername();

if (username == null)
{
return Unauthorized();
}

var user = await _userManager.FindByNameAsync(username);

if (user == null)
{
return NotFound();
}

var commentModel = commentDto.FromCreatedDtoToComment(stockId, user.Id);

await _commentRepo.CreateAsync(commentModel);

Expand Down
1 change: 1 addition & 0 deletions api/DTOs/Comment/CommentDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ public class CommentDto
public string Title { get; set; } = string.Empty;
public string Content { get; set; } = string.Empty;
public DateTime CreatedOn { get; set; }
public string? CreatedBy { get; set; } = string.Empty;
public int? StockId { get; set; }
}
}
6 changes: 4 additions & 2 deletions api/Mappers/CommentMappers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,19 @@ public static CommentDto ToCommentDto(this Comment commentModel)
Title = commentModel.Title,
Content = commentModel.Content,
CreatedOn = commentModel.CreatedOn,
StockId = commentModel.StockId
CreatedBy = commentModel.AppUser?.UserName,
StockId = commentModel.StockId,
};
}

public static Comment FromCreatedDtoToComment(this CreateCommentRequestDto commentDto, int stockId)
public static Comment FromCreatedDtoToComment(this CreateCommentRequestDto commentDto, int stockId, string userId)
{
return new Comment
{
Title = commentDto.Title,
Content = commentDto.Content,
StockId = stockId,
AppUserId = userId
};
}

Expand Down
Loading

0 comments on commit bee2958

Please sign in to comment.