示例#1
0
        public CommonMessage(Msg msg, PermissionLevel level = PermissionLevel.Public)
        {
            Message         = msg.Message;
            UserId          = msg.UserId.ToString();
            MessageId       = msg.MessageId;
            PermissionLevel = level;

            switch (msg)
            {
            case PrivateMsg privateMsg:
                MessageType = MessageType.Private;
                Private     = privateMsg;
                break;

            case DiscussMsg discussMsg:
                MessageType = MessageType.Discuss;
                Discuss     = discussMsg;
                DiscussId   = discussMsg.DiscussId.ToString();
                break;

            case GroupMsg groupMsg:
                MessageType = MessageType.Group;
                Group       = groupMsg;
                GroupId     = groupMsg.GroupId.ToString();
                break;
            }
        }
示例#2
0
文件: File.cs 项目: Xuehuo/SAA-Online
 /// <summary>
 /// File constructor
 /// </summary>
 /// <param name="str">GUID string</param>
 public File(string str)
 {
     Guid guid;
     if (!Guid.TryParse(str, out guid))
         throw new ArgumentException();
     _guid = str.ToUpper();
     var si = new SqlIntegrate(Utility.ConnStr);
     si.AddParameter("@GUID", SqlIntegrate.DataType.VarChar, str.ToUpper());
     var fileInfo = si.Reader("SELECT * FROM [File] WHERE [GUID] = @GUID");
     _name = fileInfo["name"].ToString();
     _info = fileInfo["info"].ToString();
     _extension = fileInfo["extension"].ToString();
     _size = Convert.ToInt32(fileInfo["size"]);
     _uploader = new User(Guid.Parse(fileInfo["uploader"].ToString()));
     _downloadCount = Convert.ToInt32(fileInfo["downloadCount"]);
     _uploadTime = Convert.ToDateTime(fileInfo["uploadTime"]);
     _savePath = StoragePath + str.ToUpper();
     _permission = (PermissionLevel)Convert.ToInt32(fileInfo["permission"]);
     _mediaId = fileInfo["media_id"].ToString();
     Tag = new List<string>();
     si.ResetParameter();
     si.AddParameter("@FUID", SqlIntegrate.DataType.VarChar, str.ToUpper());
     var tagList = si.Adapter("SELECT [name] FROM [Filetag] WHERE FUID = @FUID");
     for (var i = 0; i < tagList.Rows.Count; i++)
         Tag.Add(tagList.Rows[i]["name"].ToString());
 }
示例#3
0
文件: User.cs 项目: nebez/TwitchBot
 public void AddPermission(PermissionLevel perm)
 {
     if (!_permissions.Contains(perm))
     {
         _permissions.Add(perm);
     }
 }
示例#4
0
文件: User.cs 项目: nebez/TwitchBot
 public void RemovePermission(PermissionLevel perm)
 {
     if (_permissions.Contains(perm))
     {
         _permissions.Remove(perm);
     }
 }
示例#5
0
        public static bool HasPermissionLevel(SocketGuildUser user, PermissionLevel level)
        {
            switch (level)
            {
            case PermissionLevel.MUTED:
                return(IsSilenced(user));

            case PermissionLevel.USER:
                return(!IsSilenced(user));

            case PermissionLevel.TRUSTED:
                if (IsTrusted(user))
                {
                    return(true);
                }
                goto case PermissionLevel.MODERATOR;

            case PermissionLevel.MODERATOR:
                if (IsModerator(user))
                {
                    return(true);
                }
                goto case PermissionLevel.ADMIN;

            case PermissionLevel.ADMIN:
                if (IsAdmin(user))
                {
                    return(true);
                }
                return(false);

            default:
                return(false);
            }
        }
