Skip to content

Commit 6f04d59

Browse files
committed
demo user middleware
1 parent 8364330 commit 6f04d59

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
using BugLab.Data.Extensions;
2+
using BugLab.Shared.Responses;
3+
using Microsoft.AspNetCore.Hosting;
4+
using Microsoft.AspNetCore.Http;
5+
using Microsoft.Extensions.Hosting;
6+
using System.Threading.Tasks;
7+
8+
namespace BugLab.API.Middlewares
9+
{
10+
public class DemoUserMiddleware
11+
{
12+
private readonly RequestDelegate _next;
13+
private readonly IWebHostEnvironment _env;
14+
15+
public DemoUserMiddleware(RequestDelegate next, IWebHostEnvironment env)
16+
{
17+
_next = next;
18+
_env = env;
19+
}
20+
21+
public async Task InvokeAsync(HttpContext context)
22+
{
23+
var requestType = context.Request.Method;
24+
var userId = context.User.UserId();
25+
26+
if (requestType == "GET" || _env.IsDevelopment() || string.IsNullOrWhiteSpace(userId) || userId != "757b2158-40c3-4917-9523-5861973a4d2e")
27+
{
28+
await _next(context);
29+
return;
30+
}
31+
32+
context.Response.StatusCode = StatusCodes.Status403Forbidden;
33+
var response = new ApiError($"You are not allowed to make a {requestType} request using the demo user");
34+
await context.Response.WriteAsJsonAsync(response);
35+
}
36+
}
37+
}

BugLab.API/Startup.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,9 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
4141
app.UseSwagger();
4242
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BugLab.API v1"));
4343
}
44-
44+
4545
app.UseMiddleware<ExceptionMiddleware>();
46+
4647
app.UseHttpsRedirection();
4748

4849
app.UseCors();
@@ -51,6 +52,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
5152

5253
app.UseAuthentication();
5354
app.UseAuthorization();
55+
app.UseMiddleware<DemoUserMiddleware>();
5456

5557
app.UseEndpoints(endpoints =>
5658
{

0 commit comments

Comments
 (0)