Esempio n. 1
0
 void OnCMSAdminAuthenticationSuccess(string source, Result result)
 {
     if (!WebAuthentication.VerifyAccess(PermissionType.AdministrativeAccess))
     {
         result.SetFailed("You don't have access to this area.");
     }
 }
Esempio n. 2
0
 public void PreProcessLoginPage(PageEntry page)
 {
     if (WebAuthentication.VerifyAccess(PermissionType.AccessAdminArea))
     {
         WebUtility.Redirect("admin");
     }
 }
Esempio n. 3
0
        Result AuthenticateForAjaxRequest(System.Reflection.MethodInfo source)
        {
            if (!SecurityProvider.CurrentUser.Enabled)
            {
                return(new Result("Ajax method called failed because your account has been disabled."));
            }

            Attribute[] roleAttr = Attribute.GetCustomAttributes(source, typeof(RequiresRoleAttribute));
            Attribute[] permAttr = Attribute.GetCustomAttributes(source, typeof(RequiresPermissionAttribute));
            for (int i = 0; i < roleAttr.Length; i++)
            {
                if (!SecurityProvider.CurrentUser.HasRole(((RequiresRoleAttribute)roleAttr[i]).RoleCode))
                {
                    return(new Result("Ajax method call failed because you do not have one or more required roles."));
                }
            }
            for (int i = 0; i < permAttr.Length; i++)
            {
                if (!WebAuthentication.VerifyAccess(((RequiresPermissionAttribute)permAttr[i]).PermissionTypeCode))
                {
                    return(new Result("Ajax method call failed because you do not have one or more required permissions."));
                }
            }
            return(new Result());
        }
Esempio n. 4
0
        void WebEvents_OnLoadRequestedPath(HandleFlag handled)
        {
            if (handled.Handled)
            {
                return;
            }
            if (!WebAuthentication.IsLoggedIn)
            {
                return;
            }
            if (!WebAuthentication.VerifyAccess(PermissionType.ModifyPages))
            {
                return;
            }

            if (SprocketPath.Sections.Length >= 4 && SprocketPath.Sections[0] == "admin")
            {
                switch (SprocketPath.Sections[1])
                {
                case "pages":
                    switch (SprocketPath.Sections[2])
                    {
                    case "delete":
                    {
                        long id;
                        if (long.TryParse(SprocketPath.Sections[3], out id))
                        {
                            Page page = ContentManager.Instance.DataProvider.SelectPage(id);
                            if (page != null)
                            {
                                Result r = page.SaveRevision("** Page deleted.", page.RevisionInformation.Draft, page.RevisionInformation.Hidden, true);
                                if (!r.Succeeded)
                                {
                                    Response.Write("Unable to delete page:<br/>" + r.Message);
                                    Response.End();
                                    return;
                                }
                            }
                        }
                    }
                        WebUtility.Redirect("admin/pages");
                        break;

                    case "imgthumb":
                    {
                        long id;
                        if (long.TryParse(SprocketPath.Sections[3], out id))
                        {
                            SizingOptions options = new SizingOptions(60, 45, SizingOptions.Display.Constrain, id);
                            FileManager.FileManager.Instance.TransmitImage(options);
                        }
                    }
                    break;
                    }
                    break;
                }
            }
        }
Esempio n. 5
0
 void AdminWindow_OnBeforeDisplayAdminWindowOverlay(Result result)
 {
     if (WebAuthentication.IsLoggedIn)
     {
         if (WebAuthentication.VerifyAccess(PermissionType.AdministrativeAccess))
         {
             return;
         }
     }
     result.SetFailed("access denied");
 }
Esempio n. 6
0
 void AdminHandler_OnLoadAdminPage(AdminInterface admin, PageEntry page, HandleFlag handled)
 {
     if (WebAuthentication.VerifyAccess(PermissionType.ModifyPages))
     {
         admin.AddMainMenuLink(new AdminMenuLink("Pages and Content", WebUtility.MakeFullPath("admin/pages"), ObjectRank.Normal, "pages_and_content"));
     }
     if (WebAuthentication.VerifyAccess(PermissionType.ModifyTemplates))
     {
         admin.AddMainMenuLink(new AdminMenuLink("Page Templates", WebUtility.MakeFullPath("admin/templates"), ObjectRank.Normal, "page_templates"));
     }
 }
