using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using RSecurityBackend.Models.Generic; using RSecurityBackend.Services; namespace RSecurityBackend.Controllers { /// /// base class for controllers needing UserScopeCheck /// public abstract class UserScopeCheckEnabledControllerBase : Controller { /// /// UserScopeCheck method EntityShortName; /// /// /// RBillingSecurableItem.TenantEntityShortName /// protected abstract string UserScopeCheckEntityShortName { get; } /// /// UserScopeCheck method OperationShortName /// /// /// SecurableItem.ViewOperationShortName /// protected abstract string UserScopeCheckOperationShortName { get; } /// /// returns user id if user is a guest, and empty if he/she has access to view all users information /// /// protected async Task> GetUserIdUnlessUserHavePermissionToReadAllUsersDataWhichReturnEmptyUserId() { Guid userId = new Guid(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value); RServiceResult canReadAllUsersData = await _userPermissionChecker.Check ( userId, new Guid(User.Claims.FirstOrDefault(c => c.Type == "SessionId").Value), UserScopeCheckEntityShortName, UserScopeCheckOperationShortName ); if (!string.IsNullOrEmpty(canReadAllUsersData.ExceptionString)) return new RServiceResult(userId, canReadAllUsersData.ExceptionString); if (canReadAllUsersData.Result) { userId = Guid.Empty; } return new RServiceResult(userId); } /// /// can current user read this userId daya /// /// /// protected async Task> CanReadUserData(Guid userId) { RServiceResult scopeForUserId = await GetUserIdUnlessUserHavePermissionToReadAllUsersDataWhichReturnEmptyUserId(); if(!string.IsNullOrEmpty(scopeForUserId.ExceptionString)) { return new RServiceResult(false, scopeForUserId.ExceptionString); } return new RServiceResult(scopeForUserId.Result == Guid.Empty || scopeForUserId.Result == userId); } /// /// Permission Checker Service /// protected readonly IUserPermissionChecker _userPermissionChecker; /// /// constructor /// /// public UserScopeCheckEnabledControllerBase(IUserPermissionChecker userPermissionChecker) { _userPermissionChecker = userPermissionChecker; } } }