Esempio n. 1
0
        public string GetPasswordForAccessLevel(AccessLevel level)
        {
            if (PasswordFileFound && PasswordFileValid)
            {
                return(this.mLoadedPasswords[level.ToString()]);
            }

            return(this.mDefaultPasswords[level.ToString()]);
        }
Esempio n. 2
0
 public static void HasAccessLevel(int id, AccessLevel accessLevel)
 {
     string uriTemplate = _baseAddress + "/odata/HasAccessLevel(ID={0},AccessLevel={1}'{2}')";
     string requestUri = string.Format(uriTemplate, id, typeof(AccessLevel).FullName, accessLevel.ToString());
     using (HttpResponseMessage response = _httpClient.GetAsync(requestUri).Result)
     {
         response.EnsureSuccessStatusCode();
         JObject result = response.Content.ReadAsAsync<JObject>().Result;
         Console.WriteLine("\nEmployee with ID '{0}' has access level '{1}': ", id, accessLevel.ToString());
         Console.WriteLine(result);
     }
 }
Esempio n. 3
0
 private void SessionSet(string username, AccessLevel accessLevel)
 {
     HttpContext.Session.SetString("Login", "true");
     HttpContext.Session.SetString("User", username.ToLower());
     HttpContext.Session.SetString("AccessLevel", accessLevel.ToString());
     ActivityLog.Log(username + " logged into Dungeon Master");
 }
Esempio n. 4
0
        /// <summary>
        /// Generates a token that can be used for sharing a Realm.
        /// </summary>
        /// <returns>
        /// A token that can be shared with another user, e.g. via email or message and then consumed by
        /// <see cref="AcceptPermissionOfferAsync"/> to obtain permissions to a Realm.</returns>
        /// <param name="realmPath">The Realm URL whose permissions settings should be changed. Use <c>*</c> to change the permissions of all Realms managed by this <see cref="User"/>.</param>
        /// <param name="accessLevel">
        /// The access level to grant matching users. Note that the access level setting is absolute, i.e. it may revoke permissions for users that
        /// previously had a higher access level. To revoke all permissions, use <see cref="AccessLevel.None" />
        /// </param>
        /// <param name="expiresAt">Optional expiration date of the offer. If set to <c>null</c>, the offer doesn't expire.</param>
        public async Task <string> OfferPermissionsAsync(string realmPath, AccessLevel accessLevel, DateTimeOffset?expiresAt = null)
        {
            if (string.IsNullOrEmpty(realmPath))
            {
                throw new ArgumentNullException(nameof(realmPath));
            }

            if (expiresAt < DateTimeOffset.UtcNow)
            {
                throw new ArgumentException("The expiration date may not be in the past", nameof(expiresAt));
            }

            if (accessLevel == AccessLevel.None)
            {
                throw new ArgumentException("The access level may not be None", nameof(accessLevel));
            }

            var payload = new Dictionary <string, object>
            {
                ["expiresAt"]   = expiresAt?.ToString("O"),
                ["realmPath"]   = realmPath,
                ["accessLevel"] = accessLevel.ToString().ToLower()
            };

            var result = await MakePermissionRequestAsync(HttpMethod.Post, "permissions/offers", payload);

            return(result.ToObject <PermissionOffer>().Token);
        }
Esempio n. 5
0
        public override JObject ToJObject()
        {
            JObject jObject = base.ToJObject();

            if (jObject == null)
            {
                return(jObject);
            }

            if (vendorId != null)
            {
                jObject.Add("VendorId", vendorId);
            }

            jObject.Add("ReadAccessLevel", readAccessLevel.ToString());
            jObject.Add("WriteAccessLevel", writeAccessLevel.ToString());


            if (fieldName != null)
            {
                jObject.Add("FieldName", fieldName);
            }

            if (fieldDocumentation != null)
            {
                jObject.Add("FieldDocumentation", fieldDocumentation);
            }

            return(jObject);
        }
