fix: migrate to IDbContextFactory and remove direct AppDbContext from DI (#11)
Reviewed-on: #11 Co-authored-by: Marek Jasiński <jasins.marek@gmail.com> Co-committed-by: Marek Jasiński <jasins.marek@gmail.com>
This commit was merged in pull request #11.
This commit is contained in:
@@ -2,7 +2,8 @@ using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using NexusReader.Domain.Entities;
|
||||
using NexusReader.Infrastructure.Persistence;
|
||||
using NexusReader.Data.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace NexusReader.Infrastructure.Identity;
|
||||
|
||||
@@ -11,12 +12,12 @@ namespace NexusReader.Infrastructure.Identity;
|
||||
/// </summary>
|
||||
public class TokenLimitHandler : AuthorizationHandler<TokenLimitRequirement>
|
||||
{
|
||||
private readonly AppDbContext _dbContext;
|
||||
private readonly IDbContextFactory<AppDbContext> _dbContextFactory;
|
||||
private readonly UserManager<NexusUser> _userManager;
|
||||
|
||||
public TokenLimitHandler(AppDbContext dbContext, UserManager<NexusUser> userManager)
|
||||
public TokenLimitHandler(IDbContextFactory<AppDbContext> dbContextFactory, UserManager<NexusUser> userManager)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
_dbContextFactory = dbContextFactory;
|
||||
_userManager = userManager;
|
||||
}
|
||||
|
||||
@@ -30,14 +31,18 @@ public class TokenLimitHandler : AuthorizationHandler<TokenLimitRequirement>
|
||||
return;
|
||||
}
|
||||
|
||||
var user = await _userManager.FindByIdAsync(userId);
|
||||
using var db = _dbContextFactory.CreateDbContext();
|
||||
var user = await db.Users
|
||||
.Include(u => u.SubscriptionPlan)
|
||||
.FirstOrDefaultAsync(u => u.Id == userId);
|
||||
|
||||
if (user == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if user has available tokens
|
||||
if (user.AITokensUsed < user.AITokenLimit)
|
||||
// Check if user has available tokens or unlimited plan
|
||||
if (user.SubscriptionPlan?.IsUnlimitedTokens == true || user.AITokensUsed < user.AITokenLimit)
|
||||
{
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user