コード例 #1
0
        public async Task AllSrvrMdls(PermissionAction action)
        {
            var newPerm = new Permission {
                PrimaryTarget       = PrimaryPermissionType.Server,
                PrimaryTargetId     = 0,
                SecondaryTarget     = SecondaryPermissionType.AllModules,
                SecondaryTargetName = "*",
                State = action.Value,
            };

            var allowUser = new Permission {
                PrimaryTarget       = PrimaryPermissionType.User,
                PrimaryTargetId     = Context.User.Id,
                SecondaryTarget     = SecondaryPermissionType.AllModules,
                SecondaryTargetName = "*",
                State = true,
            };

            await Service.AddPermissions(Context.Guild.Id,
                                         newPerm,
                                         allowUser);

            if (action.Value)
            {
                await ReplyConfirmLocalized("asm_enable").ConfigureAwait(false);
            }
            else
            {
                await ReplyConfirmLocalized("asm_disable").ConfigureAwait(false);
            }
        }
コード例 #2
0
        public async Task RoleMdl(ModuleOrCrInfo module, PermissionAction action, [Remainder] IRole role)
        {
            if (role == role.Guild.EveryoneRole)
            {
                return;
            }

            await Service.AddPermissions(Context.Guild.Id, new Permission {
                PrimaryTarget       = PrimaryPermissionType.Role,
                PrimaryTargetId     = role.Id,
                SecondaryTarget     = SecondaryPermissionType.Module,
                SecondaryTargetName = module.Name.ToLowerInvariant(),
                State = action.Value,
            });


            if (action.Value)
            {
                await ReplyConfirmLocalized("rx_enable",
                                            Format.Code(module.Name),
                                            GetText("of_module"),
                                            Format.Code(role.Name)).ConfigureAwait(false);
            }
            else
            {
                await ReplyConfirmLocalized("rx_disable",
                                            Format.Code(module.Name),
                                            GetText("of_module"),
                                            Format.Code(role.Name)).ConfigureAwait(false);
            }
        }
コード例 #3
0
        public async Task ChnlMdl(ModuleOrCrInfo module, PermissionAction action, [Remainder] ITextChannel chnl)
        {
            await Service.AddPermissions(Context.Guild.Id, new Permission {
                PrimaryTarget       = PrimaryPermissionType.Channel,
                PrimaryTargetId     = chnl.Id,
                SecondaryTarget     = SecondaryPermissionType.Module,
                SecondaryTargetName = module.Name.ToLowerInvariant(),
                State = action.Value,
            });

            if (action.Value)
            {
                await ReplyConfirmLocalized("cx_enable",
                                            Format.Code(module.Name),
                                            GetText("of_module"),
                                            Format.Code(chnl.Name)).ConfigureAwait(false);
            }
            else
            {
                await ReplyConfirmLocalized("cx_disable",
                                            Format.Code(module.Name),
                                            GetText("of_module"),
                                            Format.Code(chnl.Name)).ConfigureAwait(false);
            }
        }
コード例 #4
0
            public async Task LogServer(PermissionAction action)
            {
                var channel    = (ITextChannel)Context.Channel;
                var logSetting = uow.GuildConfigs.For(channel.Guild.Id, set => set.Include(x => x.LogSetting)).LogSetting;

                logSetting.LogOtherId                                                                    =
                    logSetting.MessageUpdatedId                                                          =
                        logSetting.MessageDeletedId                                                      =
                            logSetting.UserJoinedId                                                      =
                                logSetting.UserLeftId                                                    =
                                    logSetting.UserBannedId                                              =
                                        logSetting.UserUnbannedId                                        =
                                            logSetting.UserUpdatedId                                     =
                                                logSetting.ChannelCreatedId                              =
                                                    logSetting.ChannelDestroyedId                        =
                                                        logSetting.ChannelUpdatedId                      =
                                                            logSetting.LogUserPresenceId                 =
                                                                logSetting.LogVoicePresenceId            =
                                                                    logSetting.UserMutedId               =
                                                                        logSetting.LogVoicePresenceTTSId = (action.Value ? channel.Id : (ulong?)null);

                await uow.SaveChangesAsync(false).ConfigureAwait(false);

                if (action.Value)
                {
                    await ReplyConfirmLocalized("log_all").ConfigureAwait(false);
                }
                else
                {
                    await ReplyConfirmLocalized("log_disabled").ConfigureAwait(false);
                }
            }