Esempio n. 6
0
        private void button_OK_Click(object sender, System.EventArgs e)
        {
            AccessLevel newAccessLevel = ((AccessLevel_Localized)(comboBox_Login.SelectedItem)).val;
            bool        isSuccess      = true;

            if (newAccessLevel > mCurrentAccessLevel)
            {
                string expected = mPasswordFile.GetPasswordForAccessLevel(newAccessLevel);
                if (expected != "")
                {
                    this.Text = ResourceUtility.FormatString("RtEnterPassword", newAccessLevel.ToString());
                    string enteredPassword = this.textBox_Password.Text;
                    if (enteredPassword != expected)
                    {
                        isSuccess = false;
                        MessageBox.Show(ResourceUtility.GetString("RtInvalidPassword2"), ResourceUtility.GetString("RtInvalidPassword"));
                    }
                }
            }
            if (isSuccess)
            {
                mCurrentAccessLevel = newAccessLevel;
                this.DialogResult   = DialogResult.OK;
                this.Close();
                MessageLoggerManager.Log.Info("[Action] Log-in as " + mCurrentAccessLevel.ToString());
            }
            //else
            //{
            //    this.DialogResult = DialogResult.Cancel;
            //}
        }
Esempio n. 7
0
        public static void EditUserType(CMSDatabase db, int?itemID, UserTypeModel model, HttpContext context, out bool successfullyCompleted)
        {
            if (string.IsNullOrEmpty(model.Name) || !model.AccessLevel.HasValue || !itemID.HasValue || !Enum.IsDefined(typeof(AccessLevel), model.AccessLevel.Value))
            {
                successfullyCompleted = false;
                return;
            }
            UserType userType = db.UserTypes.FirstOrDefault(ut => ut.ID == itemID.Value);

            if (userType == null || (userType.ID == 1 && model.AccessLevel.Value != userType.AccessLevel))
            {
                successfullyCompleted = false;
                return;
            }
            string      oldName        = userType.Name;
            AccessLevel oldAccessLevel = userType.AccessLevel;

            userType.Name        = model.Name;
            userType.AccessLevel = model.AccessLevel.Value;
            db.SaveChanges();
            successfullyCompleted = true;

            LogManagementFunctions.AddAdminPanelLog(
                db: db,
                context: context,
                info: $"{oldName} ({oldAccessLevel.ToString()}) -> {userType.Name} ({userType.AccessLevel.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.UserTypeEdited}"
                );
        }
Esempio n. 8
0
        public override void Write(IWriter writer)
        {
            Comment?.Write(writer);

            writer.Append(AccessLevel.ToString().ToLower());
            writer.Append(" ");

            if (IsStatic)
            {
                writer.Append("static ");
            }
            else
            {
                if (IsAbstract)
                {
                    writer.Append("abstract ");
                }
            }

            if (IsReadonly)
            {
                writer.Append("readonly ");
            }

            base.Write(writer);
        }
        /// <summary>
        /// Gets the C# representation of the access level.
        /// </summary>
        /// <param name="access">The access level.</param>
        /// <returns>The access level the compiler expects in C# source files.</returns>
        public static string AccessString(this AccessLevel access)
        {
            switch (access)
            {
            case AccessLevel.ProtectedInternal:
                return("protected internal");

            default:
                return(access.ToString().ToLower());
            }
        }
        public static void QueryEmployeesByAccessLevel(AccessLevel accessLevel)
        {
            string uriTemplate = _baseAddress + "/odata/Employees?$filter=AccessLevel has {0}'{1}'";
            string uriHas = string.Format(uriTemplate, typeof(AccessLevel).FullName, accessLevel.ToString());

            using (HttpResponseMessage response = _httpClient.GetAsync(uriHas).Result)
            {
                response.EnsureSuccessStatusCode();
                JObject result = response.Content.ReadAsAsync<JObject>().Result;
                Console.WriteLine("\nEmployees who has the access level '{0}' are:", accessLevel.ToString());
                Console.WriteLine(result);
            }
        }
