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 Step.Model.DatabaseModels; using static Step.Config.ServerConfig; using static Step.Model.Constants; namespace Step { class WebApiAuthorizeAttribute : AuthorizeAttribute { public string FunctionAccess; public ACTIONS Action; protected override bool IsAuthorized(HttpActionContext actionContext) { if (!base.IsAuthorized(actionContext)) return false; // Get claims from token ClaimsPrincipal principal = actionContext.RequestContext.Principal as ClaimsPrincipal; // Get user id stored in the bearer token var userId = principal.Claims.Where(c => c.Type == USER_ID_KEY).FirstOrDefault(); // Get machine unique id stored in the bearer token var machineId = principal.Claims.Where(c => c.Type == MACHINE_ID_KEY).FirstOrDefault(); //User data not found -> not authorized if (userId == null || machineId == null) return false; // Get token from headers string token = actionContext.Request.Headers.Authorization.ToString(); token = token.Split(' ')[1]; // check authorization if (!CheckAuthorization(Convert.ToInt32(machineId.Value), Convert.ToInt32(userId.Value), FunctionAccess, token)) return false; return true; } private bool CheckAuthorization(int machineId, int userId, string functionName, string token) { // Check if the machine is the same where the user logged in if (machineId != MachineConfig.MachineId) return false; using (SessionsController sessionsController = new SessionsController()) { // Find user session on this machine SessionModel session = sessionsController.FindSessionByToken(token); if (session == null) return false; MachineUserModel machineUser = new MachineUserModel(); using (MachinesUsersController machineUsersController = new MachinesUsersController()) { // Find machineUser data and joined to user data, role data, machine data machineUser = machineUsersController.FindByIdWithData(session.MachineUserId); } using (FunctionsAccessController acController = new FunctionsAccessController()) { // Read from db function levels FunctionAccessModel functionAccess = acController.FindEnabledFunctionByName(functionName); if (functionAccess != null && ServerConfigController.CheckAreaStatus(functionAccess.Area)) { if (Action == ACTIONS.READ) { // Check read permissions if (functionAccess.ReadLevelMin > machineUser.Role.Level) return false; // Not authorized } else { // Check write permissions if (functionAccess.WriteLevelMin > machineUser.Role.Level) return false; // Not authorized } } else return false; // Authorized return true; } } } } }