コード例 #5
0
ファイル: userService.cs プロジェクト: dlfranks/rkbc-core
        public bool permissionForUserEditing(PermissionAction action, string id, bool autoThrow = false)
        {
            //Can't delete yourself no matter who you are
            if (CurrentUserSettings.userId == id && action == PermissionAction.Delete)
            {
                if (autoThrow)
                {
                    throw new InvalidOperationException("User " + CurrentUserSettings.userName + " does not have permission to " + action.ToString());
                }
                return(false);
            }
            // Can do anything else to yourself
            if (CurrentUserSettings.userId == id)
            {
                return(true);
            }
            //Otherwise only these guys have permission to do anything else
            if (CurrentUserSettings.isAdmin)
            {
                return(true);
            }

            if (autoThrow)
            {
                throw new InvalidOperationException("User " + CurrentUserSettings.userName + " does not have permission to " + action.ToString());
            }
            return(false);
        }
コード例 #6
0
        public async Task AllRoleMdls(PermissionAction action, [Remainder] IRole role)
        {
            if (role == role.Guild.EveryoneRole)
            {
                return;
            }

            await Service.AddPermissions(Context.Guild.Id, new Permission {
                PrimaryTarget       = PrimaryPermissionType.Role,
                PrimaryTargetId     = role.Id,
                SecondaryTarget     = SecondaryPermissionType.AllModules,
                SecondaryTargetName = "*",
                State = action.Value,
            });

            if (action.Value)
            {
                await ReplyConfirmLocalized("arm_enable",
                                            Format.Code(role.Name)).ConfigureAwait(false);
            }
            else
            {
                await ReplyConfirmLocalized("arm_disable",
                                            Format.Code(role.Name)).ConfigureAwait(false);
            }
        }
コード例 #7
0
        public IList ListIdentifiersFromFunction(Type classType, Object userId, PermissionAction action)
        {
            string hql = "SELECT DISTINCT EP.Identifier FROM EntityPermission EP JOIN EP.Functions F JOIN F.Roles R JOIN R.Users U WHERE ClassName = :ClassName AND U.ID = :UserID AND EP.PermissionAction = :Action";
            IQuery q   = NHibernateSession.CreateQuery(hql).SetString("ClassName", classType.Name).SetGuid("UserID", (Guid)userId).SetEnum("Action", action);

            return(q.List());
        }
コード例 #8
0
ファイル: UserPermission.cs プロジェクト: stg609/OpenIam
 public UserPermission(string userId, string permissionId, PermissionAction action, string[] permissionRoleIds = null)
 {
     UserId            = userId;
     PermissionId      = permissionId;
     Action            = action;
     PermissionRoleIds = permissionRoleIds;
 }
コード例 #9
0
        public async Task UsrMdl(ModuleOrCrInfo module, PermissionAction action, [Remainder] IGuildUser user)
        {
            await Service.AddPermissions(Context.Guild.Id, new Permission {
                PrimaryTarget       = PrimaryPermissionType.User,
                PrimaryTargetId     = user.Id,
                SecondaryTarget     = SecondaryPermissionType.Module,
                SecondaryTargetName = module.Name.ToLowerInvariant(),
                State = action.Value,
            });

            if (action.Value)
            {
                await ReplyConfirmLocalized("ux_enable",
                                            Format.Code(module.Name),
                                            GetText("of_module"),
                                            Format.Code(user.ToString())).ConfigureAwait(false);
            }
            else
            {
                await ReplyConfirmLocalized("ux_disable",
                                            Format.Code(module.Name),
                                            GetText("of_module"),
                                            Format.Code(user.ToString())).ConfigureAwait(false);
            }
        }
