Пример #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string domain = Request.QueryString["domain"];
            string path = Request.QueryString["path"];
            string urlreferer = Request.QueryString["urlreferer"];
            //string sessionId = Request.QueryString["sid"];

            try
            {
                DnsRecord record = new DnsRecord(core, domain);

                /*if (!string.IsNullOrEmpty(sessionId))
                {
                    core.session.SessionEnd(sessionId, 0, record);
                }*/

                Uri referer = null;
                if (!string.IsNullOrEmpty(urlreferer))
                {
                    referer = new Uri(urlreferer);
                }

                string sessionId = core.Session.SessionBegin(core.LoggedInMemberId, false, false, false, record, referer);

                Response.Redirect(core.Hyperlink.AppendSid("http://" + record.Domain + "/" + path, true));
            }
            catch (InvalidDnsRecordException)
            {
                core.Display.ShowMessage("Error", "Error starting remote session");
            }
        }
Пример #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string redirect = (Request.Form["redirect"] != null) ? Request.Form["redirect"] : Request.QueryString["redirect"];
            string domain = (Request.Form["domain"] != null) ? Request.Form["domain"] : Request.QueryString["domain"];
            DnsRecord record = null;

            template.Parse("IS_CONTENT", "FALSE");
            template.Parse("S_POST", core.Hyperlink.AppendSid("/sign-in/", true));

            if (!string.IsNullOrEmpty(domain))
            {
                try
                {
                    if (domain != Hyperlink.Domain)
                    {
                        record = new DnsRecord(core, domain);
                    }
                    if (core.Http["mode"] == "sign-out")
                    {
                        if (record != null)
                        {
                            session.SessionEnd(Request.QueryString["sid"], loggedInMember.UserId, record);
                        }
                        else
                        {
                            session.SessionEnd(Request.QueryString["sid"], loggedInMember.UserId);
                        }

                        if (!string.IsNullOrEmpty(redirect))
                        {
                            Response.Redirect(core.Hyperlink.AppendSid("http://" + record.Domain + "/" + redirect.TrimStart(new char[] { '/' }), true));
                        }
                        else
                        {
                            Response.Redirect(core.Hyperlink.AppendSid("http://" + record.Domain + "/", true));
                        }
                    }
                    else if (core.LoggedInMemberId > 0)
                    {
                        string sessionId = Request.QueryString["sid"];

                        if (!string.IsNullOrEmpty(sessionId))
                        {
                            core.Session.SessionEnd(sessionId, 0, record);
                        }

                        sessionId = core.Session.SessionBegin(core.LoggedInMemberId, false, false, false, record, null);

                        Response.Redirect(core.Hyperlink.AppendSid("http://" + record.Domain + "/" + redirect.TrimStart(new char[] { '/' }), true));
                    }
                }
                catch (InvalidDnsRecordException)
                {
                    core.Display.ShowMessage("Error", "Error starting remote session");
                    return;
                }
            }

            if (core.Http["mode"] == "sign-out")
            {
                string sessionId = Request.QueryString["sid"];

                if (!string.IsNullOrEmpty(sessionId))
                {
                    core.Session.SessionEnd(sessionId, loggedInMember.UserId);
                }

                if (!string.IsNullOrEmpty(redirect))
                {
                    Response.Redirect(redirect, true);
                }
                else
                {
                    Response.Redirect("/", true);
                }
                return;
            }
            if (Request.Form["submit"] != null)
            {
                if (core.Http["mode"] == "reset-password")
                {
                    string email = Request.Form["email"];

                    if (string.IsNullOrEmpty(email))
                    {
                        core.Display.ShowMessage("Error", "An error occured");
                        return;
                    }
                    else
                    {
                        try
                        {
                            UserEmail userEmail = new UserEmail(core, email);

                            if (userEmail.IsActivated)
                            {
                                string newPassword = BoxSocial.Internals.User.GenerateRandomPassword();
                                string activateCode = BoxSocial.Internals.User.GenerateActivationSecurityToken();

                                db.UpdateQuery(string.Format("UPDATE user_info SET user_new_password = '******', user_activate_code = '{1}' WHERE user_id = {2}",
                                    Mysql.Escape(newPassword), Mysql.Escape(activateCode), userEmail.Owner.Id));

                                string activateUri = string.Format(core.Hyperlink.Uri + "register/?mode=activate-password&id={0}&key={1}",
                                    userEmail.Owner.Id, activateCode);

                                // send the e-mail

                                Template emailTemplate = new Template(core.Http.TemplateEmailPath, "new_password.html");

                                emailTemplate.Parse("SITE_TITLE", core.Settings.SiteTitle);
                                emailTemplate.Parse("U_SITE", core.Hyperlink.StripSid(core.Hyperlink.AppendAbsoluteSid(core.Hyperlink.BuildHomeUri())));
                                emailTemplate.Parse("TO_NAME", userEmail.Owner.DisplayName);
                                emailTemplate.Parse("U_ACTIVATE", activateUri);
                                emailTemplate.Parse("USERNAME", userEmail.Owner.UserName);
                                // TODO: do not send a new password in plain text
                                emailTemplate.Parse("PASSWORD", newPassword);

                                core.Email.SendEmail(userEmail.Email, core.Settings.SiteTitle + " Password Reset", emailTemplate);

                                core.Display.ShowMessage("Password reset", "You have been sent an e-mail to the address you entered with your new password. You will need to click the confirmation link before you can sign in");
                                return;
                            }
                            else
                            {
                                core.Display.ShowMessage("E-mail not verified", "The e-mail you have entered has not been verified, you need to enter an e-mail address you have verified to reset your password.");
                                return;
                            }
                        }
                        catch (InvalidUserEmailException)
                        {
                            core.Display.ShowMessage("No e-mail registered", "The e-mail you have entered is not associated with a user account.");
                            return;
                        }
                    }
                }
                else if (core.Http.Form["mode"] == "verify")
                {
                    Authenticator authenticator = new Authenticator();
                    if (authenticator.CheckCode(core.Session.CandidateMember.UserInfo.TwoFactorAuthKey, core.Http.Form["verify"]))
                    {
                        if (Request.Form["remember"] == "true")
                        {
                            session.SessionBegin(core.Session.CandidateMember.UserId, false, true, true);
                        }
                        else
                        {
                            session.SessionBegin(core.Session.CandidateMember.UserId, false, false, true);
                        }
                        if ((!string.IsNullOrEmpty(domain)) && (record != null))
                        {
                            string sessionId = core.Session.SessionBegin(core.Session.CandidateMember.UserId, false, false, true, record, null);

                            core.Hyperlink.Sid = sessionId;
                            if (!string.IsNullOrEmpty(redirect))
                            {
                                Response.Redirect(core.Hyperlink.AppendSid("http://" + record.Domain + "/" + redirect.TrimStart(new char[] { '/' }), true));
                            }
                            else
                            {
                                Response.Redirect(core.Hyperlink.AppendSid("http://" + record.Domain + "/", true));
                            }
                            return;
                        }
                        if (!string.IsNullOrEmpty(redirect))
                        {
                            if (redirect.StartsWith("/account", StringComparison.Ordinal))
                            {
                                redirect = core.Hyperlink.AppendSid(core.Hyperlink.StripSid(redirect), true);
                            }
                            else
                            {
                                redirect = core.Hyperlink.AppendSid(redirect);
                            }
                            Response.Redirect(redirect, true);
                        }
                        else
                        {
                            Response.Redirect(core.Hyperlink.AppendSid("/"), true);
                        }
                        return; /* stop processing the display of this page */
                    }
                    else
                    {
                        core.Session.SessionEnd(core.Session.SessionId, core.Session.CandidateMember.UserId);

                        template.Parse("ERROR", "Bad log in credentials were given, you could not be logged in. Try again.");
                    }
                }
                else
                {
                    string userName = Request.Form["username"];
                    string password = BoxSocial.Internals.User.HashPassword(Request.Form["password"]);

                    DataTable userTable = db.Query(string.Format("SELECT uk.user_name, uk.user_id, ui.user_password, ui.user_two_factor_auth_key, ui.user_two_factor_auth_verified FROM user_keys uk INNER JOIN user_info ui ON uk.user_id = ui.user_id WHERE uk.user_name = '{0}';",
                       userName));

                    if (userTable.Rows.Count == 1)
                    {
                        DataRow userRow = userTable.Rows[0];
                        bool authenticated = false;
                        string dbPassword = (string)userRow["user_password"];

                        // old phpBB passwords
                        if (dbPassword.Length == 32)
                        {
                            // phpBB2 passwords
                            if (SessionState.SessionMd5(Request.Form["password"]) == dbPassword.ToLower())
                            {
                                authenticated = true;
                            }
                        }
                        else if (dbPassword.Length == 34)
                        {
                            // phpBB3 passwords
                            string itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

                            if (SessionState.phpBB3Hash(Request.Form["password"], dbPassword, ref itoa64) == dbPassword)
                            {
                                authenticated = true;
                            }
                        }
                        else
                        {
                            if (dbPassword == password)
                            {
                                authenticated = true;
                            }
                        }

                        if (authenticated)
                        {
                            if ((byte)userRow["user_two_factor_auth_verified"] > 0)
                            {
                                template.SetTemplate("login_two_factor_verify.html");

                                HiddenField rememberHiddenField = new HiddenField("remember");
                                rememberHiddenField.Value = core.Http.Form["remember"];

                                TextBox verifyTextBox = new Forms.TextBox("verify");

                                template.Parse("S_REMEMBER", rememberHiddenField);
                                template.Parse("S_VERIFY", verifyTextBox);

                                if (Request.Form["remember"] == "true")
                                {
                                    session.SessionBegin((long)userRow["user_id"], false, true, false);
                                }
                                else
                                {
                                    session.SessionBegin((long)userRow["user_id"], false, false, false);
                                }
                            }
                            else
                            {

                                if (Request.Form["remember"] == "true")
                                {
                                    session.SessionBegin((long)userRow["user_id"], false, true);
                                }
                                else
                                {
                                    session.SessionBegin((long)userRow["user_id"], false, false);
                                }
                                if ((!string.IsNullOrEmpty(domain)) && (record != null))
                                {
                                    string sessionId = core.Session.SessionBegin((long)userRow["user_id"], false, false, false, record, null);

                                    core.Hyperlink.Sid = sessionId;
                                    if (!string.IsNullOrEmpty(redirect))
                                    {
                                        Response.Redirect(core.Hyperlink.AppendSid("http://" + record.Domain + "/" + redirect.TrimStart(new char[] { '/' }), true));
                                    }
                                    else
                                    {
                                        Response.Redirect(core.Hyperlink.AppendSid("http://" + record.Domain + "/", true));
                                    }
                                    return;
                                }
                                if (!string.IsNullOrEmpty(redirect))
                                {
                                    if (redirect.StartsWith("/account", StringComparison.Ordinal))
                                    {
                                        redirect = core.Hyperlink.AppendSid(core.Hyperlink.StripSid(redirect), true);
                                    }
                                    else
                                    {
                                        redirect = core.Hyperlink.AppendSid(redirect);
                                    }
                                    Response.Redirect(redirect, true);
                                }
                                else
                                {
                                    Response.Redirect(core.Hyperlink.AppendSid("/"), true);
                                }
                                return; /* stop processing the display of this page */
                            }
                        }
                        else
                        {
                            template.Parse("ERROR", "Bad log in credentials were given, you could not be logged in. Try again.");
                        }

                    }
                    else
                    {
                        template.Parse("ERROR", "Bad log in credentials were given, you could not be logged in. Try again.");
                    }
                }
            }

            if (core.Http["mode"] == "reset-password")
            {
                template.Parse("S_POST", core.Hyperlink.AppendSid("/sign-in/?mode=reset-password", true));

                template.SetTemplate("password_reset.html");

                EndResponse();
                return;
            }
            else
            {
                template.Parse("U_FORGOT_PASSWORD", core.Hyperlink.AppendSid("/sign-in/?mode=reset-password"));
            }

            template.Parse("DOMAIN", domain);
            template.Parse("REDIRECT", redirect);

            EndResponse();
        }