Esempio n. 11
0
        public static void QueryEmployeesByAccessLevel(AccessLevel accessLevel)
        {
            string uriTemplate = _baseAddress + "/odata/Employees?$filter=AccessLevel has {0}'{1}'";
            string uriHas      = string.Format(uriTemplate, typeof(AccessLevel).FullName, accessLevel.ToString());

            using (HttpResponseMessage response = _httpClient.GetAsync(uriHas).Result)
            {
                response.EnsureSuccessStatusCode();
                JObject result = response.Content.ReadAsAsync <JObject>().Result;
                Console.WriteLine("\nEmployees who has the access level '{0}' are:", accessLevel.ToString());
                Console.WriteLine(result);
            }
        }
        public override string ToString()
        {
            string name = "[" + Name;

            if (CodeType != null)
            {
                name += ", Type:" + CodeType.Name;
            }
            name += ", Access:" + AccessLevel.ToString();
            name += ", Store:" + StoreType.ToString();
            name += "]";
            return(name);
        }
Esempio n. 13
0
        public static void AddAccessLevel(int id, AccessLevel accessLevel)
        {
            var     requestUri  = _baseAddress + string.Format("/odata/Employees({0})/{1}.AddAccessLevel", id, _namespace);
            string  body        = string.Format(@"{{'AccessLevel':'{0}'}}", accessLevel.ToString());
            JObject postContent = JObject.Parse(body);

            using (HttpResponseMessage response = _httpClient.PostAsJsonAsync(requestUri, postContent).Result)
            {
                response.EnsureSuccessStatusCode();
                JObject result = response.Content.ReadAsAsync <JObject>().Result;
                Console.WriteLine("\nThe new access level of employee with ID '{0}' is:", id);
                Console.WriteLine(result);
            }
        }
Esempio n. 14
0
        public static void AddAccessLevel(int id, AccessLevel accessLevel)
        {
            var requestUri = _baseAddress + string.Format("/odata/Employees({0})/{1}.AddAccessLevel", id, _namespace);
            string body = string.Format(@"{{'AccessLevel':'{0}'}}", accessLevel.ToString());
            JObject postContent = JObject.Parse(body);

            using (HttpResponseMessage response = _httpClient.PostAsJsonAsync(requestUri, postContent).Result)
            {
                response.EnsureSuccessStatusCode();
                JObject result = response.Content.ReadAsAsync<JObject>().Result;
                Console.WriteLine("\nThe new access level of employee with ID '{0}' is:", id);
                Console.WriteLine(result);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Changes the permissions of a Realm.
        /// </summary>
        /// <returns>
        /// An awaitable task, that, upon completion, indicates that the permissions have been successfully applied by the server.
        /// </returns>
        /// <param name="condition">A <see cref="PermissionCondition"/> that will be used to match existing users against.</param>
        /// <param name="realmPath">The Realm path whose permissions settings should be changed. Use <c>*</c> to change the permissions of all Realms managed by this <see cref="User"/>.</param>
        /// <param name="accessLevel">
        /// The access level to grant matching users. Note that the access level setting is absolute, i.e. it may revoke permissions for users that
        /// previously had a higher access level. To revoke all permissions, use <see cref="AccessLevel.None" />
        /// </param>
        public async Task ApplyPermissionsAsync(PermissionCondition condition, string realmPath, AccessLevel accessLevel)
        {
            if (string.IsNullOrEmpty(realmPath))
            {
                throw new ArgumentNullException(nameof(realmPath));
            }

            var payload = new Dictionary <string, object>
            {
                ["condition"]   = condition.ToJsonObject(),
                ["realmPath"]   = realmPath,
                ["accessLevel"] = accessLevel.ToString().ToLower()
            };

            await MakePermissionRequestAsync(HttpMethod.Post, "permissions/apply", payload);
        }
Esempio n. 16
0
        private string GetPermissionsAsString()
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < _permissions.Length; i++)
            {
                AccessLevel accessLevel = _permissions[i];
                sb.Append(accessLevel.ToString());
                if (i < _permissions.Length - 1)
                {
                    sb.Append(", ");
                }
            }

            return(sb.ToString());
        }