Esempio n. 7
0
        public void ProcessLoginForm()
        {
            WebAuthentication auth = WebAuthentication.Instance;

            if (auth.ProcessLoginForm("SprocketUsername", "SprocketPassword", "SprocketPreserveLogin"))
            {
                if (WebAuthentication.VerifyAccess(PermissionType.AccessAdminArea))
                {
                    WebUtility.Redirect("admin");
                }
                else
                {
                    auth.ClearAuthenticationCookie();
                }
            }
            FormValues.Set("login", "", null, true);
        }
Esempio n. 8
0
        void WebEvents_OnRequestedPathProcessed()
        {
            if (!HttpContext.Current.Response.ContentType.Contains("html"))
            {
                return;
            }
            if (!IsAdminRequest)
            {
                return;
            }
            if (!WebAuthentication.VerifyAccess(PermissionType.AccessAdminArea))
            {
                return;
            }
            string html = WebUtility.CacheTextFile("resources/admin/header.htm");

            HttpContext.Current.Response.Write(string.Format(html, WebUtility.BasePath));
        }
Esempio n. 9
0
        void OnAdminRequest(AdminInterface admin, PageEntry page, HandleFlag handled)
        {
            // build the "current user" block
            User   user  = User.Select(SecurityProvider.ClientSpaceID, WebAuthentication.Instance.CurrentUsername);
            string block = "<div id=\"currentuser-block\">"
                           + "You are currently logged in as <b>{0}</b>."
                           + "</div>";

            admin.AddLeftColumnSection(new AdminSection(
                                           string.Format(block, (user.FirstName + " " + user.Surname).Trim()), ObjectRank.First));

            if (!WebAuthentication.VerifyAccess(PermissionType.UserAdministrator))
            {
                return;
            }

            admin.AddMainMenuLink(new AdminMenuLink("Users and Roles", WebUtility.MakeFullPath("admin/security"), ObjectRank.Normal));

            // build the security interface if it has been requested
            if (SprocketPath.Value.StartsWith("admin/security"))
            {
                //handled.Set();

                int defaultMaxFilterMatches;
                try { defaultMaxFilterMatches = int.Parse(SprocketSettings.GetValue("WebSecurityDefaultUserFilterMatches")); }
                catch { defaultMaxFilterMatches = 50; }

                admin.AddInterfaceScript(WebControlScript.TabStrip);
                admin.AddInterfaceScript(WebControlScript.Fader);
                admin.AddInterfaceScript(WebControlScript.AjaxForm);
                string scr = ResourceLoader.LoadTextResource("Sprocket.Security.CMS.security.js")
                             .Replace("50,//{defaultMaxFilterMatches}", defaultMaxFilterMatches.ToString() + ",")
                             .Replace("if(true)//{ifUserCanAccessRoleManagement}",
                                      WebAuthentication.VerifyAccess(PermissionType.RoleAdministrator) ? "" : "if(false)");
                admin.AddInterfaceScript(new AdminSection(scr, 0));
                admin.AddBodyOnLoadScript(new AdminSection("SecurityInterface.Run()", 0));

                string html = "<div id=\"user-admin-container\"></div>";

                admin.AddPreContentSection(new AdminSection(html, 0));
                admin.AddHeadSection(new AdminSection("<link rel=\"stylesheet\" type=\"text/css\" href=\""
                                                      + WebUtility.MakeFullPath("resources/admin/security.css") + "\" />", 0));
            }
        }
