Ejemplo n.º 1
0
        private SmtpClient GetClient()
        {
            string mailserver = SprocketSettings.GetValue("MailServer");
            int    port;

            int.TryParse(SprocketSettings.GetValue("MailServerPort"), out port);
            string useAuthentication = SprocketSettings.GetValue("MailServerAuthentication");
            string authUsername      = SprocketSettings.GetValue("MailServerUsername");
            string authPassword      = SprocketSettings.GetValue("MailServerPassword");

            SmtpClient client = new SmtpClient();

            if (mailserver != null)
            {
                client.Host = mailserver;
            }
            else
            {
                client.Host = "localhost";
            }
            if (port > 0)
            {
                client.Port = port;
            }
            if (useAuthentication != null && authUsername != null && authPassword != null)
            {
                if (Utilities.MatchesAny(useAuthentication.ToLower(), "true", "yes", "1"))
                {
                    client.Credentials = new NetworkCredential(authUsername, authPassword);
                }
            }

            return(client);
        }
Ejemplo n.º 2
0
        void Settings_OnCheckingSettings(SprocketSettings.SettingsErrors errors)
        {
            if (!IntegrationEnabled)
            {
                return;
            }

            if (TestMode)
            {
                if (SprocketSettings.GetValue("PayPalTestIdentityToken") == null)
                {
                    errors.Add("PayPal", "PayPalTestMode setting has been specified, thus a value is required for PayPalTestIdentityToken. This is the PayPal-supplied identity token for use with the PayPal Sandbox development environment. See developer.paypal.com for more info.");
                    errors.SetCriticalError();
                }
                if (SprocketSettings.GetValue("PayPalTestAccountAddress") == null)
                {
                    errors.Add("PayPal", "PayPalTestMode setting has been specified, thus a value is required for PayPalTestAccountAddress. This is a test PayPal account address for use with the PayPal Sandbox development environment. See developer.paypal.com for more info.");
                    errors.SetCriticalError();
                }
            }
            else
            {
                if (SprocketSettings.GetValue("PayPalIdentityToken") == null)
                {
                    errors.Add("PayPal", "The PayPalTestMode setting is disabled and the PayPalIntegration setting is enabled, thus a value is required for PayPalIdentityToken. This is the PayPal-supplied identity token for authenticating PayPal responses. See developer.paypal.com for more info.");
                    errors.SetCriticalError();
                }
                if (SprocketSettings.GetValue("PayPalAccountAddress") == null)
                {
                    errors.Add("PayPal", "The PayPalTestMode setting is disabled and the PayPalIntegration setting is enabled, thus a value is required for PayPalAccountAddress. This is the PayPal account address that is to receive transaction payments. See developer.paypal.com for more info.");
                    errors.SetCriticalError();
                }
            }
        }
Ejemplo n.º 3
0
        public void LoadDefaultDatabase()
        {
            Database db = Database.Create(defaultEngine);

            db.ConnectionString = SprocketSettings.GetValue("ConnectionString");
            Database.Add("DEFAULT", db, true);
        }
Ejemplo n.º 4
0
 public void LoadConnectionString(string appSettingsKeyName)
 {
     if (SprocketSettings.GetValue(appSettingsKeyName) == null)
     {
         throw new SprocketException("The application settings file does not contain a connection string for the key \"" + appSettingsKeyName + "\".");
     }
     ConnectionString = SprocketSettings.GetValue(appSettingsKeyName);
 }
Ejemplo n.º 5
0
        private string PassKeyFromPasswordHash(string passwordHash)
        {
            string startIP = HttpContext.Current.Request.UserHostAddress;

            startIP = startIP.Substring(0, startIP.LastIndexOf('.'));
            string encKey = SprocketSettings.GetValue("EncryptionKeyWord");

            return(StringUtilities.HexStringFromBytes(Crypto.RC2Encrypt(passwordHash, encKey, startIP)));
        }
Ejemplo n.º 6
0
        internal static string DecryptCAPTCHAKey(string encryptedCaptcha)
        {
            string key    = SprocketSettings.GetValue("EncryptionKeyWord");
            string vector = HttpContext.Current.Request.UserHostAddress;

            vector = vector.Substring(0, vector.LastIndexOf('.'));

            return(Crypto.RC2Decrypt(StringUtilities.BytesFromHexString(encryptedCaptcha), key, vector));
        }
Ejemplo n.º 7
0
 void Instance_OnBeforeLoadExistingFile(HttpApplication app, string sprocketPath, string[] pathSections, HandleFlag handled)
 {
     if (sprocketPath.EndsWith(".js"))
     {
         if (SprocketSettings.GetBooleanValue("CompressJavaScript"))
         {
             HttpContext.Current.Response.Write(WebUtility.CacheTextFile(sprocketPath, true));
             handled.Set();
         }
     }
 }
