This is my first WIP backend asp.net application, which I will pair with react to create a full stack app. The thing I'm mostly worried about is model conversion to DTO and custom policy authorization, as It has 2 contexts I feel like it's bloated, and hacked. I will be grateful for any tips, from experienced developers, as I have no real commercial experience, and I am self-taught.
Custom authorization:
public class FamilyHeadOnlyHandler : AuthorizationHandler<FamilyHeadOnlyRequirement> { private readonly IHttpContextAccessor _httpContextAccessor; private readonly FamilyManDbContext _databaseContext; private readonly UserManager<ApplicationUser> _userManager; public FamilyHeadOnlyHandler( IHttpContextAccessor httpContextAccessor, FamilyManDbContext databaseContext, UserManager<ApplicationUser> userManager ) { _httpContextAccessor = httpContextAccessor; _databaseContext = databaseContext; _userManager = userManager; } protected override async Task HandleRequirementAsync( AuthorizationHandlerContext context, FamilyHeadOnlyRequirement requirement) { var currentUserId = context.User.FindFirst(c => c.Type == ClaimTypes.NameIdentifier)?.Value; var requestedFamilyId = _httpContextAccessor.HttpContext!.GetRouteValue("id")!.ToString(); var requestedFamily = await _databaseContext.Families!.Include("Head").FirstOrDefaultAsync(f => f.Id.ToString() == requestedFamilyId); if (requestedFamily == null) { throw new NotFoundException("Family not found."); } if (requestedFamily!.Head!.Id == currentUserId) { context.Succeed(requirement); } } }
I'm aware, that most people use Allman indentation convention, but I'm used to C, C++ and JavaScript's K&R standard. And I might need to start Allman in my C# code.
Link to the repo, which contains full code: Github repo
Edit: AuthorizationHandlerContext
context is default context of overriden method, it has currentUser
property, but lacks things such as route value, ability to manipulate cookies, and so on, unlike HttpContextAccessor
. Now the second thing is, userManager
is part of IdentityContext
, which is in my databaseContext
. I probably could use _dataBaseContext
instead of _userManager
to manipulate user, but the _userManager
is built in, whereas databaseContext
is my own context. It feels like bloated code to me. I would like to know, if this is good by design, or should I change it. Is the code readable?