Esempio n. 10
0
        public object Evaluate(Token contextToken, List <ExpressionArgument> args, ExecutionState state)
        {
            if (args.Count != 1)
            {
                throw new InstructionExecutionException("\"haspermission\" expects exactly one argument specifying the name of a permission.", contextToken);
            }
            object o          = TokenParser.ReduceFromExpression(state, args[0].Token, args[0].Expression.Evaluate(state, args[0].Token));
            string permission = o == null ? null : o.ToString();

            if (permission == null)
            {
                throw new InstructionExecutionException("the argument didn't equate to a string naming a permission.", contextToken);
            }
            if (!WebAuthentication.IsLoggedIn)
            {
                return(false);
            }
            return(WebAuthentication.VerifyAccess(permission));
        }
        void OnSaveForm(AjaxFormSubmittedValues form)
        {
            List <string> roleCodes = new List <string>(), permissionTypeCodes = new List <string>();

            switch (form.FormName)
            {
            case "UserEditForm":
                if (!WebAuthentication.VerifyAccess(PermissionType.UserAdministrator))
                {
                    return;
                }
                AjaxFormSubmittedValues.Block block = form.Blocks["MainUserFields"];
                string pw      = block.Fields["Password"].Value;
                bool   enabled = block.Fields["Enabled"].Value == "True";
                if (pw.Length == 0)
                {
                    pw = null;
                }
                User user;

                if (form.RecordID == null)
                {
                    user = new User(
                        SecurityProvider.ClientSpaceID,
                        block.Fields["Username"].Value,
                        pw,
                        block.Fields["FirstName"].Value,
                        block.Fields["Surname"].Value,
                        block.Fields["Email"].Value,
                        enabled, false, false, 0);
                    Result result = SecurityProvider.DataLayer.Store(user);
                    if (!result.Succeeded)
                    {
                        throw new AjaxException(result.Message);
                    }
                    if (OnUserSaved != null)
                    {
                        OnUserSaved(form, user);
                    }

                    form.RecordID = user.UserID;
                }
                else
                {
                    user = User.Select(form.RecordID.Value);
                    //if (!CurrentUser.CanModifyUser(user))
                    //    throw new AjaxException("You don't have access to modify that user.");
                    user.Username = block.Fields["Username"].Value;
                    if (pw != null)
                    {
                        user.Password = pw;
                    }
                    user.FirstName = block.Fields["FirstName"].Value;
                    user.Surname   = block.Fields["Surname"].Value;
                    user.Email     = block.Fields["Email"].Value;
                    user.Enabled   = enabled;
                    SecurityProvider.DataLayer.Store(user);
                    //user.Save();
                    if (OnUserSaved != null)
                    {
                        OnUserSaved(form, user);
                    }

                    if (user.Locked)
                    {
                        return;                                          // don't muck with permissions/roles
                    }
                }

                if (user.Username != SecurityProvider.CurrentUser.Username)                         // users can't alter their own permissions
                {
                    if (form.Blocks.ContainsKey("Roles"))
                    {
                        foreach (KeyValuePair <string, AjaxFormSubmittedValues.Field> kvp in form.Blocks["Roles"].Fields)
                        {
                            if (SecurityProvider.CurrentUser.HasRole(kvp.Value.Name))                                     //make sure the logged in user has the right to assign this role
                            {
                                if (kvp.Value.Value == "True")
                                {
                                    roleCodes.Add(kvp.Value.Name);
                                }
                            }
                        }
                    }
                    //sql.AppendFormat("exec AssignUserToRole '{0}', '{1}'\r\n", user.UserID, kvp.Value.Name.Replace("'", "''"));
                    if (form.Blocks.ContainsKey("Permissions"))
                    {
                        foreach (KeyValuePair <string, AjaxFormSubmittedValues.Field> kvp in form.Blocks["Permissions"].Fields)
                        {
                            if (SecurityProvider.CurrentUser.HasRole(kvp.Value.Name))                                     //make sure the logged in user has the right to assign this role
                            {
                                if (kvp.Value.Value == "True")
                                {
                                    permissionTypeCodes.Add(kvp.Value.Name);
                                }
                            }
                        }
                    }
                    //sql.AppendFormat("exec AssignPermission '{0}', null, '{1}'\r\n", kvp.Value.Name.Replace("'", "''"), user.UserID);
                    //if (sql.Length == 0) return;

                    SecurityProvider.DataLayer.SetRolesAndPermissionsForUser(user.UserID, roleCodes, permissionTypeCodes);
                    //user.RevokeRolesAndPermissions(); // revoke any pre-existing permissions/roles before we assign the new ones
                    //Database.Main.CreateCommand(sql.ToString(), CommandType.Text).ExecuteNonQuery();
                }
                break;

            case "RoleEditForm":
                if (!WebAuthentication.VerifyAccess(PermissionType.RoleAdministrator))
                {
                    return;
                }
                block = form.Blocks["RoleDetails"];
                string name = block.Fields["Name"].Value;
                enabled = block.Fields["Enabled"].Value == "True";
                Role role;
                if (form.RecordID == null)
                {
                    role               = new Role();
                    role.RoleID        = DatabaseManager.GetUniqueID();
                    role.RoleCode      = role.RoleID.ToString();                        // role codes are only used by system roles
                    role.ClientSpaceID = SecurityProvider.ClientSpaceID;
                }
                else
                {
                    role = Role.Select(form.RecordID.Value);
                    if (role == null)
                    {
                        return;
                    }
                    if (role.Locked)
                    {
                        return;                                          // locked roles aren't supposed to be edited by users
                    }
                }
                role.Name    = name;
                role.Enabled = enabled;
                SecurityProvider.DataLayer.Store(role);
                //((SecurityProvider)Core.Instance["SecurityProvider"]).SaveRole(role);

                //sql = new StringBuilder();
                if (form.Blocks.ContainsKey("Roles"))
                {
                    foreach (KeyValuePair <string, AjaxFormSubmittedValues.Field> kvp in form.Blocks["Roles"].Fields)
                    {
                        if (SecurityProvider.CurrentUser.HasRole(kvp.Value.Name))                                 //make sure the logged in user has the right to assign this role
                        {
                            if (kvp.Value.Value == "True")
                            {
                                roleCodes.Add(kvp.Value.Name);
                            }
                        }
                    }
                }
                //sql.AppendFormat("exec InheritRoleFrom '{0}', '{1}'\r\n", role.RoleID, kvp.Value.Name.Replace("'", "''"));
                if (form.Blocks.ContainsKey("Permissions"))
                {
                    foreach (KeyValuePair <string, AjaxFormSubmittedValues.Field> kvp in form.Blocks["Permissions"].Fields)
                    {
                        if (SecurityProvider.CurrentUser.HasRole(kvp.Value.Name))                                 //make sure the logged in user has the right to assign this role
                        {
                            if (kvp.Value.Value == "True")
                            {
                                permissionTypeCodes.Add(kvp.Value.Name);
                            }
                        }
                    }
                }
                //sql.AppendFormat("exec AssignPermission '{0}', null, '{1}'\r\n", kvp.Value.Name.Replace("'", "''"), role.RoleID);

                SecurityProvider.DataLayer.SetRolesAndPermissionsForRole(role.RoleID, roleCodes, permissionTypeCodes);
                //role.RevokeRolesAndPermissions(); // revoke any pre-existing permissions/roles before we assign the new ones
                //if (sql.Length == 0) return;
                //Database.Main.CreateCommand(sql.ToString(), CommandType.Text).ExecuteNonQuery();
                break;
            }
        }
