Skip to content

Commit

Permalink
Utilize identity in backend (#123)
Browse files Browse the repository at this point in the history
Co-authored-by: Aug-8 <130132558+sol-wizard@users.noreply.github.com>
  • Loading branch information
Ben0189 and sol-wizard authored Nov 8, 2024
1 parent 5f307cd commit 754c0f9
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 5 deletions.
9 changes: 8 additions & 1 deletion blotztask-api/Controllers/TaskController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,14 @@ public TaskController(ITaskService taskService)
[HttpGet("alltask")]
public async Task<IActionResult> GetAllTask()
{
return Ok(await _taskService.GetTodoItems());
var userId = HttpContext.Items["UserId"] as string;

if (userId == null)
{
throw new UnauthorizedAccessException("Could not find user id from Http Context");
}

return Ok(await _taskService.GetTodoItemsByUser(userId));
}

[HttpGet("{id}")]
Expand Down
35 changes: 35 additions & 0 deletions blotztask-api/Middleware/UserContextMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System.Security.Claims;

public class UserContextMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<UserContextMiddleware> _logger;

public UserContextMiddleware(RequestDelegate next, ILogger<UserContextMiddleware> logger)
{
_next = next;
_logger = logger;
}

public async Task InvokeAsync(HttpContext context)
{
// Check if the user is authenticated
if (context.User.Identity?.IsAuthenticated == true)
{
// Extract UserId from the claims
var userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

if (userId == null)
{
_logger.LogError("Unable to get user Id in UserContextMiddleware for an authenticated user.");
throw new UnauthorizedAccessException("Unable to get user Id in UserContextMiddleware.");
}

// Store UserId in HttpContext.Items
context.Items["UserId"] = userId;
}

// Pass request to the next middleware in the pipeline
await _next(context);
}
}
1 change: 1 addition & 0 deletions blotztask-api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@

var app = builder.Build();
app.UseMiddleware<ErrorHandlingMiddleware>();
app.UseMiddleware<UserContextMiddleware>();

app.MapIdentityApi<User>();
// Configure the HTTP request pipeline.
Expand Down
8 changes: 4 additions & 4 deletions blotztask-api/Services/TaskService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@
using Microsoft.EntityFrameworkCore;
using BlotzTask.Data.Entities;
using BlotzTask.Models.CustomError;
using System.Threading.Tasks;

namespace BlotzTask.Services;

public interface ITaskService
{
public Task<List<TaskItemDTO>> GetTodoItems();
public Task<List<TaskItemDTO>> GetTodoItemsByUser(string userId);
public Task<TaskItemDTO> GetTaskByID(int Id);
public Task<int> EditTask(int Id, EditTaskItemDTO editTaskItem);
public Task<string> AddTask(AddTaskItemDTO addtaskItem);
Expand All @@ -26,11 +25,12 @@ public TaskService(BlotzTaskDbContext dbContext)
_dbContext = dbContext;
}

public async Task<List<TaskItemDTO>> GetTodoItems()
public async Task<List<TaskItemDTO>> GetTodoItemsByUser(string userId)
{
try
{
return await _dbContext.TaskItems
.Where(x => x.UserId == userId)
.Select(x => new TaskItemDTO
{
Id = x.Id,
Expand All @@ -40,7 +40,7 @@ public async Task<List<TaskItemDTO>> GetTodoItems()
}
catch (Exception ex)
{
//TODO: Add some error log throw (havent create PBI)
//TODO: Add some error log throw
throw;
}
}
Expand Down

0 comments on commit 754c0f9

Please sign in to comment.