Esempio n. 17
0
        public void Write(IWriter writer)
        {
            if (Comment != null)
            {
                Comment.Write(writer);
                writer.Append("\n");
            }

            writer.Append(AccessLevel.ToString().ToLower());
            writer.Append(" ");

            if (IsStatic)
            {
                writer.Append("static ");
            }
            else
            {
                if (IsAbstract)
                {
                    writer.Append("abstract ");
                }
            }

            writer.Append(Name);
            writer.Append("(");

            if (Parameters.Count > 0)
            {
                writer.Join(", ", Parameters);
            }

            writer.Append("): ");
            Return.Write(writer);

            if (IsAbstract || Body == null)
            {
                writer.Append(";");
            }
            else
            {
                writer.Append("{\n");
                Body.WriteBody(writer, this);
                writer.Append("\n}");
            }
        }
Esempio n. 18
0
    protected new void Start()
    {
        base.Start();
        manager     = GameManager.manager.AIManager;
        tileManager = GameManager.manager.tileManager;
        manager.AIList.Add(this);
        AIName = manager.names.names[Random.Range(0, manager.names.names.Length - 1)];

        if (tooltip != null)
        {
            tooltip.SetProperty("Name", AIName.ToString());
            tooltip.SetProperty("Access Level", accessLevel.ToString());
            tooltip.SetProperty("Occupied", occupied.ToString());
            tooltip.SetProperty("Current Task", task.type.ToString());

            tooltip.SetCommand("Execute", Die);
        }
    }
        ///GENMHASH:5E14BE5799A25FD072BFBD2635947666:F9F576DF5B4E696FFA8774883C7E48E2
        public async Task <string> GrantAccessAsync(
            string resourceGroupName,
            string diskName,
            AccessLevel accessLevel,
            int accessDuration,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            GrantAccessDataInner grantAccessDataInner = new GrantAccessDataInner();

            grantAccessDataInner.Access            = accessLevel.ToString();
            grantAccessDataInner.DurationInSeconds = accessDuration;
            AccessUriInner accessUriInner = await Inner.GrantAccessAsync(resourceGroupName,
                                                                         diskName,
                                                                         grantAccessDataInner,
                                                                         cancellationToken);

            return(accessUriInner.AccessSAS);
        }
Esempio n. 20
0
        private static int GetArgInt(Mobile from, string pattern, string args, AccessLevel accessLevel, int defaultValue)
        {   // sanity
            if (from == null || pattern == null)
            {
                return(0);
            }

            // check access
            if (from.AccessLevel < accessLevel)
            {
                from.SendMessage("You must have {0} access to use the {1} switch.", accessLevel.ToString(), pattern);
                return(defaultValue);
            }

            // all int switches MUST be exactly of the form "-x=nn" where nn is the int portion. no spaces allowed
            try
            {                   // extract the integer argument from the arg-string.
                string argID      = String.Format("{0}=", pattern);
                int    startIndex = args.IndexOf(argID);
                if (startIndex == -1)
                {
                    throw new ApplicationException();
                }
                int    whiteIndex = args.IndexOf(' ', startIndex);
                int    intStart   = startIndex + pattern.Length + 1;
                string argVal     = (whiteIndex == -1) ? args.Substring(intStart) : args.Substring(intStart, whiteIndex - argID.Length);
                int    param;
                if (int.TryParse(argVal, out param) == false)
                {
                    throw new ApplicationException();
                }
                else
                {
                    return(param);
                }
            }
            catch // no logging here
            {
                from.SendMessage("Poorly formed {0} switch.", pattern);
                return(defaultValue);
            }
        }