Esempio n. 12
0
        void WebEvents_OnLoadRequestedPath(HandleFlag handled)
        {
            if (handled.Handled)
            {
                return;
            }
            if (!IsAdminRequest)
            {
                return;
            }

            PageEntry page = pages.FromPath(SprocketPath.Value);

            if (page == null)
            {
                return;
            }

            KeyValuePair <string, object>[] vars;
            if (!SprocketPath.StartsWith("admin", "login"))
            {
                if (!WebAuthentication.VerifyAccess(PermissionType.AccessAdminArea))
                {
                    WebUtility.Redirect("admin/login");
                    return;
                }

                AdminInterface   admin   = new AdminInterface();
                WebClientScripts scripts = WebClientScripts.Instance;
                admin.AddMainMenuLink(new AdminMenuLink("Website Home", WebUtility.MakeFullPath(""), ObjectRank.Last, "website_home"));
                admin.AddMainMenuLink(new AdminMenuLink("Overview", WebUtility.MakeFullPath("admin"), ObjectRank.First, "website_overview"));
                admin.AddMainMenuLink(new AdminMenuLink("Log Out", WebUtility.MakeFullPath("admin/logout"), ObjectRank.Last, "log_out"));

                admin.AddFooterLink(new AdminMenuLink("Log Out", WebUtility.MakeFullPath("admin/logout"), ObjectRank.Early));
                admin.AddFooterLink(new AdminMenuLink("&copy; 2005-" + DateTime.UtcNow.Year + " " + SprocketSettings.GetValue("WebsiteName"), "", ObjectRank.Late));
                admin.AddFooterLink(new AdminMenuLink("Powered by Sprocket", "http://www.sprocketcms.com", ObjectRank.Last));
                admin.AddHeadSection(new AdminSection(scripts.BuildStandardScriptsBlock(), ObjectRank.Late));
                admin.WebsiteName = GetWebsiteName();

                if (OnLoadAdminPage != null)
                {
                    OnLoadAdminPage(admin, page, handled);
                    if (handled.Handled)
                    {
                        return;
                    }
                }

                vars = admin.GetScriptVariables();
            }
            else
            {
                vars    = new KeyValuePair <string, object> [1];
                vars[0] = new KeyValuePair <string, object>("_admin_websitename", GetWebsiteName());
            }

            ContentManager.RequestedPage = page;
            if (pagePreProcessors.ContainsKey(page.PageCode))
            {
                foreach (PagePreprocessorHandler method in pagePreProcessors[page.PageCode])
                {
                    method(page);
                }
            }
            string txt = page.Render(vars);

            Response.ContentType = page.ContentType;
            Response.Write(txt);
            handled.Set();
        }