Ejemplo n.º 8
0
        private string PasswordHashFromPassKey(string passKey)
        {
            string startIP = HttpContext.Current.Request.UserHostAddress;

            startIP = startIP.Substring(0, startIP.LastIndexOf('.'));
            string encKey = SprocketSettings.GetValue("EncryptionKeyWord");

            if (encKey == null)
            {
                throw new Exception("Please add a kay named \"EncryptionKeyWord\" to your Web.Config file. This is a secret keyword or phrase of your choice.");
            }
            return(Crypto.RC2Decrypt(StringUtilities.BytesFromHexString(passKey), encKey, startIP));
        }
Ejemplo n.º 9
0
        void OnAdminRequest(AdminInterface admin, string sprocketPath, string[] pathSections, HandleFlag handled)
        {
            // build the "current user" block
            WebAuthentication auth = (WebAuthentication)Core.Instance["WebAuthentication"];

            SecurityProvider.User user = SecurityProvider.User.Load(WebsiteClientID, auth.CurrentUsername);
            string block = "<div id=\"currentuser-block\">"
                           + "You are currently logged in as <b>{0}</b>."
                           + "</div>";

            admin.AddLeftColumnSection(new RankedString(
                                           string.Format(block, (user.FirstName + " " + user.Surname).Trim()), -100));

            admin.WebsiteName = WebsiteClient.Name;

            if (!CurrentUser.HasPermission(SecurityProvider.PermissionTypeCodes.UserAdministrator))
            {
                return;
            }

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

            // build the security interface if it has been requested
            if (sprocketPath.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.Web.CMS.Security.security.js")
                             .Replace("50,//{defaultMaxFilterMatches}", defaultMaxFilterMatches.ToString() + ",")
                             .Replace("if(true)//{ifUserCanAccessRoleManagement}",
                                      CurrentUser.HasPermission("ROLEADMINISTRATOR") ? "" : "if(false)");
                admin.AddInterfaceScript(new RankedString(scr, 0));
                admin.AddBodyOnLoadScript(new RankedString("SecurityInterface.Run()", 0));

                admin.ContentHeading = "Users and Roles";
                SecurityProvider security = (SecurityProvider)Core.Instance["SecurityProvider"];

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

                admin.AddContentSection(new RankedString(html, 0));
                admin.AddHeadSection(new RankedString("<link rel=\"stylesheet\" type=\"text/css\" href=\""
                                                      + WebUtility.MakeFullPath("resources/admin/security.css") + "\" />", 0));
            }
        }
Ejemplo n.º 10
0
        void OnCheckSettings(SprocketSettings.SettingsErrors errors)
        {
            if (SprocketSettings.GetValue("ConnectionString") == null)
            {
                errors.Add("DatabaseManager", "The application settings (.config) file requires a valid value for \"ConnectionString\".");
                errors.SetCriticalError();
            }
            if (SprocketSettings.GetValue("DatabaseEngine") == null)
            {
                errors.Add("DatabaseManager", "The application settings (.config) file requires a valid value for \"DatabaseEngine\".");
                errors.SetCriticalError();
            }
            if (errors.HasCriticalError)
            {
                return;
            }

            DatabaseEngine engType;

            try { engType = Database.ParseEngineName(SprocketSettings.GetValue("DatabaseEngine")); }
            catch (SprocketException)
            {
                errors.Add("DatabaseManager", "The value for \"DatabaseEngine\" is not valid.");
                errors.SetCriticalError();
                return;
            }

            Database db = Database.Create(engType);

            db.ConnectionString = SprocketSettings.GetValue("ConnectionString");
            string errorMessage;

            if (!db.TestConnectionString(out errorMessage))
            {
                string msg = errorMessage;
                //if (msg.ToLower().Contains("password")
                //    || msg.ToLower().Contains("pwd")
                //    || msg.ToLower().Contains("pass")
                //    || msg.ToLower().Contains("pword"))
                //    msg = "[error message hidden because it contains password information]";
                errors.Add("DatabaseManager", "The supplied connection string didn't work. The error was: " + msg);
                errors.SetCriticalError();
                return;
            }

            defaultConnectionString = db.ConnectionString;
            defaultEngine           = db.DatabaseEngine;
        }
