Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Neo.Api/Controllers/AuthController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ public async Task<IActionResult> Register([FromBody] RegisterDto dto)
if (!Enum.TryParse<Neo.Domain.Enums.UserRole>(dto.Role, true, out var userRole) ||
!Enum.IsDefined(typeof(Neo.Domain.Enums.UserRole), userRole) ||
userRole == Neo.Domain.Enums.UserRole.None) // If you have a None/Unknown default
return BadRequest("Invalid role.");
return BadRequest(new { message = "Invalid role." });

var result = await mediator.Send(new RegisterUserCommand(dto.Username, dto.Password, userRole));
if (!result.Success)
return Conflict(new { error = result.ErrorMessage });
return Ok(new { id = result.UserId });
return Ok(new { message = "Successfully registerd a user.", Id = result.UserId });
}


Expand All @@ -53,7 +53,7 @@ public async Task<IActionResult> Login([FromBody] LoginDto dto)
{
var user = await userRepo.GetByUsernameAsync(dto.Username);
if (user == null || !passwordHasher.VerifyPassword(dto.Password, user.PasswordHash))
return Unauthorized("Invalid credentials.");
return Unauthorized(new { message = "Invalid credentials." });

var token = jwtTokenService.GenerateToken(user);
return Ok(new { token, username = user.Username, role = user.Role, userId = user.Id });
Expand Down
2 changes: 1 addition & 1 deletion Neo.Api/Controllers/CommentsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public async Task<IActionResult> Add([FromBody] AddCommentDto dto)

var newCommand = new AddCommentCommand(dto.PostId, userId, dto.Content);
var commentId = await mediator.Send(newCommand);
return Ok(new { commentId });
return Ok(new {message ="Successfuly crated a comment",commentId });
}

public record AddCommentDto(int PostId, string Content);
Expand Down
38 changes: 22 additions & 16 deletions Neo.Api/Controllers/PostsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ namespace Neo.Api.Controllers;
public class PostsController(IMediator mediator) : ControllerBase
{
/// <summary>
/// Gets paged posts with filters.
/// Gets paged posts with filters, this does not require an auth token.
/// </summary>
[HttpGet]
[AllowAnonymous]
Expand All @@ -40,7 +40,7 @@ public async Task<IActionResult> GetPaged(
}

/// <summary>
/// Creates a new post by the current user.
/// Creates a new post by the current user, you need to be authotised first to perfom this.
/// </summary>
[HttpPost]
[Authorize]
Expand All @@ -53,11 +53,16 @@ public async Task<IActionResult> Create([FromBody] CreatePostDto dto)
var command = new CreatePostCommand(userId, dto.Title, dto.Content);
var postId = await mediator.Send(command);

return CreatedAtAction(nameof(GetPaged), new { id = postId }, new { postId });
return CreatedAtAction(
nameof(Create),
new { id = postId },
new { postId, message = "Successfully created a post" }
);

}

/// <summary>
/// Likes a post by the current user.
/// Likes a post by the current user, this only allows one like per user, users cannot like theirs own posts.
/// </summary>
[HttpPost("{id}/like")]
[Authorize]
Expand All @@ -68,15 +73,15 @@ public async Task<IActionResult> Like(int id)

var likeId = await mediator.Send(new LikePostCommand(id, userId));
if (likeId == -1)
return BadRequest("You cannot like a post more than once.");
return BadRequest(new { message = "You cannot like a post more than once." });

if (likeId == -2)
return BadRequest("You cannot like your own post.");
return Ok(new { likeId });
return Ok(new { message = "Successfully liked post.", likeId });
}

/// <summary>
/// Removes a like from a post by the current user.
/// Removes a like from a post by the current user, if the .
/// </summary>
[HttpPost("{id}/unlike")]
[Authorize]
Expand All @@ -88,9 +93,10 @@ public async Task<IActionResult> Unlike(int id)
var result = await mediator.Send(new UnlikePostCommand(id, userId));

if (result == -1)
return BadRequest("You have not liked this post or already unliked it.");
return BadRequest(new { message = "You have not liked this post or already unliked it." });

return Ok(new { message = "Successfully removed like on the post." });

return Ok();
}

/// <summary>
Expand All @@ -104,25 +110,25 @@ public async Task<IActionResult> Flag(int PostId, [FromBody] FlagPostDto dto)
var userId = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "0");
if (userId == 0) return Unauthorized();

if (string.IsNullOrWhiteSpace(dto.reason))
return BadRequest("Flag reason is required.");
if (string.IsNullOrWhiteSpace(dto.Reason))
return BadRequest(new { message = "Flag reason is required." });

// --- Map reason to tag name ---
var tagName = MapReasonToTag(dto.reason);
var tagName = MapReasonToTag(dto.Reason);
if (string.IsNullOrWhiteSpace(tagName))
return BadRequest("Invalid flag reason. No corresponding tag found.");
return BadRequest(new { message = "Invalid flag reason. No corresponding tag found." });

var cmd = new FlagPostCommand(PostId, tagName, userId);

var flagResult = await mediator.Send(cmd);
if (!flagResult)
return BadRequest("Failed to flag post.");
return BadRequest(new { message = "Failed to flag post." });

// Only add a tag if the mapping found one
if (!string.IsNullOrWhiteSpace(tagName))
await mediator.Send(new TagPostCommand(PostId, tagName));

return Ok($"Sucessfully flagged the post and created a {tagName} tag on it.");
return Ok(new { message = $"Sucessfully flagged the post and created a {tagName} tag on it." });
}