コード例 #10
0
            public async Task LogServer(PermissionAction action)
            {
                var        channel = (ITextChannel)Context.Channel;
                LogSetting logSetting;

                using (var uow = DbHandler.UnitOfWork())
                {
                    logSetting = uow.GuildConfigs.LogSettingsFor(channel.Guild.Id).LogSetting;
                    GuildLogSettings.AddOrUpdate(channel.Guild.Id, (id) => logSetting, (id, old) => logSetting);
                    logSetting.LogOtherId                                                                =
                        logSetting.MessageUpdatedId                                                      =
                            logSetting.MessageDeletedId                                                  =
                                logSetting.UserJoinedId                                                  =
                                    logSetting.UserLeftId                                                =
                                        logSetting.UserBannedId                                          =
                                            logSetting.UserUnbannedId                                    =
                                                logSetting.UserUpdatedId                                 =
                                                    logSetting.ChannelCreatedId                          =
                                                        logSetting.ChannelDestroyedId                    =
                                                            logSetting.ChannelUpdatedId                  =
                                                                logSetting.LogUserPresenceId             =
                                                                    logSetting.LogVoicePresenceId        =
                                                                        logSetting.LogVoicePresenceTTSId = (action.Value ? channel.Id : (ulong?)null);

                    await uow.CompleteAsync().ConfigureAwait(false);
                }
                if (action.Value)
                {
                    await channel.SendMessageAsync("✅ Logging all events on this channel.").ConfigureAwait(false);
                }
                else
                {
                    await channel.SendMessageAsync("ℹ️ Logging disabled.").ConfigureAwait(false);
                }
            }
コード例 #11
0
        public IList ListUsersForEntity(Object o, string identifier, PermissionAction action)
        {
            string hql = "SELECT DISTINCT U.Email FROM EntityPermission EP JOIN EP.Users U WHERE EP.ClassName = :ClassName AND (EP.Identifier = :Identifier OR EP.Identifier is NULL)AND EP.PermissionAction = :Action";

            IQuery q = NHibernateSession.CreateQuery(hql).SetString("ClassName", o.GetType().Name).SetString("Identifier", identifier).SetEnum("Action", action);

            return(q.List());
        }
コード例 #12
0
ファイル: Administration.cs プロジェクト: Silvamord/Sansbot
        public async Task RoleHoist(string roleSearchName, PermissionAction targetState)
        {
            var roleName = roleSearchName.ToUpperInvariant();
            var role     = Context.Guild.Roles.FirstOrDefault(r => r.Name.ToUpperInvariant() == roleName);

            await role.ModifyAsync(r => r.Hoist = targetState.Value).ConfigureAwait(false);

            await ReplyConfirmLocalized("rh", Format.Bold(role.Name), Format.Bold(targetState.Value.ToString())).ConfigureAwait(false);
        }
コード例 #13
0
        /// <summary>
        /// The ChangePermissionsion
        /// </summary>
        /// <param name="client">The <see cref="RestClient"/></param>
        /// <param name="action">The <see cref="PermissionAction"/></param>
        /// <param name="grants">The <see cref="PermissionSet"/></param>
        /// <param name="resourceType">The <see cref="PermissionResourceType"/></param>
        /// <param name="resourceId">The <see cref="string"/></param>
        /// <param name="childType">The <see cref="PermissionResourceType"/></param>
        /// <param name="subjectType">The <see cref="PermissionSubjectType"/></param>
        /// <param name="subjectId">The <see cref="string"/></param>
        private static void ChangePermission(RestClient client, PermissionAction action, PermissionSet grants,
                                             PermissionResourceType resourceType, string resourceId, PermissionResourceType childType,
                                             PermissionSubjectType subjectType, string subjectId)
        {
            var uri = string.Format("/perms/{0}/{1}/{2}/{3}/{4}/{5}",
                                    action.ToString().ToLower(),
                                    resourceType.ToString().ToLower(),
                                    resourceId,
                                    childType == PermissionResourceType.none ? string.Empty : childType.ToString(),
                                    subjectType.ToString().ToLower(),
                                    subjectId
                                    );

            var permsManage           = PermissionsToList(grants.Manage);                    //.Where(o=>o == "R" ||o=="U" || o == "D");
            var permsAuthorize        = PermissionsToList(grants.Authorize);                 //.Where(o=>o =="R" || o == "U" || o == "D"  || o == "A");
            var permsCreatedManage    = PermissionsToList(grants.CreatedDocument.Manage);    //.Where(o => o == "R" || o == "U" || o == "D");
            var permsCreatedAuthorize = PermissionsToList(grants.CreatedDocument.Authorize); // .Where(o => o == "R" || o == "U" || o == "D" || o == "A");

            object grantBody = new { };

            if (!permsCreatedManage.Any() && !permsCreatedAuthorize.Any())
            {
                grantBody = new
                {
                    manage    = permsManage,
                    authorize = permsAuthorize
                };
            }
            else
            {
                var created = new
                {
                    manage    = permsCreatedManage,
                    authorize = permsCreatedAuthorize,
                };

                grantBody = new
                {
                    manage           = permsManage,
                    authorize        = permsAuthorize,
                    created_document = created
                };
            }

            uri = uri.Replace("//", "/");

            var request = new RestRequest(uri, Method.POST);

#if DEBUG
            var bodyTxt = JsonConvert.SerializeObject(grantBody);
#endif

            Rest.Execute <BasicResponse>(client, request, grantBody);
        }
