Skip to content

Commit ec0b8b6

Browse files
authored
Merge pull request #78 from boolean-uk/comments-fix-swaggerAuth-fix
fixed comments endpoint and swagger auto auth
2 parents 37bdc10 + 388771d commit ec0b8b6

File tree

2 files changed

+45
-31
lines changed

2 files changed

+45
-31
lines changed

exercise.wwwapi/Endpoints/CommentEndpoints.cs

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
using Microsoft.AspNetCore.Authorization;
1010
using Microsoft.AspNetCore.Mvc;
1111
using Microsoft.EntityFrameworkCore;
12+
using Npgsql;
1213
using System.Security.Claims;
1314
using Post = exercise.wwwapi.Models.Post;
1415

@@ -49,6 +50,7 @@ private static async Task<IResult> GetCommentsPerPost(IRepository<Comment> comme
4950
[ProducesResponseType(StatusCodes.Status200OK)]
5051
[ProducesResponseType(StatusCodes.Status400BadRequest)]
5152
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
53+
[ProducesResponseType(StatusCodes.Status404NotFound)]
5254
public static async Task<IResult> CreateComment(
5355
CreateCommentRequestDTO request,
5456
IRepository<Comment> commentRepository,
@@ -74,24 +76,31 @@ public static async Task<IResult> CreateComment(
7476
return Results.BadRequest(failResponse);
7577
}
7678

77-
var post = await postRepository.GetByIdAsync(postId);
78-
if (post == null)
79-
{
80-
return Results.NotFound();
81-
}
82-
8379
var comment = new Comment
8480
{
8581
PostId = postId,
8682
UserId = userIdClaim.Value,
8783
Body = request.Body,
88-
CreatedAt = DateTime.UtcNow,
84+
CreatedAt = DateTime.UtcNow
8985
};
9086

9187
commentRepository.Insert(comment);
92-
await commentRepository.SaveAsync();
88+
try
89+
{
90+
await commentRepository.SaveAsync();
91+
}
92+
catch (DbUpdateException ex)
93+
{
94+
if (ex.InnerException is PostgresException CohortNumberEx &&
95+
CohortNumberEx.SqlState == "23503") //23503 = FK violation (Post Id or User Id did not exist)
96+
{
97+
return TypedResults.NotFound($"Post with id: {postId} was not found");
98+
}
99+
}
100+
101+
var commentWithUser = await commentRepository.GetByIdWithIncludes(c => c.Include(c => c.User), comment.Id);
93102

94-
var commentData = new CommentDTO(comment);
103+
var commentData = new CommentDTO(commentWithUser);
95104

96105
var response = new ResponseDTO<CommentDTO>
97106
{
@@ -106,6 +115,7 @@ public static async Task<IResult> CreateComment(
106115
[ProducesResponseType(StatusCodes.Status200OK)]
107116
[ProducesResponseType(StatusCodes.Status400BadRequest)]
108117
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
118+
[ProducesResponseType(StatusCodes.Status404NotFound)]
109119
public static async Task<IResult> UpdateComment(
110120
IRepository<Comment> commentRepository,
111121
int id,
@@ -191,7 +201,7 @@ public static async Task<IResult> DeleteComment(
191201
return TypedResults.NotFound();
192202
}
193203

194-
if (comment.UserId != userIdClaim)
204+
if (comment.UserId != userIdClaim && !claimsPrincipal.IsInRole("Teacher"))
195205
{
196206
return Results.Unauthorized();
197207
}

exercise.wwwapi/Program.cs

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@
174174
app.UseSwagger(c => c.OpenApiVersion = Microsoft.OpenApi.OpenApiSpecVersion.OpenApi2_0);
175175

176176
// Generate a JWT token using your existing signing key
177-
var devJwtToken = GenerateDevJwtToken(token);
177+
var devJwtToken = CreateToken(config);
178178

179179
app.UseSwaggerUI(c =>
180180
{
@@ -220,31 +220,35 @@
220220
app.ConfigureLikeEndpoints();
221221
app.Run();
222222

223-
static string GenerateDevJwtToken(string signingKey)
223+
static string CreateToken(IConfigurationSettings configurationSettings)
224224
{
225-
var tokenHandler = new JwtSecurityTokenHandler();
226-
var key = Encoding.UTF8.GetBytes(signingKey);
227-
228225
var claims = new List<Claim>
226+
{
227+
new(ClaimTypes.Sid, "2"),
228+
new(ClaimTypes.Name, "test2"),
229+
new(ClaimTypes.Email, "test2@test2"),
230+
new(ClaimTypes.Role, "Teacher")
231+
};
232+
233+
var tokenKey = Environment.GetEnvironmentVariable(Globals.EnvironmentEnvVariable) == "Staging"
234+
? Globals.TestTokenKey
235+
: Globals.TokenKey;
236+
var rawToken = configurationSettings.GetValue(tokenKey);
237+
if (rawToken == null)
229238
{
230-
new Claim(ClaimTypes.Name, "Development User"),
231-
new Claim(ClaimTypes.Email, "dev@localhost.com"),
232-
new Claim(ClaimTypes.Role, "Teacher")
233-
};
234-
235-
var tokenDescriptor = new SecurityTokenDescriptor
236-
{
237-
Subject = new ClaimsIdentity(claims),
238-
Expires = DateTime.UtcNow.AddDays(30),
239-
SigningCredentials = new SigningCredentials(
240-
new SymmetricSecurityKey(key),
241-
SecurityAlgorithms.HmacSha256Signature)
242-
};
239+
throw new Exception($"TokenKey: {tokenKey} could not be found.");
240+
}
243241

244-
var jwtToken = tokenHandler.CreateToken(tokenDescriptor);
245-
return tokenHandler.WriteToken(jwtToken);
242+
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(rawToken));
243+
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
244+
var token = new JwtSecurityToken(
245+
claims: claims,
246+
expires: DateTime.MaxValue,
247+
signingCredentials: credentials
248+
);
249+
var jwt = new JwtSecurityTokenHandler().WriteToken(token);
250+
return jwt;
246251
}
247-
248252
public partial class Program
249253
{
250254
} // needed for testing - please ignore

0 commit comments

Comments
 (0)