protected override async Task <PermissionResult> CanDeleteAsync(Organization value)
    {
        if (!String.IsNullOrEmpty(value.StripeCustomerId) && !User.IsInRole(AuthorizationRoles.GlobalAdmin))
        {
            return(PermissionResult.DenyWithMessage("An organization cannot be deleted if it has a subscription.", value.Id));
        }

        var projects = (await _projectRepository.GetByOrganizationIdAsync(value.Id)).Documents.ToList();

        if (!User.IsInRole(AuthorizationRoles.GlobalAdmin) && projects.Any())
        {
            return(PermissionResult.DenyWithMessage("An organization cannot be deleted if it contains any projects.", value.Id));
        }

        return(await base.CanDeleteAsync(value));
    }
Esempio n. 2
0
        public static PermissionResult CanAddHeader(MainContext context, AgendaHeader header, IEnumerable <AgendaHeader> headers)
        {
            if (header == null)
            {
                throw new ArgumentNullException(nameof(header));
            }
            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            var result = Validator.ValidateNotEmpty(header.Name, @"HeaderNameIsRequired");

            if (result != PermissionResult.Allow)
            {
                return(result);
            }
            var name = (header.Name ?? string.Empty).Trim();

            foreach (var h in headers)
            {
                if (h.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
                {
                    return(PermissionResult.Deny(@"HeaderWithTheSameNameAlreadyExists"));
                }
            }
            var values = GetData(context);

            //context.Log(nameof(IsAgendaHeaderExists), LogLevel.Info);
            if (IsAgendaHeaderExists(values, name))
            {
                return(PermissionResult.Deny(@"HeaderWithTheSameNameAlreadyExists"));
            }
            var date = header.DateTime.Date;

            //context.Log(nameof(IsDateExists), LogLevel.Info);
            if (IsDateExists(values, date))
            {
                return(PermissionResult.Deny(@"HeaderWithTheSameDateAlreadyExists"));
            }
            // TODO : Parameter ???
            if (date < DateTime.Today.AddDays(-30))
            {
                return(PermissionResult.Confirm(@"HeaderDateConfirmTooOld"));
            }
            return(PermissionResult.Allow);
        }
Esempio n. 3
0
        public PermissionResult CheckHasAnyPermission(IIdentity target, params string[] permissions)
        {
            GuardTarget(target);

            foreach (IPermissionProvider provider in ProxiedServices.Where(c => c.SupportsTarget(target)))
            {
                PermissionResult result = provider.CheckHasAnyPermission(target, permissions);
                if (result == PermissionResult.Default)
                {
                    continue;
                }

                return(result);
            }

            return(PermissionResult.Default);
        }
Esempio n. 4
0
        public override bool PreRender()
        {
            if (this.Status != RenderStatus.None)
            {
                return(false);
            }
            this.Status = RenderStatus.Rendering;

            PermissionResult permissionResult =
                this.EnsurePermission();

            this._SelectedContent =
                permissionResult.Result == PermissionResult.Results.Allowed ? ContentTypes.Allowed : ContentTypes.Forbidden;
            this.Parse();

            return(this._HasStatementContent);
        }
Esempio n. 5
0
        //public PermissionResult CanCreate(Outlet outlet, ActivityType activityType)
        //{
        //	if (outlet == null)
        //	{
        //		return PermissionResult.Deny(@"MissingOutlet");
        //	}
        //	if (activityType == null)
        //	{
        //		return PermissionResult.Deny(@"MissingActivityType");
        //	}
        //	if (outlet.Id > 0 && activityType.Id > 0)
        //	{
        //		return PermissionResult.Confirm(@"Confirm activity type for this outlet?");
        //	}
        //	return PermissionResult.Allow;
        //}

        //public Activity Create(DataQueryContext context, Outlet outlet, ActivityType type, ActivityStatus status, DateTime date)
        //{
        //	if (context == null) throw new ArgumentNullException(nameof(context));
        //	if (type == null) throw new ArgumentNullException(nameof(type));
        //	if (status == null) throw new ArgumentNullException(nameof(status));
        //	if (outlet == null) throw new ArgumentNullException(nameof(outlet));

        //	var activity = new Activity(0, outlet, type, status, date, date, string.Empty);

        //	// Save activity to db
        //	var newActivity = this.DataProvider.Insert(context, activity);

        //	// Find item by outlet
        //	var agendaOutlet = default(AgendaOutlet);
        //	foreach (var o in this.Outlets)
        //	{
        //		if (o.Outlet == outlet)
        //		{
        //			agendaOutlet = o;
        //			break;
        //		}
        //	}
        //	// We don't have it
        //	if (agendaOutlet == null)
        //	{
        //		// Create it
        //		agendaOutlet = new AgendaOutlet(outlet, new List<Activity>());

        //		// Add to the collection
        //		this.Outlets.Add(agendaOutlet);
        //	}

        //	// Insert into the collection
        //	agendaOutlet.Activities.Add(newActivity);

        //	this.ActivityAdded?.Invoke(this, new ActivityEventArgs(newActivity));

        //	return newActivity;
        //}

        public PermissionResult CanCancel(Activity activity, ActivityCancelReason cancelReason)
        {
            if (activity == null)
            {
                throw new ArgumentNullException(nameof(activity));
            }

            if (activity.Status == null)
            {
                return(PermissionResult.Deny(@"CannotCancelInactiveActivity"));
            }
            // Check the day
            // TODO : !!!
            //var visitDay = this.DataProvider.GetVisitDay(DateTime.Today);

            return(PermissionResult.Allow);
        }
Esempio n. 6
0
        public PermissionResult CanChangeStartTime(Activity activity, DateTime dateTime)
        {
            if (activity == null)
            {
                throw new ArgumentNullException(nameof(activity));
            }

            if (activity.Details == string.Empty)
            {
                return(PermissionResult.Deny(@"CannotChangeDateOfServerActivity"));
            }
            if (activity.Details == @"???")
            {
                return(PermissionResult.Confirm(@"OutsideOfWorkingHours"));
            }
            return(PermissionResult.Allow);
        }
    public virtual void OnRequestPermissionsResult(AndroidJavaObject resultWrapper)
    {
        if (OnPermissionRequestResultCallback != null)
        {
            AndroidJavaObject[] rawResults = resultWrapper.Get <AndroidJavaObject[]>("results");
            PermissionResult[]  results    = new PermissionResult[rawResults.Length];

            for (int i = 0; i < rawResults.Length; i++)
            {
                results[i] = new PermissionResult();
                results[i].permissionName    = rawResults[i].Get <string>("permissionName");
                results[i].permissionGranted = rawResults[i].Get <bool>("permissionGranted");
                results[i].neverAskAgain     = rawResults[i].Get <bool>("neverAskAgain");
            }

            OnPermissionRequestResultCallback(results);
        }
    }
Esempio n. 8
0
        public async Task <PermissionResult> CheckPermissionAsync(IPermissionActor target, string permission)
        {
            GuardTarget(target);

            foreach (IPermissionChecker provider in ProxiedServices.Where(c => c.SupportsTarget(target)))
            {
                PermissionResult result = await provider.CheckPermissionAsync(target, permission);

                if (result == PermissionResult.Default)
                {
                    continue;
                }

                return(result);
            }

            return(PermissionResult.Default);
        }
Esempio n. 9
0
        public async Task <PermissionResult> CheckHasAllPermissionsAsync(IPermissionEntity target, params string[] permissions)
        {
            GuardTarget(target);

            foreach (IPermissionProvider provider in ProxiedServices.Where(c => c.SupportsTarget(target)))
            {
                PermissionResult result = await provider.CheckHasAllPermissionsAsync(target, permissions);

                if (result == PermissionResult.Default)
                {
                    continue;
                }

                return(result);
            }

            return(PermissionResult.Default);
        }
Esempio n. 10
0
        public PermissionResult CanAdd(Login login)
        {
            if (login == null)
            {
                throw new ArgumentNullException("login");
            }

            // Trim the username
            var username = (login.Username ?? string.Empty).Trim();

            if (this.IsSystem(login))
            {
                return(PermissionResult.Deny(this.Settings.UsernameIsReservedForInternalUseMsg));
            }

            // Check for duplicate username
            // Check in the database ?!?? Do we need the field ?!
            foreach (var current in _logins)
            {
                if (current.Username.Equals(username, StringComparison.OrdinalIgnoreCase))
                {
                    return(PermissionResult.Deny(this.Settings.UsernameAlreadyTakenMsg));
                }
            }

            // Check password strength
            var strength = GetPasswordStrength(login.Password);

            switch (strength)
            {
            case PasswordStrength.Weak:
                return(PermissionResult.Deny(this.Settings.PasswordTooWeakMsg));

            case PasswordStrength.Medium:
                return(PermissionResult.Confirm(this.Settings.ConfirmPasswordMediumStrengthMsg));

            case PasswordStrength.Good:
            case PasswordStrength.Strong:
                return(PermissionResult.Allow);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
    protected override async Task <PermissionResult> CanAddAsync(Organization value)
    {
        if (String.IsNullOrEmpty(value.Name))
        {
            return(PermissionResult.DenyWithMessage("Organization name is required."));
        }

        if (!await IsOrganizationNameAvailableInternalAsync(value.Name))
        {
            return(PermissionResult.DenyWithMessage("A organization with this name already exists."));
        }

        if (!await _billingManager.CanAddOrganizationAsync(CurrentUser))
        {
            return(PermissionResult.DenyWithPlanLimitReached("Please upgrade your plan to add an additional organization."));
        }

        return(await base.CanAddAsync(value));
    }
    private static void RequestPermissionAsync(string permission, PermissionResult callback)
    {
#if IS_ANDROID_PLATFORM
        RequestPermissionsAsync(new string[1] {
            permission
        }, (permissions, result) =>
        {
            if (callback != null)
            {
                callback(permissions[0], result[0]);
            }
        });
#else
        if (callback != null)
        {
            callback(permission, Permission.Granted);
        }
#endif
    }
Esempio n. 13
0
    protected override async Task <PermissionResult> CanAddAsync(Project value)
    {
        if (String.IsNullOrEmpty(value.Name))
        {
            return(PermissionResult.DenyWithMessage("Project name is required."));
        }

        if (!await IsProjectNameAvailableInternalAsync(value.OrganizationId, value.Name))
        {
            return(PermissionResult.DenyWithMessage("A project with this name already exists."));
        }

        if (!await _billingManager.CanAddProjectAsync(value))
        {
            return(PermissionResult.DenyWithPlanLimitReached("Please upgrade your plan to add additional projects."));
        }

        return(await base.CanAddAsync(value));
    }
Esempio n. 14
0
        /// <summary>
        ///     Checks if the target has all of the given permissions.
        /// </summary>
        /// <param name="permissionChecker">The permission checker.</param>
        /// <param name="target">The target to check.</param>
        /// <param name="permissions">The permissions to check.</param>
        /// <returns>
        ///     <see cref="PermissionResult.Grant" /> if the target explicity has access to all of the given permissions,
        ///     <see cref="PermissionResult.Deny" /> if the target explicitly does not have access to any of the permissions;
        ///     otherwise, <see cref="PermissionResult.Default" />
        /// </returns>
        public static async Task <PermissionResult> CheckHasAllPermissionsAsync(this IPermissionChecker permissionChecker, IPermissionActor target, params string[] permissions)
        {
            PermissionResult result = PermissionResult.Grant;

            foreach (string permission in permissions)
            {
                PermissionResult tmp = await permissionChecker.CheckPermissionAsync(target, permission);

                if (tmp == PermissionResult.Deny)
                {
                    return(PermissionResult.Deny);
                }

                if (tmp == PermissionResult.Default)
                {
                    result = PermissionResult.Default;
                }
            }

            return(result);
        }
Esempio n. 15
0
        protected override PermissionResult CanAdd(WebHook value)
        {
            if (String.IsNullOrEmpty(value.ProjectId) || String.IsNullOrEmpty(value.Url) || value.EventTypes.Length == 0)
            {
                return(PermissionResult.Deny);
            }

            Project project = _projectRepository.GetById(value.ProjectId, true);

            if (!IsInProject(project))
            {
                return(PermissionResult.Deny);
            }

            if (!_billingManager.CanAddIntegration(project))
            {
                return(PermissionResult.DenyWithPlanLimitReached("Please upgrade your plan to add integrations."));
            }

            return(base.CanAdd(value));
        }
Esempio n. 16
0
        public PermissionResult Assign(List <int> permissions, int userId, UserSessionObject currentUser)
        {
            bool       flag            = true;
            var        wrongIds        = new List <int>();
            List <int> alreadyAssigned = RelationUserPermissionRepository
                                         .GetRelationUserPermissionFor(userId)
                                         .Select(x => x.PermissionId)
                                         .ToList();
            PermissionResult result = null;

            foreach (int permissionId in permissions)
            {
                if (!alreadyAssigned.Contains(permissionId))
                {
                    var newLink = new RelationUserPermissionData
                    {
                        PermissionId     = permissionId,
                        UserId           = userId,
                        RefUserCreatedBy = currentUser.UserId
                    };
                    RelationUserPermissionRepository.SaveData(newLink);
                }
                else
                {
                    flag = false;
                    wrongIds.Add(permissionId);
                }
            }

            if (!flag)
            {
                result = new PermissionResult(false, PermissionResult.OperationType.Assign, wrongIds);
            }
            else
            {
                result = new PermissionResult(true, PermissionResult.OperationType.Assign);
            }

            return(result);
        }
Esempio n. 17
0
        protected override PermissionResult CanAdd(WebHook value)
        {
            if (String.IsNullOrEmpty(value.Url) || value.EventTypes.Length == 0)
            {
                return(PermissionResult.Deny);
            }

            if (String.IsNullOrEmpty(value.ProjectId) && String.IsNullOrEmpty(value.OrganizationId))
            {
                return(PermissionResult.Deny);
            }

            Project project = null;

            if (!String.IsNullOrEmpty(value.ProjectId))
            {
                project = _projectRepository.GetById(value.ProjectId, true);
                if (!IsInProject(project))
                {
                    return(PermissionResult.Deny);
                }

                if (!String.IsNullOrEmpty(value.OrganizationId))
                {
                    value.OrganizationId = project.OrganizationId;
                }
            }
            else if (!IsInOrganization(value.OrganizationId))
            {
                return(PermissionResult.Deny);
            }

            if (!_billingManager.HasPremiumFeatures(project != null ? project.OrganizationId : value.OrganizationId))
            {
                return(PermissionResult.DenyWithPlanLimitReached("Please upgrade your plan to add integrations."));
            }

            return(base.CanAdd(value));
        }
Esempio n. 18
0
        protected override async Task <PermissionResult> CanAddAsync(WebHook value)
        {
            if (String.IsNullOrEmpty(value.Url) || value.EventTypes.Length == 0)
            {
                return(PermissionResult.Deny);
            }

            if (String.IsNullOrEmpty(value.ProjectId) && String.IsNullOrEmpty(value.OrganizationId))
            {
                return(PermissionResult.Deny);
            }

            if (!String.IsNullOrEmpty(value.OrganizationId) && !IsInOrganization(value.OrganizationId))
            {
                return(PermissionResult.DenyWithMessage("Invalid organization id specified."));
            }

            Project project = null;

            if (!String.IsNullOrEmpty(value.ProjectId))
            {
                project = await GetProjectAsync(value.ProjectId);

                if (project == null)
                {
                    return(PermissionResult.DenyWithMessage("Invalid project id specified."));
                }

                value.OrganizationId = project.OrganizationId;
            }

            if (!await _billingManager.HasPremiumFeaturesAsync(project != null ? project.OrganizationId : value.OrganizationId))
            {
                return(PermissionResult.DenyWithPlanLimitReached("Please upgrade your plan to add integrations."));
            }

            return(PermissionResult.Allow);
        }
Esempio n. 19
0
        /// <summary>
        ///     Checks if the target has any of the given permissions.
        /// </summary>
        /// <param name="permissionChecker">The permission checker.</param>
        /// <param name="target">The target to check.</param>
        /// <param name="permissions">The permissions to check.</param>
        /// <returns>
        ///     <see cref="PermissionResult.Grant" /> if the target explicity has access to any of the given permissions,
        ///     <see cref="PermissionResult.Deny" /> if the target explicitly does not have access to any of the permissions;
        ///     otherwise, <see cref="PermissionResult.Default" />
        /// </returns>
        public static async Task <PermissionResult> CheckHasAnyPermissionAsync(this IPermissionChecker permissionChecker, IPermissionActor target, params string[] permissions)
        {
            foreach (string permission in permissions)
            {
                Console.WriteLine("Checking: " + permission);

                PermissionResult result = await permissionChecker.CheckPermissionAsync(target, permission);

                if (result == PermissionResult.Deny)
                {
                    Console.WriteLine("Denied: " + permission);
                    return(PermissionResult.Deny);
                }
                if (result == PermissionResult.Grant)
                {
                    Console.WriteLine("Granted: " + permission);
                    return(PermissionResult.Grant);
                }
            }

            Console.WriteLine("Default: " + permissions);
            return(PermissionResult.Default);
        }
Esempio n. 20
0
        public PermissionResult Remove(List <int> permissions, int userId, UserSessionObject currentUser)
        {
            bool       flag            = true;
            var        wrongIds        = new List <int>();
            var        result          = new PermissionResult();
            List <int> alreadyAssigned = RelationUserPermissionRepository
                                         .GetRelationUserPermissionFor(userId)
                                         .Select(x => x.PermissionId)
                                         .ToList();

            foreach (int permissionId in permissions)
            {
                if (!alreadyAssigned.Contains(permissionId))
                {
                    flag = false;
                    wrongIds.Add(permissionId);
                }
                else
                {
                    var data = RelationUserPermissionRepository.GetRelationUserPermissionFor(userId, permissionId);
                    RelationUserPermissionRepository.DeleteById(data.Id, currentUser.UserId);
                }
            }

            if (!flag)
            {
                result = new PermissionResult(false, PermissionResult.OperationType.Remove, wrongIds);
            }
            else
            {
                result = new PermissionResult(true, PermissionResult.OperationType.Remove);
            }


            return(result);
        }
Esempio n. 21
0
 private static PermissionResult CanCreateActivityForOutlet(Feature f)
 {
     {
         {
             var assignment = "From the for outlet";
             if (assignment == null)
             {
                 // TODO : Display message
                 return(PermissionResult.Deny("No outlet assignment"));
             }
             var hasAssignment = assignment.Length > 0;
             if (!hasAssignment)
             {
                 // TODO : Display message
                 return(PermissionResult.Deny("Invalid assignment"));
             }
         }
         //Is R E D Activities Allowed
         {
             // TODO : !!!
             return(PermissionResult.Allow);
         }
     }
 }
        public PermissionResult CheckHasAllPermissions(IIdentity target, params string[] permissions)
        {
            GuardLoaded();
            GuardPermissions(permissions);
            GuardTarget(target);

            PermissionResult result = PermissionResult.Grant;

            foreach (string permission in permissions)
            {
                PermissionResult tmp = CheckPermission(target, permission);
                if (tmp == PermissionResult.Deny)
                {
                    return(PermissionResult.Deny);
                }

                if (tmp == PermissionResult.Default)
                {
                    result = PermissionResult.Default;
                }
            }

            return(result);
        }
Esempio n. 23
0
        protected override async Task <PermissionResult> CanAddAsync(Token value)
        {
            // We only allow users to create organization scoped tokens.
            if (String.IsNullOrEmpty(value.OrganizationId))
            {
                return(PermissionResult.Deny);
            }

            if (!String.IsNullOrEmpty(value.ProjectId) && !String.IsNullOrEmpty(value.UserId))
            {
                return(PermissionResult.DenyWithMessage("Token can't be associated to both user and project."));
            }

            foreach (string scope in value.Scopes.ToList())
            {
                if (scope != scope.ToLowerInvariant())
                {
                    value.Scopes.Remove(scope);
                    value.Scopes.Add(scope.ToLowerInvariant());
                }

                if (!AuthorizationRoles.AllScopes.Contains(scope.ToLowerInvariant()))
                {
                    return(PermissionResult.DenyWithMessage("Invalid token scope requested."));
                }
            }

            if (value.Scopes.Count == 0)
            {
                value.Scopes.Add(AuthorizationRoles.Client);
            }

            if (value.Scopes.Contains(AuthorizationRoles.Client) && !User.IsInRole(AuthorizationRoles.User))
            {
                return(PermissionResult.Deny);
            }

            if (value.Scopes.Contains(AuthorizationRoles.User) && !User.IsInRole(AuthorizationRoles.User))
            {
                return(PermissionResult.Deny);
            }

            if (value.Scopes.Contains(AuthorizationRoles.GlobalAdmin) && !User.IsInRole(AuthorizationRoles.GlobalAdmin))
            {
                return(PermissionResult.Deny);
            }

            if (!String.IsNullOrEmpty(value.ProjectId))
            {
                var project = await GetProjectAsync(value.ProjectId);

                if (project == null)
                {
                    return(PermissionResult.Deny);
                }

                value.OrganizationId   = project.OrganizationId;
                value.DefaultProjectId = null;
            }

            if (!String.IsNullOrEmpty(value.DefaultProjectId))
            {
                var project = await GetProjectAsync(value.DefaultProjectId);

                if (project == null)
                {
                    return(PermissionResult.Deny);
                }
            }

            if (!String.IsNullOrEmpty(value.ApplicationId))
            {
                var application = await _applicationRepository.GetByIdAsync(value.ApplicationId, true);

                if (application == null || !IsInOrganization(application.OrganizationId))
                {
                    return(PermissionResult.Deny);
                }
            }

            return(await base.CanAddAsync(value));
        }
Esempio n. 24
0
        protected override async Task <PermissionResult> CanAddAsync(Token value)
        {
            // We only allow users to create organization scoped tokens.
            if (String.IsNullOrEmpty(value.OrganizationId))
            {
                return(PermissionResult.Deny);
            }

            bool hasUserRole        = User.IsInRole(AuthorizationRoles.User);
            bool hasGlobalAdminRole = User.IsInRole(AuthorizationRoles.GlobalAdmin);

            if (!hasGlobalAdminRole && !String.IsNullOrEmpty(value.UserId) && value.UserId != CurrentUser.Id)
            {
                return(PermissionResult.Deny);
            }

            if (!String.IsNullOrEmpty(value.ProjectId) && !String.IsNullOrEmpty(value.UserId))
            {
                return(PermissionResult.DenyWithMessage("Token can't be associated to both user and project."));
            }

            foreach (string scope in value.Scopes.ToList())
            {
                string lowerCaseScoped = scope.ToLowerInvariant();
                if (!String.Equals(scope, lowerCaseScoped))
                {
                    value.Scopes.Remove(scope);
                    value.Scopes.Add(lowerCaseScoped);
                }

                if (!AuthorizationRoles.AllScopes.Contains(lowerCaseScoped))
                {
                    return(PermissionResult.DenyWithMessage("Invalid token scope requested."));
                }
            }

            if (value.Scopes.Count == 0)
            {
                value.Scopes.Add(AuthorizationRoles.Client);
            }

            if (value.Scopes.Contains(AuthorizationRoles.Client) && !hasUserRole)
            {
                return(PermissionResult.Deny);
            }

            if (value.Scopes.Contains(AuthorizationRoles.User) && !hasUserRole)
            {
                return(PermissionResult.Deny);
            }

            if (value.Scopes.Contains(AuthorizationRoles.GlobalAdmin) && !hasGlobalAdminRole)
            {
                return(PermissionResult.Deny);
            }

            if (!String.IsNullOrEmpty(value.ProjectId))
            {
                var project = await GetProjectAsync(value.ProjectId);

                if (project == null)
                {
                    return(PermissionResult.Deny);
                }

                value.OrganizationId   = project.OrganizationId;
                value.DefaultProjectId = null;
            }

            if (!String.IsNullOrEmpty(value.DefaultProjectId))
            {
                var project = await GetProjectAsync(value.DefaultProjectId);

                if (project == null)
                {
                    return(PermissionResult.Deny);
                }
            }

            return(await base.CanAddAsync(value));
        }
 public PermissionDecision(IPermissionGrant consideredGrant, PermissionResult result, bool conditionsSatisfied)
 {
     ConsideredGrant     = consideredGrant;
     Result              = result;
     ConditionsSatisfied = conditionsSatisfied;
 }
 public PermissionResult Handler(PermissionContext context)
 {
     return(PermissionResult.Success());
 }
Esempio n. 27
0
        public async Task SpeakAndShowText(Devices.Interfaces.IDeviceable deviceable, CarInModel carIn, PermissionResult permissionResult)
        {
            var temp = GetLedables(deviceable);

            await Task.Run(() => temp?.ForEach(x => {
                x.Speak(string.Empty);
                x.Show(string.Empty);
            }));
        }
Esempio n. 28
0
        protected override PermissionResult CanAdd(Token value)
        {
            if (String.IsNullOrEmpty(value.OrganizationId))
            {
                return(PermissionResult.Deny);
            }

            if (!String.IsNullOrEmpty(value.ProjectId) && !String.IsNullOrEmpty(value.UserId))
            {
                return(PermissionResult.DenyWithMessage("Token can't be associated to both user and project."));
            }

            foreach (string scope in value.Scopes.ToList())
            {
                if (scope != scope.ToLower())
                {
                    value.Scopes.Remove(scope);
                    value.Scopes.Add(scope.ToLower());
                }

                if (!AuthorizationRoles.AllScopes.Contains(scope.ToLower()))
                {
                    return(PermissionResult.DenyWithMessage("Invalid token scope requested."));
                }
            }

            if (value.Scopes.Count == 0)
            {
                value.Scopes.Add(AuthorizationRoles.Client);
            }

            if (value.Scopes.Contains(AuthorizationRoles.Client) && !User.IsInRole(AuthorizationRoles.User))
            {
                return(PermissionResult.Deny);
            }

            if (value.Scopes.Contains(AuthorizationRoles.User) && !User.IsInRole(AuthorizationRoles.User))
            {
                return(PermissionResult.Deny);
            }

            if (value.Scopes.Contains(AuthorizationRoles.GlobalAdmin) && !User.IsInRole(AuthorizationRoles.GlobalAdmin))
            {
                return(PermissionResult.Deny);
            }

            if (!String.IsNullOrEmpty(value.ProjectId))
            {
                Project project = _projectRepository.GetById(value.ProjectId, true);
                value.OrganizationId = project.OrganizationId;

                if (!IsInProject(project))
                {
                    return(PermissionResult.Deny);
                }
            }

            if (!String.IsNullOrEmpty(value.ApplicationId))
            {
                var application = _applicationRepository.GetById(value.ApplicationId, true);
                if (application == null || !IsInOrganization(application.OrganizationId))
                {
                    return(PermissionResult.Deny);
                }
            }

            return(base.CanAdd(value));
        }
Esempio n. 29
0
        public async Task ExecuteAsync(ICommandContext context)
        {
            PermissionResult permResult = await _permissionChecker.CheckPermissionAsync(context.User, "back");

            IUser target;
            bool  otherUser;

            if (context.Parameters.Length >= 1 && _config.allowOtherPlayer)
            {
                target = await context.Parameters.GetAsync <IUser>(0);

                otherUser = true;
            }
            else
            {
                if (context.Parameters.Length >= 1 && !_config.allowOtherPlayer)
                {
                    await context.User.SendMessageAsync("Other user functionality is disabled in the config");

                    return;
                }
                else
                {
                    target    = context.User;
                    otherUser = false;
                }
            }

            if (!(target is IUser paramType))
            {
                await context.User.SendMessageAsync("Invalid parameter");

                return;
            }

            UnturnedPlayer player = ((UnturnedUser)target).Player;

            switch (permResult)
            {
            case PermissionResult.Grant:
                if (_eventHandler.deaths.ContainsKey(target))
                {
                    await player.Entity.TeleportAsync(_eventHandler.deaths[target], player.Entity.Rotation);

                    await context.User.SendMessageAsync("You have been teleported back to your last death");
                }
                else
                {
                    if (otherUser)
                    {
                        await context.User.SendMessageAsync("This player hasn't died yet!");
                    }
                    else
                    {
                        await context.User.SendMessageAsync("You haven't died yet!");
                    }
                }
                break;

            case PermissionResult.Deny:
                await context.User.SendMessageAsync("You do not have permission to use this command!");     //I swear there was a built in way for this?

                break;

            case PermissionResult.Default:
                await context.User.SendMessageAsync("You do not have permission to use this command!");

                break;
            }
        }
 public ComputedChainDecisionEventArgs(IEnumerable <PermissionDecision> decisions, string chainName, int identifier, PermissionResult finalResult, INode nodeInQuestion)
 {
     Decisions      = decisions;
     ChainName      = chainName;
     Identifier     = identifier;
     FinalResult    = finalResult;
     NodeInQuestion = nodeInQuestion;
 }