コード例 #14
0
ファイル: UserModule.cs プロジェクト: Inkluzitron/Inkluzitron
        public async Task ChangeConsentAsync(PermissionAction action, ConsentType consent)
        {
            var dbConsent = consent switch
            {
                ConsentType.All => CommandConsent.BdsmImageCommands,
                ConsentType.Bdsm => CommandConsent.BdsmImageCommands,
                _ => CommandConsent.None,
            };

            await UpdateConsentAsync(c => action == PermissionAction.Grant?(c | dbConsent) : (c & ~dbConsent));
        }
コード例 #15
0
 /// <summary>
 /// Check to see if the user has permissions on the specific resource to perform said action.
 /// </summary>
 /// <param name="user">The user to check for.</param>
 /// <param name="action">The action being performed.</param>
 /// <param name="resource">The resource being acted upon.</param>
 /// <returns>True if the user has permission to do the action.</returns>
 public async Task <bool> HasPermission(User user, PermissionAction action, TResource resource)
 {
     // Admin can do anything!
     if (user.Username == adminConfig.Username)
     {
         return(true);
     }
     else
     {
         return(await HasPermissionTo(user, action, resource));
     }
 }
コード例 #16
0
#pragma warning disable 1998
        protected override async Task <bool> HasPermissionTo(User user, PermissionAction action, Comment comment)
        {
            switch (action)
            {
            case PermissionAction.UpdateComment:
            case PermissionAction.DeleteComment:
                return(user.Equals(comment.User));

            default:
                throw new NotSupportedException();
            }
        }
コード例 #17
0
        /// <summary>
        /// Inserts a permission action record
        /// </summary>
        /// <param name="permission">Permission</param>
        public virtual async Task DeletePermissionActionRecord(PermissionAction permissionAction)
        {
            if (permissionAction == null)
            {
                throw new ArgumentNullException("permissionAction");
            }

            //delete
            await _permissionActionRepository.DeleteAsync(permissionAction);

            //clear cache
            await _cacheManager.RemoveByPrefix(CacheKey.PERMISSIONS_PATTERN_KEY);
        }
コード例 #18
0
            public async Task LogServer(PermissionAction action)
            {
                await _service.LogServer(Context.Guild.Id, Context.Channel.Id, action.Value).ConfigureAwait(false);

                if (action.Value)
                {
                    await ReplyConfirmLocalized("log_all").ConfigureAwait(false);
                }
                else
                {
                    await ReplyConfirmLocalized("log_disabled").ConfigureAwait(false);
                }
            }
コード例 #19
0
#pragma warning disable 1998
        protected override async Task <bool> HasPermissionTo(User user, PermissionAction action, Space space)
        {
            switch (action)
            {
            case PermissionAction.CreateSpace:
            case PermissionAction.UpdateSpace:
            case PermissionAction.DeleteSpace:
                return(false);

            default:
                throw new NotSupportedException();
            }
        }
コード例 #20
0
        public static IList GetPermissionIdentifiersFromFunction(Type classType, PermissionAction action)
        {
            string cachedKey = string.Format("LISTIDENTIFIERSFromFunction_{0}_{1}_{2}", classType.Name.ToString(), action.ToString(), MembershipHelper.GetUser().UserId);
            object result    = CacheManager.GetCached(cachedKey);

            if (result == null)
            {
                result = ControllerManager.EntityPermission.ListIdentifiersFromFunction(classType, MembershipHelper.GetUser().UserId, (PermissionAction)action);
                CacheManager.AddItem(cachedKey, result);
            }

            return((IList)result);
        }