Ejemplo n.º 11
0
        void OnCheckingSprocketSettings(SprocketSettings.SettingsErrors errors)
        {
            string psl = SprocketSettings.GetValue("PreventSimultaneousLogins");

            if (psl == null)
            {
                errors.Add(this, "The Web.config file is missing a value for \"PreventSimultaneousLogins\". The value should be \"True\" or \"False\".");
                errors.SetCriticalError();
                return;
            }
            if (psl.ToLower() != "true" && psl.ToLower() != "false")
            {
                errors.Add(this, "The Web.config file value for \"PreventSimultaneousLogins\" is invalid. The value should be \"True\" or \"False\".");
                errors.SetCriticalError();
                return;
            }
        }
Ejemplo n.º 12
0
        void Core_OnInitialise(Dictionary <Type, List <Type> > interfaceImplementations)
        {
            // need to check web.config to see which database registration name to use
            // instantiate that Type, if found, or throw an error
            // raise a notification event specifying the ISqlDatabase object we're using
            // add an event to this module OnCheckDatabaseStructure, which will eliminate the need for IDataHandlerModule
            if (interfaceImplementations.ContainsKey(typeof(IDatabaseHandler)))
            {
                string databaseEngine = SprocketSettings.GetValue("DatabaseEngine");
                if (databaseEngine == null)
                {
                    return;
                }

                foreach (Type t in interfaceImplementations[typeof(IDatabaseHandler)])
                {
                    if (t.Name == databaseEngine)
                    {
                        dbHandler = (IDatabaseHandler)Activator.CreateInstance(t);
                        Result result = dbHandler.CheckConfiguration();
                        if (!result.Succeeded)
                        {
                            SprocketSettings.Errors.Add(this, result.Message);
                            SprocketSettings.Errors.SetCriticalError();
                            return;
                        }
                        if (OnDatabaseHandlerLoaded != null)
                        {
                            OnDatabaseHandlerLoaded(dbHandler);
                        }
                        return;
                    }
                }

                List <string> list = new List <string>();
                foreach (Type t in interfaceImplementations[typeof(IDatabaseHandler)])
                {
                    list.Add(t.Name);
                }
                SprocketSettings.Errors.Add(this, "The application settings (.config) file requires a valid value for \"DatabaseEngine\".");
                SprocketSettings.Errors.Add(this, "Current valid values for DatabaseEngine are: " + StringUtilities.CommaJoin(list));
                SprocketSettings.Errors.SetCriticalError();
            }
        }
Ejemplo n.º 13
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));
            }
        }
Ejemplo n.º 14
0
        public static SprocketFile Upload(HttpPostedFile upload, Guid?clientID, Guid?ownerID,
                                          Guid?parentFileID, string sprocketPath, string categoryCode, string moduleRegCode,
                                          string description)
        {
            if (upload.ContentLength > int.Parse(SprocketSettings.GetValue("FileManagerMaxUploadSizeBytes")))
            {
                return(null);
            }

            SprocketFile file = new SprocketFile();

            file.sprocketFileID    = Guid.NewGuid();
            file.clientID          = clientID;
            file.ownerID           = ownerID;
            file.parentFileID      = parentFileID;
            file.sprocketPath      = (sprocketPath.Trim('/') + "/" + Path.GetFileName(upload.FileName)).Trim('/');
            file.categoryCode      = categoryCode;
            file.moduleRegCode     = moduleRegCode;
            file.description       = description;
            file.contentType       = upload.ContentType;
            file.uploadDate        = DateTime.Now;
            file.FileTypeExtension = Path.GetExtension(upload.FileName);
            upload.SaveAs(file.PhysicalPath);
            if (Database.Main.IsTransactionActive)
            {
                file.Save();
            }
            else
            {
                Database.Main.BeginTransaction();
                try
                {
                    file.Save();
                }
                catch (Exception ex)
                {
                    Database.Main.RollbackTransaction();
                    file.EnsureFileDeleted();
                    throw ex;
                }
                Database.Main.CommitTransaction();
            }
            return(file);
        }
Ejemplo n.º 15
0
 public Result CheckConfiguration()
 {
     connectionString = SprocketSettings.GetValue("ConnectionString");
     if (connectionString == null)
     {
         return(new Result("No value exists in Web.config for ConnectionString. SqlServer2005Database requires a valid connection string."));
     }
     try
     {
         SqlConnection conn = new SqlConnection(connectionString);
         conn.Open();
         conn.Close();
         conn.Dispose();
     }
     catch (Exception ex)
     {
         return(new Result("The ConnectionString value was unable to be used to open the database. The error was: " + ex.Message));
     }
     return(new Result());
 }