// Maps moderator reason to regulatory tag
Expand All @@ -139,5 +145,5 @@ public async Task<IActionResult> Flag(int PostId, [FromBody] FlagPostDto dto)
}

public record CreatePostDto(string Title, string Content);
public record FlagPostDto(string reason);
public record FlagPostDto(string Reason);
}
14 changes: 7 additions & 7 deletions Neo.Application/DTOs/PagedPostDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
public class PagedPostDto
{
public int PostId { get; set; }
public string PostTitle { get; set; }
public string PostContent { get; set; }
public string? PostTitle { get; set; }
public string? PostContent { get; set; }
public DateTime PostCreated { get; set; }
public bool IsPostFlagged { get; set; }
public string? FlaggedReason { get; set; }
public PostUserDto CreatedUser { get; set; }
public List<PostTagDto> Tags { get; set; }
public List<PostCommentDto> Comments { get; set; }
public List<PostLikeDto> Likes { get; set; }
public PostSummaryDto Summary { get; set; }
public PostUserDto? CreatedUser { get; set; }
public List<PostTagDto>? Tags { get; set; }
public List<PostCommentDto>? Comments { get; set; }
public List<PostLikeDto>? Likes { get; set; }
public PostSummaryDto? Summary { get; set; }
}
6 changes: 3 additions & 3 deletions Neo.Application/DTOs/PostCommentDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
namespace Neo.Application.DTOs;
public class PostCommentDto
{
public string CommentUserName { get; set; }
public string CommentContent { get; set; }
public DateTime DateCreated { get; set; }
public string? CommentUserName { get; set; }
public string? CommentContent { get; set; }
public DateTime? DateCreated { get; set; }
}
4 changes: 2 additions & 2 deletions Neo.Application/DTOs/PostLikeDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
namespace Neo.Application.DTOs;
public class PostLikeDto
{
public string LikedUserName { get; set; }
public DateTime LikedDate { get; set; }
public string? LikedUserName { get; set; }
public DateTime? LikedDate { get; set; }
}
2 changes: 1 addition & 1 deletion Neo.Application/DTOs/PostTagDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@

public class PostTagDto
{
public string TagName { get; set; }
public string? TagName { get; set; }
}
2 changes: 1 addition & 1 deletion Neo.Application/DTOs/PostUserDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
public class PostUserDto
{
public int Id { get; set; }
public string UserName { get; set; }
public string? UserName { get; set; }
// Add more user details as needed
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using Neo.Application.DTOs;
using Neo.Application.UseCases.GetPagedPosts;
using Neo.Domain.Interfaces;

namespace Neo.Application.UseCases.GetPagedPosts;
public sealed class GetPagedPostsHandler(
IPostRepository postRepo,
ICommentRepository commentRepo,
Expand Down Expand Up @@ -43,23 +43,23 @@
// Fetch all needed users (avoid N+1 problem)
var userDict = new Dictionary<int, Neo.Domain.Entities.User>();
foreach (var uid in allUserIds)
userDict[uid] = await userRepo.GetByIdAsync(uid);

Check warning on line 46 in Neo.Application/UseCases/GetPagedPosts/GetPagedPostsHandler.cs

View workflow job for this annotation

GitHub Actions / build-and-test

Possible null reference assignment.

Check warning on line 46 in Neo.Application/UseCases/GetPagedPosts/GetPagedPostsHandler.cs

View workflow job for this annotation

GitHub Actions / build-and-test

Possible null reference assignment.

// Map comments using fetched user names
var commentDtos = comments.Select(c =>
new PostCommentDto
{
CommentUserName = userDict.ContainsKey(c.UserId) ? userDict[c.UserId].Username : c.UserId.ToString(),
CommentUserName = userDict.TryGetValue(c.UserId, out var user) ? user.Username : c.UserId.ToString(),
CommentContent = c.Content,
DateCreated = c.CreatedAt
DateCreated = c.CreatedAt,
}
).ToList();

// Map likes using fetched user names
var likeDtos = likes.Select(l =>
new PostLikeDto
{
LikedUserName = userDict.ContainsKey(l.UserId) ? userDict[l.UserId].Username : l.UserId.ToString(),
LikedUserName = userDict.TryGetValue(l.UserId, out var user) ? user.Username : l.UserId.ToString(),
LikedDate = l.CreatedAt
}
).ToList();
Expand All @@ -74,7 +74,7 @@
FlaggedReason = post.FlagReason,
CreatedUser = new PostUserDto
{
Id = user.Id,

Check warning on line 77 in Neo.Application/UseCases/GetPagedPosts/GetPagedPostsHandler.cs

View workflow job for this annotation

GitHub Actions / build-and-test

Dereference of a possibly null reference.

Check warning on line 77 in Neo.Application/UseCases/GetPagedPosts/GetPagedPostsHandler.cs

View workflow job for this annotation

GitHub Actions / build-and-test

Dereference of a possibly null reference.
UserName = user.Username // Make sure this is UserName, not Username
},
Tags = tags,
Expand Down
2 changes: 1 addition & 1 deletion Neo.Database/Store Procedures/spPostLike_GetByPostId.sql
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ BEGIN
pl.Id,
pl.PostId,
pl.UserId,
u.UserName, -- Join to get user name
u.Username, -- Join to get user name
pl.CreatedAt
FROM PostLikes pl
INNER JOIN Users u ON pl.UserId = u.Id
Expand Down
2 changes: 1 addition & 1 deletion Neo.Domain/Entities/Post.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,6 @@ public class Post
/// <summary>
/// Gets or sets the tags associated with the post.
/// </summary>
public string TagName { get; set; }
public string? TagName { get; set; }

}
Loading