コード例 #21
0
        /// <summary>
        /// Inserts a permission action record
        /// </summary>
        /// <param name="permission">Permission</param>
        public virtual async Task InsertPermissionAction(PermissionAction permissionAction)
        {
            if (permissionAction == null)
            {
                throw new ArgumentNullException(nameof(permissionAction));
            }

            //insert
            await _permissionActionRepository.InsertAsync(permissionAction);

            //clear cache
            await _cacheBase.RemoveByPrefix(CacheKey.PERMISSIONS_PATTERN_KEY);
        }
コード例 #22
0
        /// <summary>
        ///   Grants or revokes a permission to or from members of a role for a given type of entity.
        /// </summary>
        /// <param name="entitytype">
        ///   Base type of entities for which the permission is granted. To assign the permission to all
        ///   entity types, pass <c>typeof(object)</c>.
        /// </param>
        /// <param name="permission">The permission being granted or revoked.</param>
        /// <param name="role">The role for which the permissio is being granted or revoked.</param>
        /// <param name="action">Whether the permission is being granted or revoked.</param>
        public void AddRolePermissionAssignment(Type entitytype, IPermission permission, IRole role,
                                                PermissionAction action)
        {
            var assignment = new Assignment(permission, role, action);
            List <Assignment> list;

            if (!rolePermissionAssignments.TryGetValue(entitytype, out list))
            {
                list = new List <Assignment>();
                rolePermissionAssignments.Add(entitytype, list);
            }

            list.Add(assignment);
        }
コード例 #23
0
        public bool ListIdentifiers(Type classType, Object userId, PermissionAction action, out IList list)
        {
            string hql = "SELECT DISTINCT EP.Identifier FROM EntityPermission EP JOIN EP.Functions F JOIN F.Roles R JOIN R.Users U WHERE ClassName = :ClassName AND U.ID = :UserID AND EP.PermissionAction = :Action AND EP.Identifier IS NULL";
            IQuery q   = NHibernateSession.CreateQuery(hql).SetString("ClassName", classType.Name).SetGuid("UserID", (Guid)userId).SetEnum("Action", action);

            list = q.List();

            if (list.Count > 0)
            {
                return(true);
            }

            list = ListIdentifiers(classType, userId, action);
            return(false);
        }
        static PermissionHelper()
        {
            var permissionTabViewModels = new List <PermissionTab>();

            var assembly    = Assembly.GetExecutingAssembly();
            var controllers = assembly.GetExportedTypes()
                              .Where(type => type.IsPublic && type.IsClass && !type.IsAbstract && type.IsSubclassOf(typeof(ControllerBase)) && type.GetCustomAttribute <AllowAnonymousAttribute>() == null)
                              .Select(controller => new
            {
                ControllerFullName  = controller.FullName,
                ControllerName      = GetControllerName(controller),
                ControllerGroupName = GetControllerGroupName(controller),
                Actions             = controller.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public)
                                      .Where(method => method.IsPublic && method.GetCustomAttribute <NonActionAttribute>() == null && method.GetCustomAttribute <AllowAnonymousAttribute>() == null)
                                      .Select(method => new
                {
                    ActionName     = GetActionName(method),
                    ActionFullName = controller.FullName + "." + method.Name
                }).ToList(),
            }).ToList();

            foreach (var tab in controllers.GroupBy(p => p.ControllerGroupName))
            {
                var tabViewModel = new PermissionTab {
                    Name = tab.Key
                };
                foreach (var controller in tab)
                {
                    var controllerViewModel = new PermissionController {
                        Name = controller.ControllerName, FullName = controller.ControllerFullName
                    };
                    foreach (var action in controller.Actions.GroupBy(p => p.ActionName))
                    {
                        var actionViewModel = new PermissionAction
                        {
                            Name      = action.Key,
                            FullNames = action.Select(p => p.ActionFullName).Distinct().ToList()
                        };
                        controllerViewModel.Actions.Add(actionViewModel);
                    }
                    tabViewModel.Controllers.Add(controllerViewModel);
                }
                Tabs.Add(tabViewModel);
            }
        }