Пример #3
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="member"></param>
        /// <param name="autoCreate"></param>
        /// <param name="enableAutologin"></param>
        /// <param name="admin"></param>
        public string SessionBegin(long userId, bool autoCreate, bool enableAutologin, bool twoFactor, DnsRecord record, Uri urlreferer)
        {
            string cookieName = "hailToTheChef";
            /*XmlSerializer xs;
            StringWriter stw;*/

            string protocol = "http://";
            if (core.Settings.UseSecureCookies)
            {
                protocol = "https://";
            }

            string rootSessionId = string.Empty;
            if (record != null)
            {
                rootSessionId = core.Session.SessionId;
            }

            sessionData = null;
            sessionId = null;
            string currentDomain = core.Hyperlink.CurrentDomain;
            if (record != null)
            {
                currentDomain = record.Domain;
            }

            if (!String.IsNullOrEmpty(IsBotUserAgent(Request.UserAgent)))
            {
                signInState = SessionSignInState.Bot;
                core.Hyperlink.SidUrls = false;
                return sessionId;
            }

            if (record == null)
            {
                if (Request.Cookies[cookieName + "_sid"] != null || Request.Cookies[cookieName + "_data"] != null)
                {
                    if (Request.Cookies[cookieName + "_sid"] != null)
                    {
                        sessionId = Request.Cookies[cookieName + "_sid"].Value;
                    }

                    if (Request.Cookies[cookieName + "_data"] != null)
                    {
                        /*xs = new XmlSerializer(typeof(SessionCookie));
                        StringReader sr = new StringReader(HttpUtility.UrlDecode(Request.Cookies[cookieName + "_data"].Value));*/

                        try
                        {
                            sessionData = new SessionCookie(HttpUtility.UrlDecode(Request.Cookies[cookieName + "_data"].Value)); //(SessionCookie)xs.Deserialize(sr);
                        }
                        catch
                        {
                            sessionData = new SessionCookie();
                        }
                    }
                    else
                    {
                        sessionData = new SessionCookie();
                    }

                    if (string.IsNullOrEmpty(sessionId))
                    {
                        sessionId = (string)Request.QueryString["sid"];
                    }

                    sessionMethod = SessionMethods.Cookie;
                }
                else
                {
                    sessionData = new SessionCookie();
                    if (Request.QueryString["sid"] != null)
                    {
                        sessionId = (string)Request.QueryString["sid"];
                    }
                    sessionMethod = SessionMethods.Get;
                }
            }
            else
            {
                sessionData = new SessionCookie();
            }

            if (!string.IsNullOrEmpty(sessionId))
            {
                if (!IsValidSid(sessionId))
                {
                    sessionId = "";
                }
            }

            if (record != null)
            {
                sessionMethod = SessionMethods.Get;
            }

            //
            // First off attempt to join with the autologin value if we have one
            // If not, just use the user_id value
            //

            loggedInMember = null;

            if (userId != 0)
            {
                //if (isset($sessiondata['autologinid']) && (string) $sessiondata['autologinid'] != '' && $user_id)
                if (!string.IsNullOrEmpty(sessionData.autoLoginId) && userId > 0)
                {
                    SelectQuery query = User.GetSelectQueryStub(core, UserLoadOptions.Info);
                    query.AddJoin(JoinTypes.Inner, "session_keys", "user_id", "user_id");
                    query.AddCondition("user_keys.user_id", userId);
                    query.AddCondition("user_active", true);
                    query.AddCondition("key_id", SessionState.SessionMd5(sessionData.autoLoginId));

                    System.Data.Common.DbDataReader userReader = db.ReaderQuery(query);

                    if (userReader.HasRows)
                    {
                        userReader.Read();

                        loggedInMember = new User(core, userReader, UserLoadOptions.Info);

                        userReader.Close();
                        userReader.Dispose();

                        enableAutologin = isLoggedIn = true;
                        if (loggedInMember.UserInfo.TwoFactorAuthVerified && twoFactor)
                        {
                            signInState = SessionSignInState.TwoFactorValidated;
                        }
                        else
                        {
                            signInState = SessionSignInState.SignedIn;
                        }
                    }
                    else
                    {
                        userReader.Close();
                        userReader.Dispose();

                        core.Template.Parse("REDIRECT_URI", "/");

                        if (record == null)
                        {
                            Response.Cookies.Clear();

                            HttpCookie sessionDataCookie = new HttpCookie(cookieName + "_data");
                            //sessionDataCookie.Domain = core.Hyperlink.CurrentDomain;
                            sessionDataCookie.Path = "/";
                            sessionDataCookie.Value = "";
                            sessionDataCookie.Expires = DateTime.MinValue;
                            sessionDataCookie.Secure = core.Settings.UseSecureCookies && core.Hyperlink.CurrentDomain == Hyperlink.Domain;
                            sessionDataCookie.HttpOnly = true;
                            Response.Cookies.Add(sessionDataCookie);

                            HttpCookie sessionSidCookie = new HttpCookie(cookieName + "_sid");
                            //sessionSidCookie.Domain = core.Hyperlink.CurrentDomain;
                            sessionSidCookie.Path = "/";
                            sessionSidCookie.Value = "";
                            sessionSidCookie.Expires = DateTime.MinValue;
                            sessionDataCookie.Secure = core.Settings.UseSecureCookies && core.Hyperlink.CurrentDomain == Hyperlink.Domain;
                            sessionSidCookie.HttpOnly = true;
                            Response.Cookies.Add(sessionSidCookie);

                            if (Request.Cookies[cookieName + "_sid"] == null && signInState != SessionSignInState.Bot)
                            {
                                core.Hyperlink.SidUrls = true;
                            }
                        }

                        //core.Display.ShowMessage("Error", "Error starting session");
                        /*Response.Write("Error starting session");

                        if (db != null)
                        {
                            db.CloseConnection();
                        }
                        Response.End();
                        return null;*/

                        /* Let's try just signing out rather than showing an error message */
                        userId = 0;
                    }
                }
                else if (!autoCreate)
                {
                    sessionData.autoLoginId = "";
                    sessionData.userId = userId;

                    if (userId > 0)
                    {
                        SelectQuery query = User.GetSelectQueryStub(core, UserLoadOptions.Info);
                        query.AddCondition("user_active", true);
                        query.AddCondition("user_keys.user_id", userId);

                        System.Data.Common.DbDataReader userSessionReader = db.ReaderQuery(query);

                        if (userSessionReader.HasRows)
                        {
                            userSessionReader.Read();

                            loggedInMember = new User(core, userSessionReader, UserLoadOptions.Info);

                            userSessionReader.Close();
                            userSessionReader.Dispose();

                            isLoggedIn = true;
                            //signInState = SessionSignInState.SignedIn;
                            if (loggedInMember.UserInfo.TwoFactorAuthVerified && twoFactor)
                            {
                                signInState = SessionSignInState.TwoFactorValidated;
                            }
                            else
                            {
                                signInState = SessionSignInState.SignedIn;
                            }
                        }
                        else
                        {
                            userSessionReader.Close();
                            userSessionReader.Dispose();

                            // TODO: activation
                            //core.Display.ShowMessage("Inactive account", "You have attempted to use an inactive account. If you have just registered, check for an e-mail with an activation link at the e-mail address you provided.");
                            Response.Write("You have attempted to use an inactive account. If you have just registered, check for an e-mail with an activation link at the e-mail address you provided.");
                            //Display.ShowMessage(this, "Error", "Error starting session");
                            //Response.Write("fail 1");
                            if (db != null)
                            {
                                db.CloseConnection();
                            }
                            Response.End();
                        }
                    }
                }
            }

            //
            // At this point either loggedInMember should be populated or
            // one of the below is true
            // * Key didn't match one in the DB
            // * User does not exist
            // * User is inactive
            //
            if (loggedInMember == null)
            {
                if (sessionData == null)
                {
                    sessionData = new SessionCookie();
                }
                sessionData.autoLoginId = "";
                sessionData.userId = userId = 0;
                enableAutologin = isLoggedIn = false;
                signInState = SessionSignInState.SignedOut;

                if (userId > 0)
                {
                    SelectQuery query = User.GetSelectQueryStub(core, UserLoadOptions.Info);
                    query.AddCondition("user_keys.user_id", userId);

                    System.Data.Common.DbDataReader userReader = db.ReaderQuery(query);

                    if (userReader.HasRows)
                    {
                        userReader.Read();

                        loggedInMember = new User(core, userReader, UserLoadOptions.Info);
                    }

                    userReader.Close();
                    userReader.Dispose();
                }
            }

            // INFO: phpBB2 performs a ban check, we don't have those facilities so let's skip

            //
            // Create or update the session
            //
            long changedRows = 0;

            if (record == null)
            {
                changedRows = db.UpdateQuery(string.Format("UPDATE user_sessions SET session_time_ut = UNIX_TIMESTAMP(), user_id = {0}, session_signed_in = {1} WHERE session_string = '{3}' AND session_ip = '{2}';",
                    userId, (byte)signInState, ipAddress.ToString(), sessionId)); // , session_http_referer = ''
            }

            if (changedRows == 0)
            {
                // This should force new sessions on external domains to re-auth rather than logout
                if (core.Hyperlink.CurrentDomain != Hyperlink.Domain)
                {
                    string referer = string.Empty;
                    if (HttpContext.Current.Request.UrlReferrer != null)
                    {
                        referer = HttpContext.Current.Request.UrlReferrer.ToString();
                    }
                    HttpContext.Current.Response.Redirect(protocol + Hyperlink.Domain + string.Format("/session.aspx?domain={0}&path={1}&urlreferer={2}",
                        HttpContext.Current.Request.Url.Host, core.PagePath.TrimStart(new char[] { '/' }), referer));
                    return string.Empty;
                }
                else
                {
                    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                    byte[] randomNumber = new byte[16];
                    rng.GetBytes(randomNumber);
                    //Random rand = new Random((int)(DateTime.Now.Ticks & 0xFFFF));
                    //rand.NextDouble().ToString()

                    string rand = HexRNG(randomNumber);
                    sessionId = SessionState.SessionMd5(rand + "bsseed" + DateTime.Now.Ticks.ToString() + ipAddress.ToString()).ToLower();

                    if (record == null)
                    {
                        rootSessionId = sessionId;
                    }
                    string referer = string.Empty;
                    if (urlreferer != null)
                    {
                        referer = urlreferer.ToString();
                    }
                    db.UpdateQuery(string.Format("INSERT INTO user_sessions (session_string, session_time_ut, session_start_ut, session_signed_in, session_ip, user_id, session_root_string, session_domain, session_http_referer) VALUES ('{0}', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), {1}, '{2}', {3}, '{4}', '{5}', '{6}')",
                        sessionId, (byte)signInState, ipAddress.ToString(), userId, Mysql.Escape(rootSessionId), Mysql.Escape(currentDomain), Mysql.Escape(referer)));
                }
            }

            if (record == null)
            {
                // 1 in 100 chance of deleting stale sessions
                // Move delete stale session code outside to allow guest sessions to clear stale sessions on low use websites
                Random rand = new Random();
                if (rand.NextDouble() * 100 < 1)
                {
                    db.UpdateQuery(string.Format("DELETE FROM user_sessions WHERE session_time_ut + {0} < UNIX_TIMESTAMP()",
                        SessionState.SESSION_EXPIRES));
                }

                if (userId != 0)
                {
                    long ts = UnixTime.UnixTimeStamp() - loggedInMember.UserInfo.LastVisitDateRaw;

                    if (ts >= 60)
                    {
                        db.UpdateQuery(string.Format("UPDATE user_info SET user_last_visit_ut = UNIX_TIMESTAMP() where user_id = {0}",
                            loggedInMember.UserId));
                    }

                    if (enableAutologin)
                    {
                        string autoLoginKey = SessionState.SessionMd5(rand.NextDouble().ToString() + "zzseed").Substring(4, 16) + SessionState.SessionMd5(rand.NextDouble().ToString() + "zzseed").Substring(4, 16);

                        if (!string.IsNullOrEmpty(sessionData.autoLoginId))
                        {
                            db.UpdateQuery(string.Format("UPDATE session_keys SET key_last_ip = '{0}', key_id = '{1}', key_last_visit_ut = UNIX_TIMESTAMP() WHERE key_id = '{2}'",
                                ipAddress.ToString(), SessionState.SessionMd5(autoLoginKey), SessionState.SessionMd5(sessionData.autoLoginId)));
                        }
                        else
                        {
                            db.UpdateQuery(string.Format("INSERT INTO session_keys (key_id, user_id, key_last_ip, key_last_visit_ut, key_browser_string) VALUES ('{0}', {1}, '{2}', UNIX_TIMESTAMP(), '{3}')",
                                SessionState.SessionMd5(autoLoginKey), userId, ipAddress.ToString(), Mysql.Escape(Request.UserAgent)));
                        }

                        sessionData.autoLoginId = autoLoginKey;
                        autoLoginKey = "";
                    }
                    else
                    {
                        sessionData.autoLoginId = "";
                    }
                }
            }

            core.Hyperlink.Sid = sessionId;

            if (record == null)
            {
                Response.Cookies.Clear();

                /*xs = new XmlSerializer(typeof(SessionCookie));
                StringBuilder sb = new StringBuilder();
                stw = new StringWriter(sb);

                xs.Serialize(stw, sessionData);
                stw.Flush();
                stw.Close();*/

                HttpCookie newSessionDataCookie = new HttpCookie(cookieName + "_data");

                //newSessionDataCookie.Domain = core.Hyperlink.CurrentDomain; // DO NOT DO THIS, exposes cookie to sub domains
                newSessionDataCookie.Path = "/";
                newSessionDataCookie.Value = sessionData.ToString().Replace("\r", "").Replace("\n", "");
                newSessionDataCookie.Expires = DateTime.Now.AddYears(1);
                newSessionDataCookie.Secure = core.Settings.UseSecureCookies && core.Hyperlink.CurrentDomain == Hyperlink.Domain;
                newSessionDataCookie.HttpOnly = true;
                Response.Cookies.Add(newSessionDataCookie);

                HttpCookie newSessionSidCookie = new HttpCookie(cookieName + "_sid");
                //newSessionSidCookie.Domain = core.Hyperlink.CurrentDomain; // DO NOT DO THIS, exposes cookie to sub domains
                newSessionSidCookie.Path = "/";
                newSessionSidCookie.Value = sessionId;
                newSessionSidCookie.Expires = DateTime.MinValue;
                newSessionSidCookie.Secure = core.Settings.UseSecureCookies && core.Hyperlink.CurrentDomain == Hyperlink.Domain;
                newSessionSidCookie.HttpOnly = true;
                Response.Cookies.Add(newSessionSidCookie);

                if (Request.Cookies[cookieName + "_sid"] == null && signInState != SessionSignInState.Bot)
                {
                    core.Hyperlink.SidUrls = true;
                }
            }

            return sessionId;
        }