Esempio n. 21
0
        private void FormLogin_Load(object sender, EventArgs e)
        {
            comboBox_Login.Items.Add(new AccessLevel_Localized(AccessLevel.Operator, ResourceUtility.GetString("RtOperator")));
            comboBox_Login.Items.Add(new AccessLevel_Localized(AccessLevel.Supervisor, ResourceUtility.GetString("RtSupervisor")));
            comboBox_Login.Items.Add(new AccessLevel_Localized(AccessLevel.Administrator, ResourceUtility.GetString("RtAdministrator")));
            // default access level is "Operator"
            comboBox_Login.SelectedIndex = (int)mCurrentAccessLevel;
            label_CurrentLogin.Text      = string.Format("(当前登陆用户:{0})", mCurrentAccessLevel.ToString());

            // create, validate & setup the password file
            string passwordfname = Utility.ResolveAssociatedFilename(FormMain.strLoadedVppFilePath[0], "passwords.txt");

            mCurrentPasswordFile = new PasswordFile(passwordfname);
            if (mCurrentPasswordFile.PasswordFileFound && !mCurrentPasswordFile.PasswordFileValid)
            {
                string quoted = "\"" + mCurrentPasswordFile.PasswordFilename + "\"";
                // label_controlErrorMessage.Text = ResourceUtility.FormatString("RtInvalidPasswordFile", quoted);
            }
            // mCurrentPasswordFile.SetDefaultPassword(AccessLevel.Operator, mDefaultOperatorPassword);
            mCurrentPasswordFile.SetDefaultPassword(AccessLevel.Administrator, mDefaultAdministratorPassword);
            mCurrentPasswordFile.SetDefaultPassword(AccessLevel.Supervisor, mDefaultSupervisorPassword);

            EnableOk();
        }
Esempio n. 22
0
 internal void InsertNewSessionImpl(string newSessionId, AccessLevel al)
 {
     this.cache[newSessionId] = al.ToString();
 }
Esempio n. 23
0
            private void FinishTarget(Mobile m, Mobile from, AccessLevel level)
            {
                Account acct = m.Account as Account;

                if (acct != null)
                {
                    acct.AccessLevel = level;
                }

                m.AccessLevel = level;

                from.SendMessage(String.Format("The accesslevel for {0} has been changed to {1}.", m.RawName, level.ToString()));
            }
Esempio n. 24
0
 public virtual bool HasPermission(AccessLevel permission)
 {
     return HasRight(permission.ToString());
 }
Esempio n. 25
0
 ///<summary>
 /// Get appropriate users assigned to a project by access level.
 ///</summary>
 /// <exception cref="MCException"></exception>
 public IList<IAccount> GetProjectUsers(long projectId, AccessLevel access)
 {
     var mc = CreateMantisClientProxyInstance();
     try
     {
         AccountData[] data = mc.mc_project_get_users(Username, Password, projectId.ToString(), access.ToString());
         IList<IAccount> result = new List<IAccount>();
         foreach (var item in data)
         {
             result.Add(new Account(item));
         }
         return result;
     }
     catch (Exception ex)
     {
         throw new MCException(String.Format("Could not get project users for project {0}", projectId), ex);
     }
     finally
     {
         mc.CloseSafely();
     }
 }
Esempio n. 26
0
        public async Task HandleHelpCommand(CommandContext context)
        {
            AccessLevel userLevel = SettingsModel.GetUserAccessLevel(context.Guild.GetUser(context.User.Id));

            List <EmbedField> embeds = new List <EmbedField>();

            foreach (Command cmd in CommandService.commands)
            {
                if (cmd.HasPermission(userLevel))
                {
                    embeds.Add(new EmbedField(CommandService.Prefix + cmd.Syntax, cmd.Summary));
                }
            }
            await context.Channel.SendSafeEmbedList(string.Format("Your access level is `{0}`. Available commands:", userLevel.ToString()), embeds, string.Format("Use `{0}help <cmdname>` to see syntax.", CommandService.Prefix));
        }
Esempio n. 27
0
 public void SetPasswordForAccessLevel(AccessLevel level, string pass)
 {
     mLoadedPasswords[level.ToString()] = pass;
 }