コード例 #25
0
        public static IList GetPermissionIdentifiers(Type classType, PermissionAction action)
        {
            // Check if there are permissions for this object cached for this user.
            if (logger.IsDebugEnabled)
            {
                logger.DebugFormat("Finding entity permission list: {0} {1}", classType.Name, action);
            }
            string cachedKey = string.Format("LISTIDENTIFIERS_{0}_{1}_{2}", classType.Name.ToString(), action.ToString(), MembershipHelper.GetUser().UserId);
            object result    = CacheManager.GetCached(cachedKey);

            if (result == null)
            {
                result = ControllerManager.EntityPermission.ListIdentifiers(classType, MembershipHelper.GetUser().UserId, (PermissionAction)action);
                CacheManager.AddItem(cachedKey, result);
            }

            return((IList)result);
        }
コード例 #26
0
        public async Task Verbose(PermissionAction action)
        {
            var config = uow.GuildConfigs.GcWithPermissionsv2For(Context.Guild.Id);

            config.VerbosePermissions = action.Value;
            await uow.SaveChangesAsync(false).ConfigureAwait(false);

            Service.UpdateCache(config);

            if (action.Value)
            {
                await ReplyConfirmLocalized("verbose_true").ConfigureAwait(false);
            }
            else
            {
                await ReplyConfirmLocalized("verbose_false").ConfigureAwait(false);
            }
        }
コード例 #27
0
        public async Task Verbose(PermissionAction action)
        {
            using (var uow = _db.UnitOfWork)
            {
                var config = uow.GuildConfigs.GcWithPermissionsv2For(Context.Guild.Id);
                config.VerbosePermissions = action.Value;
                await uow.CompleteAsync().ConfigureAwait(false);

                Service.UpdateCache(config);
            }
            if (action.Value)
            {
                await ReplyConfirmLocalized("verbose_true").ConfigureAwait(false);
            }
            else
            {
                await ReplyConfirmLocalized("verbose_false").ConfigureAwait(false);
            }
        }
コード例 #28
0
        public async Task AllChnlMdls(PermissionAction action, [Remainder] ITextChannel chnl)
        {
            await Service.AddPermissions(Context.Guild.Id, new Permission {
                PrimaryTarget       = PrimaryPermissionType.Channel,
                PrimaryTargetId     = chnl.Id,
                SecondaryTarget     = SecondaryPermissionType.AllModules,
                SecondaryTargetName = "*",
                State = action.Value,
            });

            if (action.Value)
            {
                await ReplyConfirmLocalized("acm_enable",
                                            Format.Code(chnl.Name)).ConfigureAwait(false);
            }
            else
            {
                await ReplyConfirmLocalized("acm_disable",
                                            Format.Code(chnl.Name)).ConfigureAwait(false);
            }
        }
コード例 #29
0
        public async Task AllUsrMdls(PermissionAction action, [Remainder] IUser user)
        {
            await Service.AddPermissions(Context.Guild.Id, new Permission {
                PrimaryTarget       = PrimaryPermissionType.User,
                PrimaryTargetId     = user.Id,
                SecondaryTarget     = SecondaryPermissionType.AllModules,
                SecondaryTargetName = "*",
                State = action.Value,
            });

            if (action.Value)
            {
                await ReplyConfirmLocalized("aum_enable",
                                            Format.Code(user.ToString())).ConfigureAwait(false);
            }
            else
            {
                await ReplyConfirmLocalized("aum_disable",
                                            Format.Code(user.ToString())).ConfigureAwait(false);
            }
        }
コード例 #30
0
        public async Task SrvrMdl(ModuleOrCrInfo module, PermissionAction action)
        {
            await Service.AddPermissions(Context.Guild.Id, new Permission {
                PrimaryTarget       = PrimaryPermissionType.Server,
                PrimaryTargetId     = 0,
                SecondaryTarget     = SecondaryPermissionType.Module,
                SecondaryTargetName = module.Name.ToLowerInvariant(),
                State = action.Value,
            });

            if (action.Value)
            {
                await ReplyConfirmLocalized("sx_enable",
                                            Format.Code(module.Name),
                                            GetText("of_module")).ConfigureAwait(false);
            }
            else
            {
                await ReplyConfirmLocalized("sx_disable",
                                            Format.Code(module.Name),
                                            GetText("of_module")).ConfigureAwait(false);
            }
        }