Пример #4
0
        public void SessionEnd(string sessionId, long userId, DnsRecord record)
        {
            string cookieName = "hailToTheChef";
            //XmlSerializer xs;
            //StringWriter stw;

            if (!string.IsNullOrEmpty(sessionId))
            {
                if (!IsValidSid(sessionId))
                {
                    return;
                }
            }
            else
            {
                return;
            }

            //
            // Delete existing session
            //
            if (record == null)
            {
                db.UpdateQuery(string.Format("DELETE FROM user_sessions WHERE (session_string = '{0}' OR session_root_string = '{0}') AND user_id = {1};",
                    sessionId, userId));
            }
            else
            {
                SelectQuery query = new SelectQuery(typeof(Session));
                query.AddCondition("session_string", sessionId);
                query.AddCondition("user_id", userId);
                query.AddCondition("session_domain", record.Domain);

                System.Data.Common.DbDataReader sessionReader = db.ReaderQuery(query);

                List<string> rootSessionIds = new List<string>();
                while (sessionReader.Read())
                {
                    rootSessionIds.Add((string)sessionReader["session_root_string"]);
                }

                sessionReader.Close();
                sessionReader.Dispose();

                if (rootSessionIds.Count > 0)
                {
                    DeleteQuery dQuery = new DeleteQuery(typeof(Session));
                    QueryCondition qc1 = dQuery.AddCondition("session_string", ConditionEquality.In, rootSessionIds);
                    qc1.AddCondition(ConditionRelations.Or, "session_root_string", ConditionEquality.In, rootSessionIds);
                    dQuery.AddCondition("user_id", userId);

                    db.Query(dQuery);
                }
            }

            //
            // Remove this auto-login entry (if applicable)
            //

            //
            // We expect that message_die will be called after this function,
            // but just in case it isn't, reset $userdata to the details for a guest
            //

            if (record == null)
            {
                Response.Cookies.Clear();

                SelectQuery query = User.GetSelectQueryStub(core, UserLoadOptions.Info);
                query.AddCondition("user_keys.user_id", 0);

                DataTable userTable = db.Query(query);

                Response.Cookies.Clear();

                if (userTable.Rows.Count == 1)
                {
                    loggedInMember = new User(core, userTable.Rows[0], UserLoadOptions.Info);
                }
                HttpCookie newSessionDataCookie = new HttpCookie(cookieName + "_data");
                newSessionDataCookie.Path = "/";
                newSessionDataCookie.Value = "";
                newSessionDataCookie.Expires = DateTime.Now.AddYears(-1);
                newSessionDataCookie.Secure = core.Settings.UseSecureCookies && core.Hyperlink.CurrentDomain == Hyperlink.Domain;
                newSessionDataCookie.HttpOnly = true;
                Response.Cookies.Add(newSessionDataCookie);

                HttpCookie newSessionSidCookie = new HttpCookie(cookieName + "_sid");
                newSessionSidCookie.Path = "/";
                newSessionSidCookie.Value = "";
                newSessionSidCookie.Expires = DateTime.Now.AddYears(-1);
                newSessionSidCookie.Secure = core.Settings.UseSecureCookies && core.Hyperlink.CurrentDomain == Hyperlink.Domain;
                newSessionSidCookie.HttpOnly = true;
                Response.Cookies.Add(newSessionSidCookie);

                if (Request.Cookies[cookieName + "_sid"] == null && signInState != SessionSignInState.Bot)
                {
                    core.Hyperlink.SidUrls = true;
                }
            }

            return;
        }