Esempio n. 28
0
        /// <summary>
        /// Serializes this Account instance to an XmlTextWriter.
        /// </summary>
        /// <param name="xml">The XmlTextWriter instance from which to serialize.</param>
        public void Save(XmlTextWriter xml)
        {
            xml.WriteStartElement("account");

            xml.WriteStartElement("username");
            xml.WriteString(m_Username);
            xml.WriteEndElement();

            if (m_PlainPassword != null)
            {
                xml.WriteStartElement("password");
                xml.WriteString(m_PlainPassword);
                xml.WriteEndElement();
            }

            if (m_CryptPassword != null)
            {
                xml.WriteStartElement("cryptPassword");
                xml.WriteString(m_CryptPassword);
                xml.WriteEndElement();
            }

            if (m_NewCryptPassword != null)
            {
                xml.WriteStartElement("newCryptPassword");
                xml.WriteString(m_NewCryptPassword);
                xml.WriteEndElement();
            }

            if (m_AccessLevel != AccessLevel.Player)
            {
                xml.WriteStartElement("accessLevel");
                xml.WriteString(m_AccessLevel.ToString());
                xml.WriteEndElement();
            }

            if (m_Flags != 0)
            {
                xml.WriteStartElement("flags");
                xml.WriteString(XmlConvert.ToString(m_Flags));
                xml.WriteEndElement();
            }

            xml.WriteStartElement("created");
            xml.WriteString(XmlConvert.ToString(m_Created, XmlDateTimeSerializationMode.Local));
            xml.WriteEndElement();

            xml.WriteStartElement("lastLogin");
            xml.WriteString(XmlConvert.ToString(m_LastLogin, XmlDateTimeSerializationMode.Local));
            xml.WriteEndElement();

            xml.WriteStartElement("totalGameTime");
            xml.WriteString(XmlConvert.ToString(TotalGameTime));
            xml.WriteEndElement();

            xml.WriteStartElement("chars");

            //xml.WriteAttributeString( "length", m_Mobiles.Length.ToString() );	//Legacy, Not used anymore

            for (int i = 0; i < m_Mobiles.Length; ++i)
            {
                Mobile m = m_Mobiles[i];

                if (m != null && !m.Deleted)
                {
                    xml.WriteStartElement("char");
                    xml.WriteAttributeString("index", i.ToString());
                    xml.WriteString(m.Serial.Value.ToString());
                    xml.WriteEndElement();
                }
            }

            xml.WriteEndElement();

            if (m_Comments != null && m_Comments.Count > 0)
            {
                xml.WriteStartElement("comments");

                for (int i = 0; i < m_Comments.Count; ++i)
                {
                    m_Comments[i].Save(xml);
                }

                xml.WriteEndElement();
            }

            if (m_Tags != null && m_Tags.Count > 0)
            {
                xml.WriteStartElement("tags");

                for (int i = 0; i < m_Tags.Count; ++i)
                {
                    m_Tags[i].Save(xml);
                }

                xml.WriteEndElement();
            }

            if (m_LoginIPs.Length > 0)
            {
                xml.WriteStartElement("addressList");

                xml.WriteAttributeString("count", m_LoginIPs.Length.ToString());

                for (int i = 0; i < m_LoginIPs.Length; ++i)
                {
                    xml.WriteStartElement("ip");
                    xml.WriteString(m_LoginIPs[i].ToString());
                    xml.WriteEndElement();
                }

                xml.WriteEndElement();
            }

            if (m_IPRestrictions.Length > 0)
            {
                xml.WriteStartElement("accessCheck");

                for (int i = 0; i < m_IPRestrictions.Length; ++i)
                {
                    xml.WriteStartElement("ip");
                    xml.WriteString(m_IPRestrictions[i]);
                    xml.WriteEndElement();
                }

                xml.WriteEndElement();
            }

            xml.WriteEndElement();
        }