Esempio n. 13
0
        void WebEvents_OnLoadRequestedPath(HandleFlag handled)
        {
            if (handled.Handled)
            {
                return;
            }
            switch (SprocketPath.Value)
            {
            case "activate/fix":
            {
                bool failed = false;
                if (!WebAuthentication.IsLoggedIn)
                {
                    failed = true;
                }
                else if (!WebAuthentication.VerifyAccess(PermissionType.AdministrativeAccess))
                {
                    failed = true;
                }
                if (failed)
                {
                    HttpContext.Current.Response.Write("<html><body><p>Access denied. Administrative access required.</p></body></html>");
                    handled.Set();
                    return;
                }
                else
                {
                    try
                    {
                        int k;
                        using (TransactionScope scope = new TransactionScope())
                        {
                            DatabaseManager.DatabaseEngine.GetConnection();
                            List <User> users = SecurityProvider.DataLayer.FilterUsers(null, null, null, null, null, null, false, out k);
                            foreach (User user in users)
                            {
                                SecurityProvider.RequestUserActivation(user.UserID, user.Email);
                            }
                            scope.Complete();
                        }
                        HttpContext.Current.Response.Write("<html><body><p>" + k + " activation requests created.</p></body></html>");
                        handled.Set();
                        return;
                    }
                    finally
                    {
                        DatabaseManager.DatabaseEngine.ReleaseConnection();
                    }
                }
            }

            default:
                switch (SprocketPath.Sections[0])
                {
                case "_captcha":
                    RenderCAPTCHAImage();
                    break;

                case "activate":
                    if (SprocketPath.Sections.Length == 2)
                    {
                        string activationCode = SprocketPath.Sections[1];
                        long   userID;
                        Result r = SecurityProvider.DataLayer.ActivateUser(activationCode, out userID);
                        if (r.Succeeded)
                        {
                            User user = null;
                            if (WebAuthentication.IsLoggedIn)
                            {
                                if (SecurityProvider.CurrentUser.UserID == userID)
                                {
                                    user           = SecurityProvider.CurrentUser;
                                    user.Activated = true;
                                }
                            }
                            if (user == null)
                            {
                                user = SecurityProvider.DataLayer.SelectUser(userID);
                            }

                            if (OnUserActivated != null)
                            {
                                OnUserActivated(user, handled);
                            }
                            if (!handled.Handled)
                            {
                                HttpContext.Current.Response.Write("<html><body><p>The user has been successfully activated.</p></body></html>");
                                handled.Set();
                            }
                        }
                        else
                        {
                            if (OnUserActivationError != null)
                            {
                                OnUserActivationError(r, handled);
                            }
                            if (!handled.Handled)
                            {
                                HttpContext.Current.Response.Write("<html><body><p>" + r.Message + "</p></body></html>");
                                handled.Set();
                            }
                        }
                    }
                    break;
                }
                break;
            }
        }