示例#6
0
        public static bool HasUserPermission(User user, int?CountryID, PermissionLevel requiredLevel, UserPermissionsContainer userPermissions = null)
        {
            if (user != null)
            {
                if (!String.IsNullOrEmpty(user.Permissions))
                {
                    if (userPermissions == null)
                    {
                        userPermissions = JsonConvert.DeserializeObject <UserPermissionsContainer>(user.Permissions);
                    }

                    if (userPermissions.Permissions != null)
                    {
                        if (userPermissions.Permissions.Any(p => p.Level == PermissionLevel.Admin && (p.CountryID == null || p.CountryID == CountryID)))
                        {
                            //user is admin (for given country or all countries)
                            return(true);
                        }

                        if (userPermissions.Permissions.Any(p => p.Level == requiredLevel && (p.CountryID == null || p.CountryID == CountryID)))
                        {
                            //user has required level of access (for given country or all countries)
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
示例#7
0
        public static bool HasUserPermission(User user, int? CountryID, PermissionLevel requiredLevel, UserPermissionsContainer userPermissions = null)
        {
            if (user != null)
            {
                if (!String.IsNullOrEmpty(user.Permissions))
                {
                    if (userPermissions == null)
                    {
                        userPermissions = JsonConvert.DeserializeObject<UserPermissionsContainer>(user.Permissions);
                    }

                    if (userPermissions.Permissions != null)
                    {
                        if (userPermissions.Permissions.Any(p => p.Level == PermissionLevel.Admin && (p.CountryID == null || p.CountryID == CountryID)))
                        {
                            //user is admin (for given country or all countries)
                            return true;
                        }

                        if (userPermissions.Permissions.Any(p => p.Level == requiredLevel && (p.CountryID == null || p.CountryID == CountryID)))
                        {
                            //user has required level of access (for given country or all countries)
                            return true;
                        }
                    }
                }
            }
            return false;
        }
示例#8
0
        public async Task SetPermissionAsync(string commandName, PermissionLevel level)
        {
            var competition = Service.GetOrCreateCompetition(Context.Guild.Id);

            var match = CommandService.Commands.FirstOrDefault(x => x.Name.Equals(commandName, System.StringComparison.OrdinalIgnoreCase) || x.Aliases.Any(a => a.Equals(commandName, System.StringComparison.OrdinalIgnoreCase)));

            if (match == null)
            {
                await SimpleEmbedAsync("Unknown command name.", Color.Red);

                return;
            }

            if (!match.Preconditions.Any(x => x is RequirePermission))
            {
                await SimpleEmbedAsync("This command cannot have it's permission overwritten.");

                return;
            }

            competition.Permissions[match.Name.ToLower()] = level;
            Service.PermissionCache[Context.Guild.Id]     = new ELOService.CachedPermission
            {
                AdminRoleId       = competition.AdminRole,
                ModeratorRoleId   = competition.ModeratorRole,
                CachedPermissions = competition.Permissions
            };

            Service.SaveCompetition(competition);
            await SimpleEmbedAsync($"{match.Name} permission level set to: {level}", Color.Blue);
        }
示例#9
0
        /// <summary>
        /// Проверить входные параметры SetInspection.
        /// </summary>
        /// <param name="login">Логин проверяющего</param>
        /// <param name="assignDate">Дата операции</param>
        /// <param name="timeZone">Часовой пояс проверяющего</param>
        private void SetInspectionCheckParams(string login, DateTime assignDate, int timeZone)
        {
            if (string.IsNullOrEmpty(login))
            {
                LogAndThrowException <ArgumentNullException, EFServiceInspecting>(
                    _Logger, nameof(login),
                    "Не задан логин проверяющего сотрудника./* Метод {methodName}.*/",
                    "SetInspectionCheckParams");
            }

            if (assignDate == default)
            {
                LogAndThrowException <ArgumentNullException, EFServiceInspecting>(
                    _Logger, nameof(assignDate),
                    "Не задана дата операции./* Метод {methodName}.*/",
                    "SetInspectionCheckParams");
            }

            if (timeZone == default)
            {
                LogAndThrowException <ArgumentNullException, EFServiceInspecting>(
                    _Logger, nameof(timeZone),
                    "Не задан часовой пояс проверяющего./* Метод {methodName}.*/",
                    "SetInspectionCheckParams");
            }

            if (PermissionLevel.Get(login) != PermissionLevelE.Security)
            {
                LogAndThrowException <Exception, EFServiceInspecting>(
                    _Logger, "",
                    "У пользователя нет прав осуществлять проверку./* Метод {methodName}, пользователь {login}.*/",
                    "SetInspectionCheckParams", login);
            }
        }
示例#10
0
        public virtual async Task SetPermissionAsync(string commandName, PermissionLevel level)
        {
            using (var db = new Database())
            {
                var match = CommandService.Commands.FirstOrDefault(x => x.Name.Equals(commandName, System.StringComparison.OrdinalIgnoreCase) || x.Aliases.Any(a => a.Equals(commandName, System.StringComparison.OrdinalIgnoreCase)));

                if (match == null)
                {
                    await SimpleEmbedAsync("Unknown command name.", Color.Red);

                    return;
                }

                if (!match.Preconditions.Any(x => x is RequirePermission))
                {
                    await SimpleEmbedAsync("This command cannot have it's permission overwritten.");

                    return;
                }

                var permission = new CommandPermission
                {
                    GuildId     = Context.Guild.Id,
                    CommandName = match.Name.ToLower(),
                    Level       = level
                };
                db.Permissions.Add(permission);
                if (PermissionService.PermissionCache.TryGetValue(Context.Guild.Id, out var cache))
                {
                    cache.Cache.Remove(match.Name.ToLower());
                }
                db.SaveChanges();
                await SimpleEmbedAsync($"{match.Name} permission level set to: {level}", Color.Blue);
            }
        }
 private void ClientOnGetAllSecurityGroupsCompleted(object sender, GetAllSecurityGroupsCompletedEventArgs e)
 {
     if (!e.Result.HasError)
     {
         foreach (var pair in e.Result.Result)
         {
             SecurityGroups.Add(PermissionLevel.Convert(pair.Key), pair.Value);
         }
         foreach (var valuePair in SecurityGroups)
         {
             foreach (var item in valuePair.Value)
             {
                 if (AllSecurityGroups.All(q => q.GroupId != item.GroupId))
                 {
                     AllSecurityGroups.Add(item);
                 }
             }
         }
         MapManager.QueryDomainsCompleted.RegisterEvent(OnAcquireDomainsCompleted);
         MapManager.QueryDomainsAsync();
     }
     else
     {
         SuperMessageBoxService.ShowError("Error Occurred",
                                          "An error occurred while retrieving the groups with Glyma permissions.", Close);
     }
 }
示例#12
0
        private ExternalUser ApplyPermission(MailboxSession mailboxSession, SmtpAddress smtpAddress, SharingContext context)
        {
            ExternalUser externalUser = null;
            ExternalUser externalUser2;

            using (ExternalUserCollection externalUsers = mailboxSession.GetExternalUsers())
            {
                externalUser2 = externalUsers.FindReachUserWithOriginalSmtpAddress(smtpAddress);
                externalUser  = externalUsers.FindFederatedUserWithOriginalSmtpAddress(smtpAddress);
                if (externalUser2 == null)
                {
                    externalUser2 = externalUsers.AddReachUser(smtpAddress);
                    externalUsers.Save();
                }
            }
            using (FolderPermissionContext current = FolderPermissionContext.GetCurrent(mailboxSession, context))
            {
                FreeBusyAccess freeBusy = this.GetFreeBusy(context);
                PermissionSecurityPrincipal principal       = new PermissionSecurityPrincipal(externalUser2);
                PermissionLevel             permissionLevel = (context.SharingDetail == SharingContextDetailLevel.FullDetails) ? PermissionLevel.Reviewer : PermissionLevel.None;
                current.AddOrChangePermission(principal, permissionLevel, new FreeBusyAccess?(freeBusy));
                if (externalUser != null)
                {
                    current.RemovePermission(new PermissionSecurityPrincipal(externalUser));
                }
            }
            return(externalUser2);
        }
示例#13
0
        private void LoadAdmin()
        {
            panModifyUser.Visibility = Visibility.Hidden;           //Hide the modification panels as they are not needed yet
            panModifyFarm.Visibility = Visibility.Hidden;           //

            lstFarms.Items.Clear();                                 //Clean the list views
            lstUsers.Items.Clear();                                 //

            cboModuserRoles.Items.Clear();                          //Clean the combo boxes associated with modifying the users/farms
            cboModuserfarmlist.Items.Clear();                       //

            foreach (User u in DownloadData.GetAllUsers())          //get all users currently on server
            {
                lstUsers.Items.Add(u);                              //add them into the list view
            }
            cboModuserfarmlist.Items.Add("NONE");                   //Make the default/first option be nil
            foreach (FullFarm ff in DownloadData.GetAllFullFarms()) //get all farms currently on server
            {
                lstFarms.Items.Add(ff);                             //add the farms into the list view
                cboModuserfarmlist.Items.Add(ff.name);              //add the farm names into the combo box on modifying farms panel
            }

            for (PermissionLevel p = PermissionLevel.Admin; p < PermissionLevel.Guest + 1; p++) //increment through all the roles possible
            {
                cboModuserRoles.Items.Add(p);                                                   //add the roles to the combo box for the user to select on modify user
            }
        }
示例#14
0
        /// <summary>
        /// Event that occurs when the login button is pressed on the Login form
        /// </summary>
        /// <param name="email">the input email</param>
        /// <param name="password">the hashed input password</param>
        /// <param name="f">reference to the login form</param>
        void HandleLoginButton(string email, string password, Form f)
        {
            userEmail           = email;
            userPermissionLevel = PermissionLevel.Invalid;

            connection.Send(new LoginRequest(email, password));
        }
    /**
     * Basic constructor for User
     *
     * @param permissionLevel
     *      The permission level of the user
     * @param branch
     *      The branch of the military this user is playing for
     * @param team
     *      The team that this user logs onto
     * @param username
     *      The name of the user
     * @param unit
     *      null for non-sub players
     *      The GUID/NetworkID of the sub controlled by this player.
     */
    public User(PermissionLevel permissionLevel, MilitaryBranch branch, int team, string username, string unit)
    {
        // Set the permission level
        MyPermissionLevel = permissionLevel;

        // Set the military branch
        MyBranch = branch;

        // Set the team
        TeamNumber = team;

        // Set the username
        Username = username;

        // Check if there is not an associated sub
        if (unit == null)
        {
            // If there is not

            // Set sub player to false
            SubPlayer = false;
        }
        else
        {
            // If there is an associated sub

            // Set sub player to true
            SubPlayer = true;

            // Record the GUID/NetworkID of the Sub
            SubUnit = unit;
        }
    }
示例#16
0
        public static MemberRights GetMemberRights(PermissionLevel permissionLevel)
        {
            switch (permissionLevel)
            {
            case PermissionLevel.None:
                return(MemberRights.None);

            case PermissionLevel.Owner:
                return(MemberRights.ReadAny | MemberRights.Create | MemberRights.EditOwned | MemberRights.DeleteOwned | MemberRights.EditAny | MemberRights.DeleteAny | MemberRights.CreateSubfolder | MemberRights.Owner | MemberRights.Contact | MemberRights.Visible);

            case PermissionLevel.PublishingEditor:
                return(MemberRights.ReadAny | MemberRights.Create | MemberRights.EditOwned | MemberRights.DeleteOwned | MemberRights.EditAny | MemberRights.DeleteAny | MemberRights.CreateSubfolder | MemberRights.Visible);

            case PermissionLevel.Editor:
                return(MemberRights.ReadAny | MemberRights.Create | MemberRights.EditOwned | MemberRights.DeleteOwned | MemberRights.EditAny | MemberRights.DeleteAny | MemberRights.Visible);

            case PermissionLevel.PublishingAuthor:
                return(MemberRights.ReadAny | MemberRights.Create | MemberRights.EditOwned | MemberRights.DeleteOwned | MemberRights.CreateSubfolder | MemberRights.Visible);

            case PermissionLevel.Author:
                return(MemberRights.ReadAny | MemberRights.Create | MemberRights.EditOwned | MemberRights.DeleteOwned | MemberRights.Visible);

            case PermissionLevel.NonEditingAuthor:
                return(MemberRights.ReadAny | MemberRights.Create | MemberRights.DeleteOwned | MemberRights.Visible);

            case PermissionLevel.Reviewer:
                return(MemberRights.ReadAny | MemberRights.Visible);

            case PermissionLevel.Contributor:
                return(MemberRights.Create | MemberRights.Visible);

            default:
                throw new EnumOutOfRangeException("PermissionLevel", ServerStrings.BadEnumValue(typeof(PermissionLevel)));
            }
        }
示例#17
0
        internal void AddOrChangePermission(PermissionSecurityPrincipal principal, PermissionLevel permissionLevel, FreeBusyAccess?freeBusyAccess)
        {
            this.CheckDisposed();
            Util.ThrowOnNullArgument(principal, "principal");
            Permission permission;

            if (freeBusyAccess == null)
            {
                permission = new Permission(principal, MemberRights.None);
            }
            else
            {
                permission = new CalendarFolderPermission(principal, MemberRights.None)
                {
                    FreeBusyAccess = freeBusyAccess.Value
                };
            }
            permission.PermissionLevel = permissionLevel;
            if (freeBusyAccess != null)
            {
                permission.MemberRights |= MemberRights.Visible;
            }
            if (this.permissionsToRemove.Remove(principal))
            {
                ExTraceGlobals.SharingTracer.TraceDebug <IExchangePrincipal, PermissionSecurityPrincipal>((long)this.GetHashCode(), "{0}: Removed {1} from permissionsToRemove list.", this.mailboxSession.MailboxOwner, principal);
            }
            if (!this.permissionsToAddOrChange.ContainsKey(principal))
            {
                this.permissionsToAddOrChange.Add(principal, permission.MemberRights);
                ExTraceGlobals.SharingTracer.TraceDebug <IExchangePrincipal, PermissionSecurityPrincipal, MemberRights>((long)this.GetHashCode(), "{0}: Added {1} to permissionsToAddOrChange list: MemberRights = {2}.", this.mailboxSession.MailboxOwner, principal, permission.MemberRights);
                return;
            }
            this.permissionsToAddOrChange[principal] = permission.MemberRights;
            ExTraceGlobals.SharingTracer.TraceDebug <IExchangePrincipal, PermissionSecurityPrincipal, MemberRights>((long)this.GetHashCode(), "{0}: Changed {1} in permissionsToAddOrChange list: MemberRights = {2}.", this.mailboxSession.MailboxOwner, principal, permission.MemberRights);
        }
示例#18
0
        //----------------------------------------------------------------------------- Permission queries

        private IEnumerable <Node> GetRelatedIdentitiesPrivate(string contentPath, PermissionLevel level, IdentityKind identityKind)
        {
            if (level != PermissionLevel.AllowedOrDenied)
            {
                throw new NotImplementedException("Not implemented. Use 'AllowedOrDenied'");
            }

            var firstPermInfo = GetFirstInfo(contentPath);
            var identityIds   = new List <int>();

            if (contentPath == firstPermInfo.Path)
            {
                SearchRelatedIdentitiesInTree(level, identityKind, firstPermInfo, identityIds);
            }
            else
            {
                var contentPathSlash = contentPath + "/";
                foreach (var childPi in firstPermInfo.Children)
                {
                    if (childPi.Path == contentPath || childPi.Path.StartsWith(contentPathSlash))
                    {
                        SearchRelatedIdentitiesInTree(level, identityKind, childPi, identityIds);
                    }
                }
            }

            var identities = new NodeList <Node>(identityIds);

            return(Filter(identities, identityKind));
        }
示例#19
0
        private void SearchRelatedIdentitiesInTree(PermissionLevel level, PermissionInfo node, IdentityKind identityKind, List <int> ids, int permissionMask)
        {
            // if breaked, adding existing parent-s effective identities
            if (!node.Inherits)
            {
                if (node.Parent != null)
                {
                    foreach (var entry in GetEffectiveEntries(node.Parent.Path))
                    {
                        if (!ids.Contains(entry.PrincipalId))
                        {
                            ids.Add(entry.PrincipalId);
                        }
                    }
                }
            }

            // adding explicite identities recursive
            foreach (var ps in node.PermissionSets)
            {
                if (((ps.AllowBits | ps.DenyBits) & permissionMask) != 0)
                {
                    if (!ids.Contains(ps.PrincipalId))
                    {
                        ids.Add(ps.PrincipalId);
                    }
                }
            }
            foreach (var childNode in node.Children)
            {
                SearchRelatedIdentitiesInTree(level, childNode, identityKind, ids, permissionMask);
            }
        }
示例#20
0
        public string CreateAuthenticationUrl(PermissionLevel permissionLevel, string frob)
        {
            var permissionName = _permissionLevelConverter.ToString(permissionLevel);
            var authUrlBuilder = _urlBuilderFactory.CreateAuthUrlBuilder(permissionName, frob);

            return(authUrlBuilder.BuildUrl());
        }
 public PermissionAttribute(
     PermissionType[] permissionTypes,
     PermissionLevel permissionLevel)
 {
     _permissionTypes = permissionTypes.ToList();
     _permissionLevel = permissionLevel;
 }
示例#22
0
 private void GetUsersPermissionLevelNameCompleted(object sender, GetUsersPermissionLevelNameCompletedEventArgs e)
 {
     if (!e.Result.HasError)
     {
         var permission = PermissionLevel.Convert(e.Result.Result);
         App.PermissionLevel = permission;
         if (permission != PermissionLevel.None)
         {
             SuperGraph.ExplorerOnly = permission < PermissionLevel.Author;
             DebugLogger.Instance.LogMsg("User Permission Loaded: " + permission);
             if (IsLoadMapByGuid)
             {
                 DebugLogger.Instance.LogMsg(string.Format("Loading map through URL: NodeId[{0}],MapId[{1}],DomainId[{2}]", NodeId, MapId, DomainId));
                 PreLoader.ReadyToInitialiseControllers += OnReadyToInitialiseControllers;
                 PreLoader.Load(DomainId, NodeId, MapId);
             }
             else
             {
                 Loader.Visibility = Visibility.Collapsed;
                 HomeScreen();
             }
         }
         else
         {
             SuperMessageBoxService.Show("Access Denied", "It seems that you don't have permission to access Glyma, please contact your system administrator for assistance.", MessageBoxType.ErrorWithNoInput);
         }
     }
     else
     {
         SuperMessageBoxService.ShowError("Error Occurred", "There was a problem reading Glyma permissions, please try again later");
     }
 }
示例#23
0
        private void ClientOnGetHighestPermissionNameCompleted(object sender, GetPermissionNameForObjectCompletedEventArgs e)
        {
            var item = DataContext as IManagementConsoleObject;

            if (!e.Result.HasError && item != null)
            {
                var id = sender as Guid?;
                if (id != null && id == item.Id)
                {
                    item.CurrentUserPermissionLevel = PermissionLevel.Convert(e.Result.Result);
                    //todo: if the user is security manager, needs to be returned as well
                    if (item.CurrentUserPermissionLevel >= PermissionLevel.Author || App.PermissionLevel == PermissionLevel.SecurityManager)
                    {
                        NewMapButton.IsEnabled = true;
                        if (item.CurrentUserPermissionLevel >= PermissionLevel.MapManager || App.PermissionLevel == PermissionLevel.SecurityManager)
                        {
                            DeleteButton.IsEnabled = true;
                        }
                    }

                    if (App.PermissionLevel != PermissionLevel.SecurityManager)
                    {
                        item.IsLoaded = true;
                    }
                }
            }
            else
            {
                SuperMessageBoxService.ShowError("Error Occurred", "There was a problem reading Glyma permissions, please try again later");
            }
        }
示例#24
0
        /* -----------------------------------------------------------------------------------
         * Create new an EmrDocument.
         * Parameter:
         *      registryID -- The registry identifier of a patient for a visit to the hospital.
         *      permission -- The current operator has what privilege on this EmrDocument.
         * Attributes:
         *      inUse directs that the array element is in use.
         *      inNew directs that the document has not been created and is empty.
         * Return:
         *      index -- Direct to the new EmrDocument if successful.
         *      -1 -- No new EmrDocument is created.
         * ------------------------------------------------------------------------------------- */
        public int open(string registryID, PermissionLevel permission, string archiveNum)
        {
            int index = AvailableIndex();

            if (index < 0)
            {
                return(-1);
            }

            if (emrDocuments[index] == null)
            {
                emrDocuments[index] = new EmrDocument();
            }
            int errno = emrDocuments[index].Create(registryID, archiveNum);

            if (errno == 0 || errno == -3)
            {
                inUse[index]           = true;
                permissionLevel[index] = permission;
                if (errno == -3)
                {
                    permissionLevel[index] = PermissionLevel.ReadOnly;
                }
                if (emrDocuments[index].Get().DocumentElement.Attributes[AttributeNames.Series].Value == "0")
                {
                    isNew[index] = true;
                }
                else
                {
                    isNew[index] = false;
                }
                return(index);
            }
            return(errno);
        }
示例#25
0
        /// <summary>
        /// Valida si un objeto tipo PermissionLevel con los filtros actuales
        /// </summary>
        /// <param name="permissionLevel">Objeto a validar</param>
        /// <returns>True. Si cumple | False. No cumple</returns>
        /// <history>
        /// [emoguel] created 11/04/2016
        /// </history>
        private bool ValidateFilter(PermissionLevel permissionLevel)
        {
            if (_nStatus != -1)//Filtro por estatus
            {
                if (permissionLevel.plA != Convert.ToBoolean(_nStatus))
                {
                    return(false);
                }
            }

            if (_permissionLevelFilter.plID > 0)//FIltro por ID
            {
                if (permissionLevel.plID != _permissionLevelFilter.plID)
                {
                    return(false);
                }
            }

            if (!string.IsNullOrWhiteSpace(_permissionLevelFilter.plN))//filtro por descripción
            {
                if (!permissionLevel.plN.Contains(_permissionLevelFilter.plN, StringComparison.OrdinalIgnoreCase))
                {
                    return(false);
                }
            }
            return(true);
        }
示例#26
0
        /// <summary>
        /// Muestra la ventana detalle
        /// </summary>
        /// <history>
        /// [emoguel] 11/04/2016 Created
        /// </history>
        private void Cell_DoubleClick(object sender, RoutedEventArgs e)
        {
            PermissionLevel          permissionLevel          = (PermissionLevel)dgrPermissionsLevels.SelectedItem;
            frmPermissionLevelDetail frmPermissionLevelDetail = new frmPermissionLevelDetail();

            frmPermissionLevelDetail.Owner              = this;
            frmPermissionLevelDetail.enumMode           = EnumMode.Edit;
            frmPermissionLevelDetail.oldPermissionLevel = permissionLevel;
            if (frmPermissionLevelDetail.ShowDialog() == true)
            {
                int nIndex = 0;
                List <PermissionLevel> lstPermissionsLevels = (List <PermissionLevel>)dgrPermissionsLevels.ItemsSource;
                if (ValidateFilter(frmPermissionLevelDetail.permissionLevel))
                {
                    ObjectHelper.CopyProperties(permissionLevel, frmPermissionLevelDetail.permissionLevel); //Actualizamos los datos
                    lstPermissionsLevels.Sort((x, y) => string.Compare(x.plN, y.plN));                      //ordenamos la lista
                    nIndex = lstPermissionsLevels.IndexOf(permissionLevel);                                 //obtenemos la posición
                }
                else
                {
                    lstPermissionsLevels.Remove(permissionLevel);   //Elminamos el registro
                }
                dgrPermissionsLevels.Items.Refresh();               //actualizamos la lista
                GridHelper.SelectRow(dgrPermissionsLevels, nIndex); //seleccionamos el registro
                StatusBarReg.Content = lstPermissionsLevels.Count + " Permission Levels.";
            }
        }
示例#27
0
        public static bool IsAuthorized(PermissionLevel permission, User user)
        {
            if (permission == PermissionLevel.None)
                return true;

            return IsRegistered(user) != null && IsAuthorised(permission, IsRegistered(user));
        }
示例#28
0
        private void WebSocketServer_NewSessionConnected(WebSocketSession session)
        {
            PermissionLevel defaultPermission = (PermissionLevel)config["defaultpermission"].Value <int>();

            while (!clients.TryAdd(session.SessionID, (PermissionLevel)config["defaultpermission"].Value <int>()))
            {
                Thread.Sleep(1);
            }
            session.Send(new WebSocketPackets.InfoPacket()
            {
                Level = defaultPermission
            }.SerializeJson());
            if (defaultPermission >= PermissionLevel.Workers)
            {
                session.Send(new WebSocketPackets.GeneralInfoPacket()
                {
                    TasksCount  = dataController.TaskQueueGetCount(),
                    WorkerCount = workers.Count
                }.SerializeJson());
                session.Send(new WebSocketPackets.StartCPanelPacket()
                {
                    Workers = workers.Values.Select(x => new WebSocketPackets.WorkerInfo()
                    {
                        WorkerProgress = x.LastProgress,
                        WorkerId       = x.GetId(),
                        WorkerStatus   = x.Status,
                        WorkerSystem   = x.System,
                        CurrentTask    = (defaultPermission < PermissionLevel.WorkersTasks ? null : (dataController.CurrentTasksGetByKey(x.GetId()) != null ? new WebSocketPackets.TaskInfo(dataController.CurrentTasksGetByKey(x.GetId()), WebSocketPackets.TaskStatus.Processing) : null))
                    }).ToArray(),
                    ReadyTasks   = dataController.ReadyTasksGetAll().Select(x => new WebSocketPackets.TaskInfo(x, WebSocketPackets.TaskStatus.Ready)).ToArray(),
                    InQueueTasks = dataController.TaskQueueGetAll().Select(x => new WebSocketPackets.TaskInfo(x, WebSocketPackets.TaskStatus.InQueue)).ToArray()
                }.SerializeJson());
            }
        }
        public async Task GetAllListsAsync_SufficientPermissions_ReturnsRtmLists(PermissionLevel permissionLevel)
        {
            // Setup
            var expectedLists = new List <IRtmList> {
                Substitute.For <IRtmList>()
            };

            var fakeAuthToken = new AuthenticationToken {
                Id = "My Fake Token ID", Permissions = permissionLevel
            };
            const string fakeListsUrl = "My Fake URL";

            var fakeUrlFactory = Substitute.For <IListsUrlFactory>();

            fakeUrlFactory.CreateGetListsUrl(fakeAuthToken.Id).Returns(fakeListsUrl);

            var fakeResponseData = new GetListResponseData();
            var fakeApiClient    = Substitute.For <IApiClient>();

            fakeApiClient.GetAsync <GetListResponseData>(fakeListsUrl).Returns(Task.FromResult(fakeResponseData));

            var fakeResponseParser = Substitute.For <IResponseParser>();

            fakeResponseParser.GetLists(fakeResponseData).Returns(expectedLists);

            // Execute
            var listRepository = GetItemUnderTest(fakeUrlFactory, fakeApiClient, fakeResponseParser, fakeAuthToken);
            var actual         = await listRepository.GetAllListsAsync().ConfigureAwait(false);

            // Verify
            Assert.AreSame(expectedLists, actual);
        }
        public static string GetCalendarPermissionsLog(MailboxSession mailboxSession, Folder folder)
        {
            if (mailboxSession == null || folder == null)
            {
                return(string.Empty);
            }
            SecurityIdentifier arg           = IdentityHelper.SidFromLogonIdentity(mailboxSession.Identity);
            StringBuilder      stringBuilder = new StringBuilder();

            stringBuilder.Append(string.Format("Folder Name: {0} Security Descriptor: {1}\n", folder.DisplayName, arg));
            PermissionSet permissionSet = folder.GetPermissionSet();

            if (permissionSet.AnonymousPermission != null)
            {
                PermissionLevel permissionLevel = permissionSet.AnonymousPermission.PermissionLevel;
                MemberRights    memberRights    = permissionSet.AnonymousPermission.MemberRights;
                stringBuilder.Append(string.Format("Anonymous Permission:{0} Member Rights:{1}", permissionLevel, memberRights));
            }
            if (permissionSet.DefaultPermission != null)
            {
                PermissionLevel permissionLevel2 = permissionSet.DefaultPermission.PermissionLevel;
                MemberRights    memberRights2    = permissionSet.DefaultPermission.MemberRights;
                stringBuilder.Append(string.Format("\nDefault Permission:{0} Member Rights:{1}", permissionLevel2, memberRights2));
            }
            foreach (Permission permission in permissionSet)
            {
                MemberRights    memberRights3    = permission.MemberRights;
                PermissionLevel permissionLevel3 = permission.PermissionLevel;
                if (permission.Principal != null)
                {
                    string text  = permission.Principal.ToString();
                    string text2 = permission.Principal.Type.ToString();
                    if (permission.Principal.Type == PermissionSecurityPrincipal.SecurityPrincipalType.ADRecipientPrincipal)
                    {
                        if (permission.Principal.ADRecipient != null)
                        {
                            SmtpAddress primarySmtpAddress = permission.Principal.ADRecipient.PrimarySmtpAddress;
                            text = permission.Principal.ADRecipient.PrimarySmtpAddress.ToString();
                        }
                    }
                    else if (permission.Principal.Type == PermissionSecurityPrincipal.SecurityPrincipalType.SpecialPrincipal)
                    {
                        text2 = permission.Principal.SpecialType.ToString();
                    }
                    stringBuilder.Append(string.Format("\nPermission:{0} UserType:{1} User:{2} Member Rights:{3}", new object[]
                    {
                        permissionLevel3,
                        text2,
                        text,
                        memberRights3
                    }));
                }
                else
                {
                    stringBuilder.Append(string.Format("\nPermission:{0} UserType:'Unknown' User:'******' Member Rights:{1}", permissionLevel3, memberRights3));
                }
            }
            return(stringBuilder.ToString());
        }
示例#31
0
 public string GetSharePointFaqPageWithAnchor(PermissionLevel permissionLevel)
 {
     return(permissionLevel switch
     {
         PermissionLevel.ReadOnly => $"{_externalLinks.SharePointFAQPage}#why-do-i-not-have-permission-to-edit-a-record",
         PermissionLevel.None => $"{_externalLinks.SharePointFAQPage}#why-can’t-i-view-the-full-details-of-a-record",
         _ => null
     });
示例#32
0
 private static bool IsWritePermission(PermissionLevel permission)
 {
     if (permission == PermissionLevel.Read)
     {
         return(false);
     }
     return(permission != PermissionLevel.ReadAcl);
 }
示例#33
0
        protected AccountBasedManagement(IDatabaseContext context, int personId, int accountId)
            : base(context, personId)
        {
            var permission = MyPermissions.Single(x => x.Key.Id == accountId);

            AccountGroup           = permission.Key;
            AccountGroupPermission = permission.Value;
        }
示例#34
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="CommandModel" /> class.
        /// </summary>
        /// <param name="familiarName">
        ///     The familiar name.
        /// </param>
        /// <param name="serverName">
        ///     The server name.
        /// </param>
        /// <param name="paramaterNames">
        ///     The paramater names.
        /// </param>
        /// <param name="typeOfCommand">
        ///     The type of command.
        /// </param>
        /// <param name="permissionLevel">
        ///     The permission level.
        /// </param>
        public CommandModel(
            string familiarName,
            string serverName,
            IList<string> paramaterNames = null,
            CommandTypes typeOfCommand = CommandTypes.SingleSentence,
            PermissionLevel permissionLevel = PermissionLevel.User)
        {
            this.familiarName = familiarName;
            ServerName = serverName;
            CommandType = typeOfCommand;
            PermissionsLevel = permissionLevel;

            ArgumentNames = paramaterNames;
        }
示例#35
0
        public static void CreateDynCommands(this ModuleManager manager, string prefix,
            PermissionLevel defaultPermissionsLevel, Action<CommandGroupBuilder> builder)
        {
            CommandService commandService = manager.Client.GetService<CommandService>();
            commandService.CreateGroup(prefix, x =>
            {
                x.Category(manager.Name);

                x.AddCheck((ModuleChecker)
                    Activator.CreateInstance(typeof (ModuleChecker), _moduleCheckerActivatorFlags, null,
                        new object[] {manager}, null));

                x.MinDynPermissions((int) defaultPermissionsLevel);
                builder(x);
            });
        }
        private static FileSystemRights GetRightsFromPermissionLevel(PermissionLevel level)
        {
            if (level == PermissionLevel.Full)
                return FileSystemRights.FullControl;

            if (level == PermissionLevel.Modify)
                return FileSystemRights.Modify;

            if (level == PermissionLevel.Write)
                return FileSystemRights.Write;

            if (level == PermissionLevel.ReadAndExecute)
                return FileSystemRights.ReadAndExecute;

            return FileSystemRights.Read;
        }
示例#37
0
文件: User.cs 项目: nebez/TwitchBot
 public void RemovePermission(PermissionLevel perm)
 {
     if (_permissions.Contains(perm))
         _permissions.Remove(perm);
 }
示例#38
0
文件: User.cs 项目: nebez/TwitchBot
 public void AddPermission(PermissionLevel perm)
 {
     if (!_permissions.Contains(perm))
         _permissions.Add(perm);
 }
示例#39
0
文件: File.cs 项目: Xuehuo/SAA-Online
 /// <summary>
 /// Check whether a user has the permission to a file (static function)
 /// </summary>
 /// <param name="permission">Permission setting</param>
 /// <param name="uuid">UUID (of uploader)</param>
 /// <param name="group">Group (of uploader)</param>
 /// <param name="user">User (current one most possibly)</param>
 /// <returns>whether a user has the permission to a file</returns>
 public static bool Visible(PermissionLevel permission, string uuid, int group, User user)
 {
     if (uuid == user.UUID)
         return true;
     switch (permission)
     {
         case PermissionLevel.All:
             return true;
         case PermissionLevel.SelfGroupOnly:
             if (group == user.Group)
                 return true;
             break;
         case PermissionLevel.SeniorTwoOnly:
             if (user.Senior == 2)
                 return true;
             break;
         case PermissionLevel.ImptMembOnly:
             if (user.IsExecutive)
                 return true;
             break;
         default:
             return false;
     }
     return false;
 }
        private bool CheckLogin(string login, string password)
        {
            //this.statusbarLogin.Text = "ChristianT";
            //return true;
            //ConfigurationSettings config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Set;
            //System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None); //TeamManagement_Tool.Properties.Settings.Default; // System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //Configuration config = ConfigurationManager.OpenMappedExeConfiguration(

            //Configuration config = Configuration

            try
            {
                MySqlCommand sqlCmd = new MySqlCommand("Select Password,PermissionLevel from User where login = '******'", sqlConnection);
                sqlConnection.Open();
                MySqlDataReader sqlRead = sqlCmd.ExecuteReader();

                //if (sqlRead.Read()) {
                Console.WriteLine("Eingabe = " + MD5_Crypto.GetMd5Hash(password));
                //Console.WriteLine("Gespeichert = " + sqlRead.GetValue(0).ToString());
                //if (sqlRead.Read() && sqlRead.GetValue(0).ToString() == password)
                if (sqlRead.Read() && sqlRead.GetValue(0).ToString() == MD5_Crypto.GetMd5Hash(password))
                {
                    this.statusbarLogin.Text = login;
                    currentPermission = (PermissionLevel)sqlRead.GetInt32("PermissionLevel");
                    this.statusbarPermission.Text = Enum.GetName(typeof(PermissionLevel), currentPermission);
                    sqlRead.Close();
                    sqlConnection.Close();
                    return true;
                }
                else
                {
                    sqlRead.Close();
                    sqlConnection.Close();
                }
                /*}
                else
                {
                    sqlRead.Close();
                    sqlCon.Close();
                }*/
                return false;
            }
            catch (MySqlException e)
            {
                MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }
        }
示例#41
0
 public Task ChangePermissionLevel(IBoardId board, PermissionLevel permissionLevel)
 {
     return _restClient.RequestAsync(new BoardsChangePermissionLevelRequest(board, permissionLevel));
 }
 public static void SetFilePermission(string path, string accountName, PermissionLevel permissionLevel)
 {
     AddFileSecurity(path, accountName, GetRightsFromPermissionLevel(permissionLevel));
 }
示例#43
0
 public static bool IsAuthorised(PermissionLevel level, ChatUser user)
 {
     return level == user.PermissionLevel;
 }
示例#44
0
 /// <summary>
 /// A new bot Command with the permissionLevel permissionLevel, and the evaluate action of action
 /// </summary>
 public BotCommand(PermissionLevel permissionLevel, string helpText, Action<CommandArgs> action)
 {
     PermissionLevel = permissionLevel;
     HelpText = helpText;
     Action = action;
 }
示例#45
0
 public Permission(string node, string description, PermissionLevel level)
 {
     this.node = node.ToLower();
     this.description = description;
     this.level = level;
 }
示例#46
0
 public Permission(string node)
 {
     this.node = node.ToLower();
     this.description = null;
     this.level = PermissionLevel.All;
 }
示例#47
0
                private void LoadPermissionlevels()
                {                 
                    _groupServiceAgent.GetPermissionLevels((roleDefs, e) =>
                    {
                        
                        _dispatcher.BeginInvoke(new Action(() =>
                        {
                            if (roleDefs != null && roleDefs.Count > 0)
                            {
                                EditGroupPermissionLevels.Clear();
                                foreach (RoleDefinition r in roleDefs)
                                {                                    
                                    PermissionLevel p = new PermissionLevel()
                                    {
                                        Description = r.Description,
                                        Mask = r.Id,
                                        LevelName = r.Name,
                                        IsEditable = !r.Hidden,
                                        IsLevelEnabled = !r.Hidden
                                    };
                                    EditGroupPermissionLevels.Add(p);                                    
                                }

                                if (EditGroupPermissionLevels != null && EditGroupPermissionLevels.Count > 0)
                                {
                                    NewGroupPermissionLevels.Clear();
                                    foreach (PermissionLevel p in EditGroupPermissionLevels)
                                    {
                                        if (p.IsLevelEnabled == true) //Add only non-Hidden
                                        {
                                            NewGroupPermissionLevels.Add(p);
                                        }
                                    }
                                }
                            }
                        }));
                    });
                    
                  
                }
示例#48
0
 public AdaCommand(bool isCommand, PermissionLevel permission, Action<string, string, User, Room, Client> action)
 {
     IsCommand = isCommand;
     Action = action;
     permissionLevel = permission;
 }
 public BoardsChangePermissionLevelRequest(IBoardId board, PermissionLevel permissionLevel)
     : base(board, "prefs/permissionLevel", Method.PUT)
 {
     this.AddValue(permissionLevel.ToTrelloString());
 }
 public static void SetDirectoryPermission(string path, string accountName, PermissionLevel permissionLevel)
 {
     AddDirectorySecurity(path, accountName, GetRightsFromPermissionLevel(permissionLevel));
 }
 public Certificate()
 {
     this.permissionLevelField = PermissionLevel.limitedOrElevated;
 }
示例#52
0
文件: Boards.cs 项目: Bunk/trellow
		public void ChangePermissionLevel(IBoardId board, PermissionLevel permissionLevel)
		{
			_restClient.Request(new BoardsChangePermissionLevelRequest(board, permissionLevel));
		}