Esempio n. 29
0
        Claim CreateLoginClaim(DBContext c, User user, WebUser wuser, string username)
        {
            Claim cl = new Claim(ClaimTypes.NameIdentifier, username);

            if (user.DiscordUserId != 0)
            {
                if (wuser != null)
                {
                    cl.Properties[ClaimProperties.AllowGlobalStats] = wuser.AllowGlobalStats.ToString();
                }
                else
                {
                    cl.Properties[ClaimProperties.AllowGlobalStats] = false.ToString();
                }

                List <Permission> permissions = c.Permission.Where(p => p.DiscordUserId == user.DiscordUserId &&
                                                                   p.AccessLevel >= (short)AccessLevel.Host &&
                                                                   (p.DiscordGuildId != 0 || p.AccessLevel == (short)AccessLevel.Dev))
                                                .ToList();

                List <Permission> filteredPerms = new List <Permission>();

                for (int i = 0; i < permissions.Count; i++)
                {
                    Permission perm = filteredPerms.FirstOrDefault(p => p.DiscordGuildId == permissions[i].DiscordGuildId);

                    if (perm != null && perm.AccessLevel < permissions[i].AccessLevel)
                    {
                        filteredPerms.Remove(perm);
                        filteredPerms.Add(permissions[i]);
                        continue;
                    }

                    filteredPerms.Add(permissions[i]);
                }

                cl.Properties[ClaimProperties.TotalServers]  = filteredPerms.Count.ToString();
                cl.Properties[ClaimProperties.DiscordUserId] = user.DiscordUserId.ToString();

                if (filteredPerms.Count > 0)
                {
                    AccessLevel global    = (AccessLevel)filteredPerms[0].AccessLevel;
                    bool        useGlobal = global == AccessLevel.Dev;

                    cl.Properties[ClaimProperties.IsDev] = permissions.Any(p => p.DiscordGuildId == 0 && p.AccessLevel == (short)AccessLevel.Dev).ToString();

                    cl.Properties[ClaimProperties.DiscordGuildId] = filteredPerms[0].DiscordGuildId.ToString();
                    cl.Properties[ClaimProperties.AccessLevel]    = useGlobal ? global.ToString() : ((AccessLevel)filteredPerms[0].AccessLevel).ToString();

                    for (int i = 1; i < filteredPerms.Count; i++)
                    {
                        cl.Properties[$"{ClaimProperties.DiscordGuildId}{i}"] = permissions[i].DiscordGuildId.ToString();
                        cl.Properties[$"{ClaimProperties.AccessLevel}{i}"]    = useGlobal ? global.ToString() : ((AccessLevel)filteredPerms[i].AccessLevel).ToString();
                    }
                }
                else
                {
                    cl.Properties[ClaimProperties.DiscordGuildId] = "0";
                    cl.Properties[ClaimProperties.AccessLevel]    = AccessLevel.User.ToString();
                }
            }
            else
            {
                cl.Properties[ClaimProperties.DiscordUserId]  = "0";
                cl.Properties[ClaimProperties.DiscordGuildId] = "0";
                cl.Properties[ClaimProperties.AccessLevel]    = AccessLevel.User.ToString();
            }

            return(cl);
        }
 public bool AccessCheck(AccessLevel user, AccessLevel required)
 {
     if (user >= required)
     {
         return(true);
     }
     else
     {
         throw new Exception(string.Format("Insufficient access, your access level {0} required access level {1}", user.ToString(), required.ToString()));
     }
 }
Esempio n. 31
0
 public void SetDefaultPassword(AccessLevel level, string pass)
 {
     this.mDefaultPasswords.Add(level.ToString(), pass);
 }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            // no permission
            if (AccessLevel == RFAccessLevel.NotSet && string.IsNullOrWhiteSpace(Permission))
            {
                SetCachePolicy(filterContext);
                return;
            }
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if (RFSettings.GetAppSetting("DisableAuthentication", false))
                {
                    return;
                }

                // auth failed, redirect to login page
                filterContext.Result = new HttpUnauthorizedResult();
            }

            var userName       = filterContext.HttpContext.User.Identity.Name;
            var controllerName = filterContext.RouteData.GetRequiredString("controller");
            var areaName       = filterContext.RouteData.DataTokens["area"]?.ToString() ?? "Core";
            var actionName     = filterContext.RouteData.GetRequiredString("action");
            var accessOk       = AccessLevel == RFAccessLevel.NotSet || RIFFStart.UserRole.HasPermission(userName, areaName, controllerName, AccessLevel.ToString());
            var permissionOk   = string.IsNullOrWhiteSpace(Permission) || RIFFStart.UserRole.HasPermission(userName, areaName, controllerName, Permission);

            if (!accessOk || !permissionOk)
            {
                RFStatic.Log.Warning(this, "Denying authorization to user {0} to area {1}/{2}/{3}:{4}",
                                     userName, areaName, controllerName, AccessLevel.ToString(), Permission);

                var message = String.Format("Unauthorized - permission required: {0}/{1}/{2}/{3}", areaName,
                                            controllerName, AccessLevel.ToString(), Permission);
                switch (ResponseType)
                {
                case ResponseType.Page:
                {
                    var viewData = new ViewDataDictionary(new RIFF.Web.Core.Models.ErrorModel
                        {
                            Message = message
                        });
                    viewData.Add("Title", "Unauthorized");
                    filterContext.Result = new ViewResult {
                        ViewName = "RIFFError", ViewData = viewData
                    };
                }
                break;

                case ResponseType.Json:
                    filterContext.Result = new JsonResult
                    {
                        ContentType = "application/json",
                        Data        = JsonError.Throw(actionName, message)
                    };
                    break;
                }
            }
            else
            {
                SetCachePolicy(filterContext);
            }
        }
