Inject roles on token validation
This commit is contained in:
@@ -21,7 +21,7 @@ public class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options
|
||||
public DbSet<OrderStatus> OrderStatuses { get; set; }
|
||||
public DbSet<ShippingStatus> ShippingStatuses { get; set; }
|
||||
public DbSet<User> Users { get; set; }
|
||||
public DbSet<UserRole> UserRoles { get; set; }
|
||||
public DbSet<UserRole> UserRole { get; set; }
|
||||
public DbSet<Role> Roles { get; set; }
|
||||
public DbSet<Category> Categories { get; set; }
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
namespace Imprink.Infrastructure.Migrations
|
||||
{
|
||||
[DbContext(typeof(ApplicationDbContext))]
|
||||
[Migration("20250606173957_InitialSetup")]
|
||||
[Migration("20250607211109_InitialSetup")]
|
||||
partial class InitialSetup
|
||||
{
|
||||
/// <inheritdoc />
|
||||
@@ -825,7 +825,7 @@ namespace Imprink.Infrastructure.Migrations
|
||||
b.HasIndex("UserId")
|
||||
.HasDatabaseName("IX_UserRole_UserId");
|
||||
|
||||
b.ToTable("UserRoles");
|
||||
b.ToTable("UserRole");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Imprink.Domain.Entities.Orders.Order", b =>
|
||||
@@ -193,7 +193,7 @@ namespace Imprink.Infrastructure.Migrations
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "UserRoles",
|
||||
name: "UserRole",
|
||||
columns: table => new
|
||||
{
|
||||
UserId = table.Column<string>(type: "nvarchar(450)", maxLength: 450, nullable: false),
|
||||
@@ -201,15 +201,15 @@ namespace Imprink.Infrastructure.Migrations
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_UserRoles", x => new { x.UserId, x.RoleId });
|
||||
table.PrimaryKey("PK_UserRole", x => new { x.UserId, x.RoleId });
|
||||
table.ForeignKey(
|
||||
name: "FK_UserRoles_Roles_RoleId",
|
||||
name: "FK_UserRole_Roles_RoleId",
|
||||
column: x => x.RoleId,
|
||||
principalTable: "Roles",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
table.ForeignKey(
|
||||
name: "FK_UserRoles_Users_UserId",
|
||||
name: "FK_UserRole_Users_UserId",
|
||||
column: x => x.UserId,
|
||||
principalTable: "Users",
|
||||
principalColumn: "Id",
|
||||
@@ -630,12 +630,12 @@ namespace Imprink.Infrastructure.Migrations
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_UserRole_RoleId",
|
||||
table: "UserRoles",
|
||||
table: "UserRole",
|
||||
column: "RoleId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_UserRole_UserId",
|
||||
table: "UserRoles",
|
||||
table: "UserRole",
|
||||
column: "UserId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
@@ -663,7 +663,7 @@ namespace Imprink.Infrastructure.Migrations
|
||||
name: "OrderItems");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "UserRoles");
|
||||
name: "UserRole");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Orders");
|
||||
@@ -822,7 +822,7 @@ namespace Imprink.Infrastructure.Migrations
|
||||
b.HasIndex("UserId")
|
||||
.HasDatabaseName("IX_UserRole_UserId");
|
||||
|
||||
b.ToTable("UserRoles");
|
||||
b.ToTable("UserRole");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Imprink.Domain.Entities.Orders.Order", b =>
|
||||
|
||||
@@ -9,7 +9,7 @@ public class UserRoleRepository(ApplicationDbContext context) : IUserRoleReposit
|
||||
{
|
||||
public async Task<IEnumerable<Role>> GetUserRolesAsync(string userId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await context.UserRoles
|
||||
return await context.UserRole
|
||||
.AsNoTracking()
|
||||
.Where(ur => ur.UserId == userId)
|
||||
.Select(ur => ur.Role)
|
||||
@@ -18,7 +18,7 @@ public class UserRoleRepository(ApplicationDbContext context) : IUserRoleReposit
|
||||
|
||||
public async Task<IEnumerable<User>> GetUsersInRoleAsync(Guid roleId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await context.UserRoles
|
||||
return await context.UserRole
|
||||
.AsNoTracking()
|
||||
.Where(ur => ur.RoleId == roleId)
|
||||
.Select(ur => ur.User)
|
||||
@@ -27,32 +27,32 @@ public class UserRoleRepository(ApplicationDbContext context) : IUserRoleReposit
|
||||
|
||||
public async Task<bool> IsUserInRoleAsync(string userId, Guid roleId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await context.UserRoles
|
||||
return await context.UserRole
|
||||
.AnyAsync(ur => ur.UserId == userId && ur.RoleId == roleId, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<UserRole?> GetUserRoleAsync(string userId, Guid roleId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await context.UserRoles
|
||||
return await context.UserRole
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(ur => ur.UserId == userId && ur.RoleId == roleId, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task AddUserRoleAsync(UserRole userRole, CancellationToken cancellationToken = default)
|
||||
{
|
||||
context.UserRoles.Add(userRole);
|
||||
context.UserRole.Add(userRole);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task RemoveUserRoleAsync(UserRole userRole, CancellationToken cancellationToken = default)
|
||||
{
|
||||
context.UserRoles.Remove(userRole);
|
||||
context.UserRole.Remove(userRole);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<UserRole>> GetUserRolesByUserIdAsync(string userId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await context.UserRoles
|
||||
return await context.UserRole
|
||||
.AsNoTracking()
|
||||
.Where(ur => ur.UserId == userId)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using System.Security.Claims;
|
||||
using Imprink.Domain.Common.Models;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
@@ -15,16 +13,11 @@ public class UserController : ControllerBase
|
||||
{
|
||||
var claims = User.Claims;
|
||||
|
||||
var enumerable = claims as Claim[] ?? claims.ToArray();
|
||||
var user = new Auth0User
|
||||
foreach (var claim in claims)
|
||||
{
|
||||
Sub = enumerable.FirstOrDefault(c => c.Type == "sub")?.Value ?? "",
|
||||
Name = enumerable.FirstOrDefault(c => c.Type == "name")?.Value ?? "",
|
||||
Nickname = enumerable.FirstOrDefault(c => c.Type == "nickname")?.Value ?? "",
|
||||
Email = enumerable.FirstOrDefault(c => c.Type == "email")?.Value ?? "",
|
||||
EmailVerified = enumerable.FirstOrDefault(c => c.Type == "email_verified")?.Value == "true"
|
||||
};
|
||||
|
||||
return Ok(user);
|
||||
Console.WriteLine($"Claim Type: {claim.Type}, Claim Value: {claim.Value}");
|
||||
}
|
||||
|
||||
return Ok("Claims logged to console.");
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Security.Claims;
|
||||
using Imprink.Application;
|
||||
using Imprink.Application.Products.Create;
|
||||
using Imprink.Domain.Repositories;
|
||||
@@ -41,6 +42,34 @@ public static class Startup
|
||||
{
|
||||
options.Authority = builder.Configuration["Auth0:Authority"];
|
||||
options.Audience = builder.Configuration["Auth0:Audience"];
|
||||
|
||||
options.Events = new JwtBearerEvents
|
||||
{
|
||||
OnMessageReceived = context =>
|
||||
{
|
||||
var token = context.Request.Cookies["access_token"];
|
||||
if (!string.IsNullOrEmpty(token)) context.Token = token;
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
OnTokenValidated = context =>
|
||||
{
|
||||
var dbContext = context.HttpContext.RequestServices.GetService<ApplicationDbContext>();
|
||||
var userId = context.Principal?.FindFirst(ClaimTypes.NameIdentifier)?.Value
|
||||
?? context.Principal?.FindFirst("sub")?.Value;
|
||||
|
||||
if (string.IsNullOrEmpty(userId)) return Task.CompletedTask;
|
||||
var identity = context.Principal!.Identity as ClaimsIdentity;
|
||||
|
||||
var roles = (from ur in dbContext?.UserRole
|
||||
join r in dbContext?.Roles on ur.RoleId equals r.Id
|
||||
where ur.UserId == userId
|
||||
select r.RoleName).ToList();
|
||||
|
||||
foreach (var role in roles) identity!.AddClaim(new Claim(ClaimTypes.Role, role));
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
services.AddAuthorization();
|
||||
|
||||
Reference in New Issue
Block a user