fa485d902b
* Added first centralized database config and added machine self-registration into db * Fix database migration with new database * Refactor
76 lines
2.7 KiB
C#
76 lines
2.7 KiB
C#
using System;
|
|
using System.Linq;
|
|
using System.Security.Claims;
|
|
using System.Security.Principal;
|
|
using Microsoft.AspNet.SignalR;
|
|
using Step.Config;
|
|
using Step.Database.Controllers;
|
|
using Step.Model.DatabaseModels;
|
|
using static Step.Utils.Constants;
|
|
using static Step.Config.ServerConfig;
|
|
|
|
namespace Step.Attributes
|
|
{
|
|
class SignalRAuthorizeAttribute : AuthorizeAttribute
|
|
{
|
|
public string FunctionAccess;
|
|
public ACTIONS Action;
|
|
|
|
protected override bool UserAuthorized(IPrincipal user)
|
|
{
|
|
if (!base.UserAuthorized(user))
|
|
return false;
|
|
|
|
// Get user level stored in the bearer token
|
|
ClaimsIdentity identity = user.Identity as ClaimsIdentity;
|
|
var userRoleLevel = identity.Claims.Where(c => c.Type == ROLE_LEVEL_KEY).SingleOrDefault();
|
|
|
|
// Get machine unique id stored in the bearer token
|
|
var machineUniqueId = identity.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.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;
|
|
}
|
|
}
|
|
}
|