Esempio n. 33
0
        private static int GetArgInt(Mobile from, string pattern, string args, AccessLevel accessLevel, int defaultValue)
        {   // sanity
            if (from == null || pattern == null)
                return 0;

            // check access
            if (from.AccessLevel < accessLevel)
            {
                from.SendMessage("You must have {0} access to use the {1} switch.", accessLevel.ToString(), pattern);
                return defaultValue;
            }

            // all int switches MUST be exactly of the form "-x=nn" where nn is the int portion. no spaces allowed
            try
			{	// extract the integer argument from the arg-string.
				string argID = String.Format("{0}=", pattern);
				int startIndex = args.IndexOf(argID);
                if (startIndex == -1) throw new ApplicationException();
				int whiteIndex = args.IndexOf(' ',startIndex);
				int intStart = startIndex + pattern.Length + 1;
				string argVal = (whiteIndex == -1) ? args.Substring(intStart) : args.Substring(intStart, whiteIndex - argID.Length);
                int param;
				if (int.TryParse(argVal, out param) == false)
                    throw new ApplicationException();
                else
                    return param;
            }
            catch // no logging here
            {
                from.SendMessage("Poorly formed {0} switch.", pattern);
                return defaultValue;
            }
        }
Esempio n. 34
0
        public string PassWordCreate(uint UIDr, string Requester, uint UIDc, string Creator)
        {
            string Password = "";

            Password = UIDr.ToString("X") + "$" + Requester + "%" + Creator + "#" + UIDc.ToString("X") + ">" + AccessLevel.ToString();
            byte[] ba        = Encoding.Default.GetBytes(Password);
            var    hexString = BitConverter.ToString(ba);

            hexString = hexString.Replace("-", "");
            return(hexString);
        }
Esempio n. 35
0
 internal void UpdateAccessLevel(string p, AccessLevel accessLevel)
 {
     this.cache[p] = accessLevel.ToString();
 }
Esempio n. 36
0
			private void FinishTarget( Mobile m, Mobile from, AccessLevel level )
			{
				Account acct = m.Account as Account;

				if( acct != null )
					acct.AccessLevel = level;

				m.AccessLevel = level;

				from.SendMessage( String.Format( "The accesslevel for {0} has been changed to {1}.", m.RawName, level.ToString() ) );
			}
Esempio n. 37
0
 public virtual bool HasPermission(AccessLevel permission)
 {
     return(HasRight(permission.ToString()));
 }
Esempio n. 38
0
        public static void HasAccessLevel(int id, AccessLevel accessLevel)
        {
            string uriTemplate = _baseAddress + "/odata/HasAccessLevel(ID={0},AccessLevel={1}'{2}')";
            string requestUri  = string.Format(uriTemplate, id, typeof(AccessLevel).FullName, accessLevel.ToString());

            using (HttpResponseMessage response = _httpClient.GetAsync(requestUri).Result)
            {
                response.EnsureSuccessStatusCode();
                JObject result = response.Content.ReadAsAsync <JObject>().Result;
                Console.WriteLine("\nEmployee with ID '{0}' has access level '{1}': ", id, accessLevel.ToString());
                Console.WriteLine(result);
            }
        }
Esempio n. 39
0
        public static string GetName(this AccessLevel?prop)
        {
            DisplayAttribute description = prop.GetAttributeOfType <DisplayAttribute>();

            return(description?.Name ?? prop?.ToString() ?? "");
        }