fa485d902b
* Added first centralized database config and added machine self-registration into db * Fix database migration with new database * Refactor
75 lines
2.7 KiB
C#
75 lines
2.7 KiB
C#
using System;
|
|
using System.Linq;
|
|
using System.Security.Claims;
|
|
using System.Web.Http;
|
|
using System.Web.Http.Controllers;
|
|
using Step.Database.Controllers;
|
|
using Step.Config;
|
|
using static Step.Utils.Constants;
|
|
using Step.Model.DatabaseModels;
|
|
using static Step.Config.ServerConfig;
|
|
|
|
namespace Step
|
|
{
|
|
class WebApiAuthorizeAttribute : AuthorizeAttribute
|
|
{
|
|
public string FunctionAccess;
|
|
public ACTIONS Action;
|
|
protected override bool IsAuthorized(HttpActionContext actionContext)
|
|
{
|
|
if (!base.IsAuthorized(actionContext))
|
|
return false;
|
|
|
|
// Get user level stored in the bearer token
|
|
ClaimsPrincipal principal = actionContext.RequestContext.Principal as ClaimsPrincipal;
|
|
var userRoleLevel = principal.Claims.Where(c => c.Type == ROLE_LEVEL_KEY).SingleOrDefault();
|
|
|
|
// Get machine unique id stored in the bearer token
|
|
var machineUniqueId = principal.Claims.Where(c => c.Type == MACHINE_ID_KEY).SingleOrDefault();
|
|
|
|
// User data not found -> not authorized
|
|
if (userRoleLevel == null || machineUniqueId == null)
|
|
return false;
|
|
|
|
// check authorization
|
|
if (!CheckAuthorization(machineUniqueId.Value.ToString(), Convert.ToInt32(userRoleLevel.Value), FunctionAccess))
|
|
return false;
|
|
|
|
return true;
|
|
}
|
|
|
|
private bool CheckAuthorization(string machineUniqueId, int userLevel, string functionName)
|
|
{
|
|
using (FunctionAccessController acController = new FunctionAccessController())
|
|
{
|
|
// Check if the machine is the same where the user logged in
|
|
if (machineUniqueId != MachineConfig.UniqueId)
|
|
return false;
|
|
|
|
// Read from db category levels
|
|
FunctionAccessModel functionAccess = acController.FindEnabledFunctionByName(functionName);
|
|
if (functionAccess != null && ServerConfigController.CheckAreaStatus(functionAccess.Area))
|
|
{
|
|
if (Action == ACTIONS.READ)
|
|
{ // Check read permissions
|
|
if (functionAccess.ReadLevelMin > userLevel)
|
|
return false; // Not authorized
|
|
}
|
|
else
|
|
{ // Check write permissions
|
|
if (functionAccess.WriteLevelMin > userLevel)
|
|
return false; // Not authorized
|
|
}
|
|
}
|
|
else
|
|
{
|
|
return false;
|
|
}
|
|
|
|
// Authorized
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
}
|