Ejemplo n.º 16
0
        public static string EncryptNewCAPTCHAKey()
        {
            Random r   = new Random();
            int    n1  = Convert.ToInt32('a');
            int    n2  = Convert.ToInt32('z') + 1;
            string str = "";

            while (str == "" || Instance.expiredCaptchaKeys.Contains(str))
            {
                str = "";
                while (str.Length < 6)
                {
                    str += Convert.ToChar(r.Next(n1, n2));
                }
            }
            string key    = SprocketSettings.GetValue("EncryptionKeyWord");
            string vector = HttpContext.Current.Request.UserHostAddress;

            vector = vector.Substring(0, vector.LastIndexOf('.'));
            return(StringUtilities.HexStringFromBytes(Crypto.RC2Encrypt(str.ToUpper(), key, vector)));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Writes all registered scripts into a single string surrounded by html script tags
        /// </summary>
        /// <returns>HTML script tags with containing javascript</returns>
        public string CreateScriptTags()
        {
            StringBuilder sb = new StringBuilder();

            foreach (KeyValuePair <string, string> script in scripts)
            {
                string js = script.Value;
                foreach (KeyValuePair <string, object> key in keys)
                {
                    js = js.Replace(key.Key, key.Value.ToString());
                }
                sb.Append("<script language=\"JavaScript\">");
                sb.Append(Environment.NewLine);
                if (SprocketSettings.GetBooleanValue("CompressJavaScript"))
                {
                    js = JavaScriptCondenser.Condense(js);
                }
                sb.Append(js);
                sb.Append(Environment.NewLine);
                sb.Append("</script>");
                sb.Append(Environment.NewLine);
            }
            return(sb.ToString());
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Sprocket calls this method in response to ASP.Net's AcquireRequestState event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        internal void FireAcquireRequestState(object sender, EventArgs e)
        {
            if (OnRequestStateLoaded != null)             // as always, let the other modules know where we are...
            {
                OnRequestStateLoaded();
            }

            if (HttpContext.Current.Request.Form != null)
            {
                if (HttpContext.Current.Request.Form.Count > 0)
                {
                    foreach (FormPostAction action in formPostActions)
                    {
                        if (action.PostFromPath != null)
                        {
                            if (action.PostFromPath != SprocketPath.ExtractSprocketPath(HttpContext.Current.Request.UrlReferrer.ToString()))
                            {
                                continue;
                            }
                        }

                        if (action.PostToPath != null)
                        {
                            if (action.PostToPath.ToLower() != SprocketPath.Value)
                            {
                                continue;
                            }
                        }

                        if (action.FieldName != null)
                        {
                            string s = HttpContext.Current.Request.Form[action.FieldName];
                            if (s == null)
                            {
                                continue;
                            }
                            if (action.FieldValue != null)
                            {
                                if (s != action.FieldValue)
                                {
                                    continue;
                                }
                            }
                        }

                        action.PostHandler();
                    }
                }
            }

            // this is our flag so that request event handlers can let us know if they handled this request.
            HandleFlag flag = new HandleFlag();

            if (OnLoadRequestedPath != null)
            {
                OnLoadRequestedPath(flag);
                if (flag.Handled)
                {
                    // stop the browser from caching the page
                    // HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

                    if (OnRequestedPathProcessed != null)
                    {
                        OnRequestedPathProcessed();
                    }

                    // if one of the modules handled the request event, then we can stop
                    // doing stuff now. The OnEndRequest event will still be called though.
                    HttpContext.Current.Response.End();
                    return;
                }
            }

            // if we've reached this point and none of our modules have volunteered to handle
            // the request, we can check to see if the requested path actually exists (gasp!)
            // and if so, serve up that file! This is handy if we insist on using the Standard
            // ASP.Net Page framework (yuck) or want to serve up other things like plain html
            // files.
            if (!flag.Handled && File.Exists(HttpContext.Current.Request.PhysicalPath))
            {
                // here we provide a last chance opportunity to alter the response before the
                // file is served.
                if (OnBeforeLoadExistingFile != null)
                {
                    OnBeforeLoadExistingFile(flag);
                    if (flag.Handled)
                    {
                        HttpContext.Current.Response.End();
                        return;
                    }
                }
                HttpContext.Current.RewritePath(HttpContext.Current.Request.Path);
                return;
            }

            // at this point we know that no file matching the exists, so we can check to see
            // if a directory of the specified name exists. If it does, we can see if there are
            // any default pages inside the folder that should execute. This requires the a key
            // to be configured for appSettings in the Web.config file:
            // <add key="DefaultPageFilenames" value="default.aspx,default.asp,default.htm,index.htm" />
            if (Directory.Exists(HttpContext.Current.Request.PhysicalPath))
            {
                string dpgstr = SprocketSettings.GetValue("DefaultPageFilenames");
                if (dpgstr != null)
                {
                    string[] pgarr = dpgstr.Split(',');
                    foreach (string pgname in pgarr)
                    {
                        string pgpath   = "/" + HttpContext.Current.Request.Path.Trim('/') + "/" + pgname;
                        string physpath = HttpContext.Current.Request.PhysicalPath + "\\" + pgname;
                        if (File.Exists(physpath))
                        {
                            HttpContext.Current.Response.Redirect(pgpath);
                            return;
                        }
                    }
                }
            }

            // if we've reached this point and still havent found anything that wants to handle
            // the current request, we offer up a final chance to respond to this fact...
            if (OnPathNotFound != null)
            {
                OnPathNotFound(flag);
                if (flag.Handled)
                {
                    if (OnRequestedPathProcessed != null)
                    {
                        OnRequestedPathProcessed();
                    }
                    HttpContext.Current.Response.End();
                    return;
                }
            }

            // if we got this far, sorry folks, but you're about to get a boring ASP.Net 404 page.
        }
Ejemplo n.º 19
0
 private static string _ppsetting(string suffix)
 {
     return(SprocketSettings.GetValue((TestMode ? "PayPalTest" : "PayPal") + suffix));
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Sprocket calls this method in response to ASP.Net's AcquireRequestState event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        internal void FireAcquireRequestState(object sender, EventArgs e)
        {
            if (OnRequestStateLoaded != null)             // as always, let the other modules know where we are...
            {
                OnRequestStateLoaded((HttpApplication)sender);
            }

            HttpContext pg = HttpContext.Current;

            // The SprocketPath refers to the bit after the application base path and before the
            // querystring, minus any leading and trailing forward-slashes. (/) For example if the
            // full URL is "http://www.sprocketcms.com/myapp/admin/users/?edit" and the subdirectory
            // "myapp" is a virtual directory (IIS application) then the SprocketPath would be
            // "admin/users".
            string sprocketPath = null;
            string appPath      = pg.Request.Path.ToLower();

            // check to see if there's a trailing slash and if there isn't, redirect to stick a trailing
            // slash onto the path. This is to keep pathing consistent because otherwise relative paths
            // (such as to images and css files) aren't pathed as expected. We DON'T do this if a form
            // has been posted however, because otherwise we lose the contents of the posted form. It is
            // assumed that if you forget to post to a path with a trailing slash, that once you finish
            // processing the form that you'll redirect off to a secondary page anyway, which means
            // sticking a slash on the end of this URL is unnecessary anyway.
            if (!appPath.EndsWith("/") && !appPath.Contains(".") && HttpContext.Current.Request.Form.Count == 0)
            {
                pg.Response.Redirect(appPath + "/");
                pg.Response.End();
                return;
            }

            // changes (e.g.) "http://www.sprocketcms.com/myapp/admin/users/?edit" into "admin/users"
            sprocketPath = appPath.Remove(0, pg.Request.ApplicationPath.Length).Trim('/');

            // split up the path sections to make things even easier for request event handlers
            string[] pathSections = sprocketPath.Split('/');

            // this is our flag so that request event handlers can let us know if they handled this request.
            HandleFlag flag = new HandleFlag();

            if (OnLoadRequestedPath != null)
            {
                OnLoadRequestedPath((HttpApplication)sender, sprocketPath, pathSections, flag);
                if (flag.Handled)
                {
                    // stop the browser from caching the page
                    // HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

                    // if one of the modules handled the request event, then we can stop
                    // doing stuff now. The OnEndRequest event will still be called though.
                    pg.Response.End();
                    return;
                }
            }

            // if we've reached this point and none of our modules have volunteered to handle
            // the request, we can check to see if the requested path actually exists (gasp!)
            // and if so, serve up that file! This is handy if we insist on using the Standard
            // ASP.Net Page framework (yuck) or want to serve up other things like plain html
            // files.
            if (!flag.Handled && File.Exists(pg.Request.PhysicalPath))
            {
                // here we provide a last chance opportunity to alter the response before the
                // file is served.
                if (OnBeforeLoadExistingFile != null)
                {
                    OnBeforeLoadExistingFile((HttpApplication)sender, sprocketPath, pathSections, flag);
                    if (flag.Handled)
                    {
                        pg.Response.End();
                        return;
                    }
                }
                HttpContext.Current.RewritePath(pg.Request.Path);
                return;
            }

            // at this point we know that no file matching the exists, so we can check to see
            // if a directory of the specified name exists. If it does, we can see if there are
            // any default pages inside the folder that should execute. This requires the a key
            // to be configured for appSettings in the Web.config file:
            // <add key="DefaultPageFilenames" value="default.aspx,default.asp,default.htm,index.htm" />
            if (Directory.Exists(pg.Request.PhysicalPath))
            {
                string dpgstr = SprocketSettings.GetValue("DefaultPageFilenames");
                if (dpgstr != null)
                {
                    string[] pgarr = dpgstr.Split(',');
                    foreach (string pgname in pgarr)
                    {
                        string pgpath   = "/" + pg.Request.Path.Trim('/') + "/" + pgname;
                        string physpath = pg.Request.PhysicalPath + "\\" + pgname;
                        if (File.Exists(physpath))
                        {
                            HttpContext.Current.Response.Redirect(pgpath);
                            return;
                        }
                    }
                }
            }

            // if we've reached this point and still havent found anything that wants to handle
            // the current request, we offer up a final chance to respond to this fact...
            if (OnPathNotFound != null)
            {
                OnPathNotFound((HttpApplication)sender, sprocketPath, pathSections, flag);
                if (flag.Handled)
                {
                    pg.Response.End();
                    return;
                }
            }

            // if we got this far, sorry folks, but you're about to get a boring ASP.Net 404 page.
        }
Ejemplo n.º 21
0
        void OnLoadRequestedPath(HttpApplication app, string path, string[] pathSections, HandleFlag handled)
        {
            if (pathSections.Length == 0)
            {
                return;
            }
            if (pathSections[0] != "admin")
            {
                return;
            }
            bool   processed = false;
            string lastchunk = pathSections[pathSections.Length - 1];

            switch (lastchunk)
            {
            case "admin.css":
                HttpContext.Current.Response.TransmitFile("~/resources/admin/admin.css");
                HttpContext.Current.Response.ContentType = "text/css";
                processed = true;
                break;

            default:
                WebAuthentication auth     = WebAuthentication.Instance;
                HttpResponse      Response = HttpContext.Current.Response;
                HttpServerUtility Server   = HttpContext.Current.Server;
                switch (path)
                {
                case "admin/login":
                    ShowLoginScreen();
                    processed = true;
                    break;

                case "admin/logout":
                    auth.ClearAuthenticationCookie();
                    Response.Redirect(WebUtility.MakeFullPath("admin/login"));
                    processed = true;
                    break;

                case "admin/login/process":
                    if (auth.ProcessLoginForm("SprocketUsername", "SprocketPassword", "SprocketPreserveLogin"))
                    {
                        Response.Redirect(WebUtility.MakeFullPath("admin"));
                    }
                    else
                    {
                        ShowLoginScreen("Invalid Username and/or Password.");
                    }
                    processed = true;
                    break;

                default:
                    if (!auth.IsLoggedIn)
                    {
                        GotoLoginScreen();
                        processed = true;
                    }
                    else if (OnCMSAdminAuthenticationSuccess != null)
                    {
                        Result result = new Result();
                        OnCMSAdminAuthenticationSuccess(auth.CurrentUsername, result);
                        if (!result.Succeeded)
                        {
                            ShowLoginScreen(result.Message);
                            processed = true;
                        }
                    }
                    break;
                }
                break;
            }
            if (processed)
            {
                handled.Set();
                return;
            }

            if (OnAdminRequest != null)
            {
                AdminInterface admin = new AdminInterface();
                OnAdminRequest(admin, path, pathSections, handled);
                if (handled.Handled)
                {
                    WebClientScripts scripts = WebClientScripts.Instance;
                    admin.AddMainMenuLink(new AdminMenuLink("Current Overview", WebUtility.MakeFullPath("admin"), -100));
                    admin.AddMainMenuLink(new AdminMenuLink("Log Out", WebUtility.MakeFullPath("admin/logout"), 100));
                    admin.AddFooterLink(new AdminMenuLink("&copy; 2005-" + DateTime.Now.Year + " " + SprocketSettings.GetValue("WebsiteName"), "", 100));
                    string powered = SprocketSettings.GetValue("ShowPoweredBySprocket");
                    if (powered != null)
                    {
                        if (StringUtilities.MatchesAny(powered.ToLower(), "true", "yes"))
                        {
                            admin.AddFooterLink(new AdminMenuLink("Powered by Sprocket", "http://www.sprocketcms.com", 1000));
                        }
                    }
                    admin.AddHeadSection(new RankedString(scripts.BuildStandardScriptsBlock(), 1));
                    HttpContext.Current.Response.Write(admin.Render(path));
                }
            }
        }
Ejemplo n.º 22
0
 void OnCheckingSprocketSettings(SprocketSettings.SettingsErrors errors)
 {
     string psl = SprocketSettings.GetValue("PreventSimultaneousLogins");
     if (psl == null)
     {
         errors.Add(RegistrationCode, "The Web.config file is missing a value for \"PreventSimultaneousLogins\". The value should be \"True\" or \"False\".");
         errors.SetCriticalError();
         return;
     }
     if (psl.ToLower() != "true" && psl.ToLower() != "false")
     {
         errors.Add(RegistrationCode, "The Web.config file value for \"PreventSimultaneousLogins\" is invalid. The value should be \"True\" or \"False\".");
         errors.SetCriticalError();
         return;
     }
 }
Ejemplo n.º 23
0
        /// <summary>
        /// This method is called in response to any request where the URL ends with a .ajax
        /// extension, which Sprocket uses to designate an Ajax request from an XmlHttpRequest
        /// call in the browser. The posted data contains information that this method uses to
        /// find the correct ISprocketModule implementation. It then uses reflection to get
        /// the requested method from the module, converts the javascript arguments into native
        /// CLR types and passes them to the method, after which it takes the returned data and
        /// writes it to the output stream ready for the XmlHttpRequest object to complete its
        /// call. Note that data transport uses JSON encoding. See the JSON class in the
        /// Sprocket.System namespace for information.
        /// </summary>
        /// <param name="context">The current HttpContext object.</param>
        internal void ProcessRequest(HttpContext context)
        {
            isAjaxRequest = true;
            System.Diagnostics.Debug.WriteLine("Start of AJAX page request...");
            Dictionary <string, object> responseData = new Dictionary <string, object>();

            try
            {
                // load the post data from the http stream
                byte[] posted = new byte[context.Request.InputStream.Length];
                context.Request.InputStream.Read(posted, 0, posted.Length);

                // interpret the stream as a JSON string and parse it into a dictionary
                string strData = System.Text.Encoding.ASCII.GetString(posted);
                IDictionary <string, object> data = (IDictionary <string, object>)JSON.Parse(strData);

                // extract the base page time stamp
                //pageTimeStamp = new DateTime(long.Parse(data["LoadTimeStamp"].ToString()));
                //System.Diagnostics.Debug.WriteLine("Extracted page time stamp of " + pageTimeStamp.Ticks.ToString());
                //if (OnAjaxRequestTimeStampCheck != null)
                //{
                //    Result result = new Result();
                //    OnAjaxRequestTimeStampCheck(pageTimeStamp, result);
                //    if (!result.Succeeded)
                //        throw new AjaxSessionExpiredException(result.Message);
                //}

                // extract the module and method name
                string fullname;
                try
                {
                    fullname = data["ModuleName"].ToString();
                }
                catch (Exception ex)
                {
                    throw;
                }
                int n = fullname.LastIndexOf(".");
                if (n == -1)
                {
                    throw new AjaxException("Method name specified incorrectly. Expected format ModuleNamespace.MethodName.\nThe following incorrect format was supplied: " + data["ModuleName"]);
                }
                string moduleNamespace = fullname.Substring(0, n);
                string methodName      = fullname.Substring(n + 1, fullname.Length - (n + 1));

                // extract the authentication key
                if (data["AuthKey"].ToString() != WebAuthentication.AuthKeyPlaceholder)
                {
                    authKey = new Guid(data["AuthKey"].ToString());
                }

                // extract the source URL
                SprocketPath.Parse(data["SourceURL"].ToString());

                // extract the arguments
                List <object> parsedArguments = (List <object>)data["MethodArgs"];

                // find and verify the module/method that should handle this request
                ISprocketModule module = Core.Instance[moduleNamespace].Module;
                if (module == null)
                {
                    throw new AjaxException("The specified module \"" + moduleNamespace + "\" was not found.");
                }
                if (Attribute.GetCustomAttribute(module.GetType(), typeof(AjaxMethodHandlerAttribute), false) == null)
                {
                    throw new SprocketException("The specified module is not marked with AjaxMethodHandlerAttribute. (" + data["ModuleName"] + ")");
                }
                MethodInfo info = module.GetType().GetMethod(methodName);
                if (info == null)
                {
                    throw new AjaxException("Failed to find an instance of the specified method. (" + data["ModuleName"] + ")");
                }
                Attribute ajaxMethodAttr = Attribute.GetCustomAttribute(info, typeof(AjaxMethodAttribute));
                if (ajaxMethodAttr == null)
                {
                    throw new AjaxException("Specified method is not marked with AjaxMethodAttribute. (" + data["ModuleName"] + ")");
                }
                AjaxMethodAttribute attr = (AjaxMethodAttribute)ajaxMethodAttr;
                if (attr.RequiresAuthentication)
                {
                    if (!WebAuthentication.IsLoggedIn)
                    {
                        AjaxRequestHandler.AbortAjaxCall("You're not currently logged in. Please refresh the page.");
                    }

                    if (AjaxAuthenticate != null)
                    {
                        Result result = AjaxAuthenticate(info);
                        if (!result.Succeeded)
                        {
                            throw new AjaxException(result.Message);
                        }
                    }
                }

                // get all of the parameters that the method requires
                ParameterInfo[] methodParamInfos = info.GetParameters();

                // funcinfo is a string representation of the method format and is used for displaying meaningful errors
                string funcinfo = data["ModuleName"] + "(";
                if (methodParamInfos.Length > 0)
                {
                    funcinfo += methodParamInfos[0].ParameterType.Name + " " + methodParamInfos[0].Name;
                }
                for (int j = 1; j < methodParamInfos.Length; j++)
                {
                    funcinfo += ", " + methodParamInfos[j].ParameterType.Name + " " + methodParamInfos[j].Name;
                }
                funcinfo += ")";
                if (methodParamInfos.Length != parsedArguments.Count)
                {
                    throw new AjaxException("Method expects " + methodParamInfos.Length + " argument(s) but instead received " + (parsedArguments.Count) + ". Expected format is:\n" + funcinfo);
                }

                // create the parameter array and convert each supplied value to its native type
                object[] prmValuesForMethod = new object[methodParamInfos.Length];
                for (int i = 0; i < prmValuesForMethod.Length; i++)
                {
                    Type t = methodParamInfos[i].ParameterType;
                    try
                    {
                        if (parsedArguments[i] == null)
                        {
                            prmValuesForMethod[i] = null;
                        }
                        else if (t.Name == "Object")
                        {
                            prmValuesForMethod[i] = parsedArguments[i];
                        }
                        else if (t.Name == "DateTime")
                        {
                            prmValuesForMethod[i] = DateTime.Parse(parsedArguments[i].ToString());
                        }
                        else if (t.IsArray || t.IsSubclassOf(typeof(IList)))
                        {
                            int    elementCount = ((List <object>)parsedArguments[i]).Count;
                            Type   arrType      = t.GetElementType().MakeArrayType(elementCount);
                            object arr          = Array.CreateInstance(t.GetElementType(), ((List <object>)parsedArguments[i]).Count);
                            for (int k = 0; k < ((IList <object>)parsedArguments[i]).Count; k++)
                            {
                                ((IList)arr)[k] = ((IList <object>)parsedArguments[i])[k];
                            }
                            prmValuesForMethod[i] = arr;
                        }
                        else if (t.GetInterface("IJSONReader") != null)
                        {
                            object obj = Activator.CreateInstance(t);
                            ((IJSONReader)obj).LoadJSON(parsedArguments[i]);
                            prmValuesForMethod[i] = obj;
                        }
                        else if (t.IsAssignableFrom(typeof(Guid)) || t.IsAssignableFrom(typeof(Guid?)))
                        {
                            prmValuesForMethod[i] = parsedArguments[i] == null ? (Guid?)null : new Guid(parsedArguments[i].ToString());
                        }
                        else if (t.IsAssignableFrom(typeof(long)) || t.IsAssignableFrom(typeof(long?)))
                        {
                            prmValuesForMethod[i] = parsedArguments[i] == null ? (long?)null : long.Parse(parsedArguments[i].ToString());
                        }
                        else
                        {
                            prmValuesForMethod[i] = Convert.ChangeType(parsedArguments[i], t);
                        }
                    }
                    catch (Exception ex)
                    {
                        string err = "Error converting parameter {0} to type {1}. Expected format is:\n{2}\nReceived Value:\n{3}\nException message:\n{4}";
                        throw new AjaxException(string.Format(err, i, methodParamInfos[i].ParameterType.Name, funcinfo, parsedArguments[i], ex));
                    }
                }

                // invoke the method
                if (info.ReturnType == typeof(void))
                {
                    info.Invoke(module, prmValuesForMethod);
                }
                else
                {
                    object returnVal = info.Invoke(module, prmValuesForMethod);
                    responseData["Data"] = returnVal;
                }
                //context.Response.Write(JSON.Encode(responseData));
            }
            catch (Exception e)
            {
                if (!(e is AjaxUserMessageException) && SprocketSettings.GetBooleanValue("CatchExceptions"))
                {
                    if (e.InnerException != null)
                    {
                        throw e.InnerException;
                    }
                    throw e;
                }
                else if (e.InnerException != null)
                {
                    e = e.InnerException;
                }
                responseData["__error"]         = e;
                responseData["__exceptionType"] = e.GetType().FullName;
            }
            if (!responseData.ContainsKey("Data"))
            {
                responseData["Data"] = null;
            }
            //responseData["__timeStamp"] = pageTimeStamp.Ticks;
            context.Response.Write(JSON.Encode(responseData));
        }
Ejemplo n.º 24
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();
        }