Refactored all Policy strings into their own constant file.

This commit is contained in:
Joseph Milazzo 2020-12-24 10:21:59 -06:00
parent a40bc9e9f7
commit 793c13e1e6
4 changed files with 15 additions and 4 deletions

View File

@ -0,0 +1,8 @@
namespace API.Constants
{
public static class PolicyConstants
{
public static readonly string AdminRole = "Admin";
public static readonly string PlebRole = "Pleb";
}
}

View File

@ -1,5 +1,6 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using API.Constants;
using API.DTOs; using API.DTOs;
using API.Entities; using API.Entities;
using API.Interfaces; using API.Interfaces;
@ -50,7 +51,7 @@ namespace API.Controllers
// TODO: Need a way to store Roles in enum and configure from there // TODO: Need a way to store Roles in enum and configure from there
var role = registerDto.IsAdmin ? "Admin" : "Pleb"; var role = registerDto.IsAdmin ? PolicyConstants.AdminRole : PolicyConstants.PlebRole;
var roleResult = await _userManager.AddToRoleAsync(user, role); var roleResult = await _userManager.AddToRoleAsync(user, role);
if (!roleResult.Succeeded) return BadRequest(result.Errors); if (!roleResult.Succeeded) return BadRequest(result.Errors);

View File

@ -1,5 +1,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using API.Constants;
using API.Entities; using API.Entities;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
@ -11,8 +12,8 @@ namespace API.Data
{ {
var roles = new List<AppRole> var roles = new List<AppRole>
{ {
new AppRole {Name = "Admin"}, new AppRole {Name = PolicyConstants.AdminRole},
new AppRole {Name = "Pleb"} new AppRole {Name = PolicyConstants.PlebRole}
}; };
foreach (var role in roles) foreach (var role in roles)

View File

@ -1,4 +1,5 @@
using System.Text; using System.Text;
using API.Constants;
using API.Data; using API.Data;
using API.Entities; using API.Entities;
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.JwtBearer;
@ -37,7 +38,7 @@ namespace API.Extensions
}); });
services.AddAuthorization(opt => services.AddAuthorization(opt =>
{ {
opt.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin")); opt.AddPolicy("RequireAdminRole", policy => policy.RequireRole(PolicyConstants.AdminRole));
}); });
return services; return services;