private OperationHandle InvokeMethodCore(string namespaceName, string className, CimInstance instance, string methodName, CimMethodParametersCollection methodParameters, CimOperationOptions options, CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) { OperationHandle operationHandle = null; InstanceHandle instanceHandle; InstanceHandle instanceHandleForMethodInvocation; SessionHandle sessionHandle = this._handle; MiOperationFlags operationFlags = options.GetOperationFlags(); OperationOptionsHandle operationOptionsHandle = options.GetOperationOptionsHandle(); string str = namespaceName; string str1 = className; string str2 = methodName; if (instance != null) { instanceHandle = instance.InstanceHandle; } else { instanceHandle = null; } if (methodParameters != null) { instanceHandleForMethodInvocation = methodParameters.InstanceHandleForMethodInvocation; } else { instanceHandleForMethodInvocation = null; } SessionMethods.Invoke(sessionHandle, operationFlags, operationOptionsHandle, str, str1, str2, instanceHandle, instanceHandleForMethodInvocation, options.GetOperationCallbacks(asyncCallbacksReceiver), out operationHandle); return operationHandle; }
public static void SaveDefaultXML(string currentXML, string ddlIndex, string ddlText, string gridType) { var sessionMethods = new SessionMethods(); string prefix = null; if (gridType == "RQMT Grid") { prefix = "RQMT"; } else { sessionMethods.Session["CurrentXML"] = currentXML; sessionMethods.Session["CurrentDropDown"] = ddlIndex; sessionMethods.Session["Crosswalk_GridView_ML"] = ddlText; sessionMethods.Session["defaultCrosswalkGrid_ML"] = ddlText; } if (prefix != null) { sessionMethods.Session[prefix + "_CurrentXML"] = currentXML; sessionMethods.Session[prefix + "_CurrentDropDown"] = ddlIndex; sessionMethods.Session[prefix + "_GridView"] = ddlText; sessionMethods.Session[prefix + "_GridView_Default"] = ddlText; } }
protected void btn_login_Click(object sender, EventArgs e) { /*1 - Grabbing the user's login info*/ String Username = txb_TUID.Text; String Password = txb_Password.Text; /*2 - Resetting controls to default values*/ lbl_Error.Text = ""; /*3 - Basic validation*/ if (Username.Equals("")) { lbl_Error.Text = "ERROR: The username field is empty."; lbl_Error.ForeColor = Color.Red; } else if (Password.Equals("")) { lbl_Error.Text = "ERROR: The password field is empty."; lbl_Error.ForeColor = Color.Red; } else if (valid.validateLogin(Username) || valid.validateLogin(Password)) { lbl_Error.Text = "ERROR: Illegal input character was used."; lbl_Error.ForeColor = Color.Red; } else { /*3 - Checking that the Username and Password are both correct*/ bool Correct_Login_Information = AuthenticateUser(Username, Password); if (!Correct_Login_Information) { lbl_Error.Text = "ERROR: Your username or password is incorrect."; lbl_Error.ForeColor = Color.Red; } else { /*4 - Requesting Web Service information*/ TempleUser.LDAPuser Temple_Information = TempleUser.WebService.getLDAPEntryByAccessnet(Username); TempleUser.StudentObj Student_Information = TempleUser.WebService.getStudentInfo(Temple_Information.templeEduID); /*5 - Checking we received something from Web Services*/ if (Temple_Information == null) { lbl_Error.Text = "ERROR: Web Services did not return anything."; } else if (Temple_Information != null) { /*Populating the Session Object with the user's information*/ Session["TU_ID"] = Temple_Information.templeEduID;//TUID Session["First_Name"] = Temple_Information.givenName; Session["Last_Name"] = Temple_Information.sn; Session["Email"] = Temple_Information.mail; Session["Title"] = Temple_Information.title; Session["Affiliation_Primary"] = Temple_Information.eduPersonPrimaryAffiliation; Session["Affiliation_Secondary"] = Temple_Information.eduPersonAffiliation; /*Security Session Variable*/ Session["Authenticated"] = true; /*If the user is also a student, we can also retreive their information and add them to the Session Object*/ if (Student_Information != null) { Session["School"] = Student_Information.school; Session["Major_1"] = Student_Information.major1; Session["Major_2"] = Student_Information.major2; } /*Successful Login - Allowed to be redirected to Home.aspx*/ DbMethods DbMethodsObj = new DbMethods(); bool test = DbMethodsObj.CheckIfAdminExists(Student_Information.tuid); //check if user is an Admin if (test == true) { //Security Session Variable for Admin Session["AdminToken"] = true; Response.Redirect("Admin.aspx"); } else { //check if expert exists in system int count = Convert.ToInt32(DbMethodsObj.CheckIfExpertExists(Student_Information.tuid)); if (count == 0) { Response.Redirect("CreateProfile.aspx"); } else { SessionMethods sessionMethodsObj = new SessionMethods(); sessionMethodsObj.storeExpertDataInSession(); //change isActive to true DbMethodsObj.SetExpertIsActiveTrue(); Expert expertProfileObj = (CapstoneBlackstone.Expert)Session["expertProfileObj"]; string user_name = expertProfileObj.username; var x = Session["Authenticated"]; //redirect to expert page Response.Redirect("ExpertPage.aspx?username=" + user_name);// conserve the session token at login } } } } } }//end logIn button clickEvent
/// <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; }
public SessionState(Core core, Mysql db, OAuthToken token, HttpRequest Request, HttpResponse Response) { if (core == null) { throw new NullCoreException(); } this.Request = Request; this.Response = Response; this.db = db; this.core = core; applicationId = token.ApplicationId; SelectQuery query = new SelectQuery(typeof(PrimitiveApplicationInfo)); query.AddCondition("application_id", token.ApplicationId); query.AddCondition("app_oauth_access_token", token.Token); System.Data.Common.DbDataReader appReader = core.Db.ReaderQuery(query); if (appReader.HasRows) { appReader.Read(); PrimitiveApplicationInfo pai = new PrimitiveApplicationInfo(core, appReader); appReader.Close(); appReader.Dispose(); if (pai.Owner is User) { this.core = core; this.db = core.Db; isLoggedIn = true; this.signInState = SessionSignInState.SignedIn; loggedInMember = (User)pai.Owner; ipAddress = IPAddress.Parse(SessionState.ReturnRealIPAddress(Request.ServerVariables)); this.sessionMethod = SessionMethods.OAuth; } } else { appReader.Close(); appReader.Dispose(); this.core = core; this.db = core.Db; isLoggedIn = false; this.signInState = SessionSignInState.SignedOut; ipAddress = IPAddress.Parse(SessionState.ReturnRealIPAddress(Request.ServerVariables)); this.sessionMethod = SessionMethods.OAuth; } }
public void SessionPagestart(string userIp) { #if DEBUG Stopwatch timeTimer = new Stopwatch(); timeTimer.Start(); #endif long nowUt = UnixTime.UnixTimeStamp(); #if DEBUG timeTimer.Stop(); HttpContext.Current.Response.Write(string.Format("<!-- section A.1.b in {0} -->\r\n", timeTimer.ElapsedTicks / 10000000.0)); #endif string cookieName = "hailToTheChef"; /*XmlSerializer xs; StringWriter stw;*/ string protocol = "http://"; if (core.Settings.UseSecureCookies) { protocol = "https://"; } sessionData = null; sessionId = null; #if DEBUG Stopwatch botTimer = new Stopwatch(); botTimer.Start(); #endif if (!String.IsNullOrEmpty(IsBotUserAgent(Request.UserAgent))) { signInState = SessionSignInState.Bot; core.Hyperlink.SidUrls = false; return; } #if DEBUG botTimer.Stop(); HttpContext.Current.Response.Write(string.Format("<!-- section A.1.c in {0} -->\r\n", botTimer.ElapsedTicks / 10000000.0)); #endif #if DEBUG Stopwatch cookieTimer = new Stopwatch(); cookieTimer.Start(); #endif HttpCookie sidCookie = Request.Cookies[cookieName + "_sid"]; HttpCookie dataCookie = Request.Cookies[cookieName + "_data"]; if (sidCookie != null || dataCookie != null) { if (sidCookie != null) { sessionId = sidCookie.Value; } if (dataCookie != null) { /*xs = new XmlSerializer(typeof(SessionCookie)); StringReader sr = new StringReader(HttpUtility.UrlDecode(Request.Cookies[cookieName + "_data"].Value));*/ try { sessionData = new SessionCookie(HttpUtility.UrlDecode(dataCookie.Value)); //(SessionCookie)xs.Deserialize(sr); } catch { sessionData = new SessionCookie(); } } else { sessionData = new SessionCookie(); } if (string.IsNullOrEmpty(sessionId)) { sessionId = (string)Request.QueryString["sid"]; } if ((Hyperlink.Domain != core.Hyperlink.CurrentDomain) && (sessionId != (string)Request.QueryString["sid"]) && (!string.IsNullOrEmpty((string)Request.QueryString["sid"]))) { sessionData = new SessionCookie(); sessionId = (string)Request.QueryString["sid"]; } if ((core.Hyperlink.CurrentDomain != Hyperlink.Domain) && string.IsNullOrEmpty(sessionId)) { 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; } sessionMethod = SessionMethods.Cookie; } else { sessionData = new SessionCookie(); if (Request.QueryString["sid"] != null) { sessionId = (string)Request.QueryString["sid"]; } sessionMethod = SessionMethods.Get; if ((core.Hyperlink.CurrentDomain != Hyperlink.Domain) && string.IsNullOrEmpty(sessionId)) { 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; } } #if DEBUG cookieTimer.Stop(); HttpContext.Current.Response.Write(string.Format("<!-- section A.1.d in {0} -->\r\n", cookieTimer.ElapsedTicks / 10000000.0)); #endif #if DEBUG Stopwatch sidTimer = new Stopwatch(); sidTimer.Start(); #endif if (!string.IsNullOrEmpty(sessionId)) { if (!IsValidSid(sessionId)) { sessionId = ""; } } #if DEBUG sidTimer.Stop(); HttpContext.Current.Response.Write(string.Format("<!-- section A.1.e in {0} -->\r\n", sidTimer.ElapsedTicks / 10000000.0)); #endif if (!string.IsNullOrEmpty(sessionId)) { // // session_id exists so go ahead and attempt to grab all // data in preparation // SelectQuery query = User.GetSelectQueryStub(core, UserLoadOptions.Info); query.AddFields("session_ip", "session_time_ut", "session_signed_in"); query.AddJoin(JoinTypes.Inner, new DataField(typeof(User), "user_id"), new DataField("user_sessions", "user_id")); query.AddCondition("session_string", sessionId); System.Data.Common.DbDataReader userSessionReader = db.ReaderQuery(query); // // Did the session exist in the DB? // if (userSessionReader.HasRows) { userSessionReader.Read(); //DataRow userSessionRow = userSessionTable.Rows[0]; loggedInMember = new User(core, userSessionReader, UserLoadOptions.Info); sbyte sessionSignedIn = (sbyte)userSessionReader["session_signed_in"]; long sessionTimeUt = (long)userSessionReader["session_time_ut"]; string sessionIp = (string)userSessionReader["session_ip"]; userSessionReader.Close(); userSessionReader.Dispose(); core.Hyperlink.Sid = sessionId; if (loggedInMember.UserId != 0) { isLoggedIn = true; if (loggedInMember.UserInfo.TwoFactorAuthVerified) { signInState = (SessionSignInState)sessionSignedIn; } else { signInState = SessionSignInState.SignedIn; } } // // Do not check IP assuming equivalence, if IPv4 we'll check only first 24 // bits ... I've been told (by vHiker) this should alleviate problems with // load balanced et al proxies while retaining some reliance on IP security. // // we will use complete matches in BoxSocial if (sessionIp == userIp) { // // Only update session DB a minute or so after last update // if (nowUt - sessionTimeUt >= 60) { long changedRows = db.UpdateQuery(string.Format("UPDATE user_sessions SET session_time_ut = UNIX_TIMESTAMP(), session_http_referer = '' WHERE session_string = '{0}';", sessionId)); if (SignedIn) { 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)); Random rand = new Random(); // 1 in 10 chance of deleting stale sessions if (rand.NextDouble() * 10 < 1) { db.UpdateQuery(string.Format("DELETE FROM user_sessions WHERE session_time_ut + {0} < UNIX_TIMESTAMP()", SessionState.SESSION_EXPIRES)); } } } SessionClean(sessionId); } #if DEBUG Stopwatch cookie2Timer = new Stopwatch(); cookie2Timer.Start(); #endif 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.Value = sessionData.ToString().Replace("\r", "").Replace("\n", ""); newSessionDataCookie.Path = "/"; 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 = sessionId; newSessionSidCookie.Expires = DateTime.MinValue; newSessionSidCookie.Secure = core.Settings.UseSecureCookies && core.Hyperlink.CurrentDomain == Hyperlink.Domain; newSessionSidCookie.HttpOnly = true; Response.Cookies.Add(newSessionSidCookie); // Add the session_key to the userdata array if it is set if (Request.Cookies[cookieName + "_sid"] == null && signInState != SessionSignInState.Bot) { core.Hyperlink.SidUrls = true; } #if DEBUG cookie2Timer.Stop(); HttpContext.Current.Response.Write(string.Format("<!-- section A.1.f in {0} -->\r\n", cookie2Timer.ElapsedTicks / 10000000.0)); #endif return; } } else { userSessionReader.Close(); userSessionReader.Dispose(); //Display.ShowMessage(this, "Error", "Error starting session"); //Response.Write("fail 3"); //Response.End(); } } // // If we reach here then no (valid) session exists. So we'll create a new one, // using the cookie user_id if available to pull basic user prefs. // long userId = (sessionData != null && sessionData.userId > 0) ? sessionData.userId : 0; // If the current domain is not the root domain, and the session is empty if ((core.Hyperlink.CurrentDomain != Hyperlink.Domain) && userId > 0 /*&& string.IsNullOrEmpty(sessionId)*/) { if ((core.Hyperlink.CurrentDomain != Hyperlink.Domain) && string.IsNullOrEmpty(sessionId)) { 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; } } else { #if DEBUG Stopwatch httpTimer = new Stopwatch(); httpTimer.Start(); #endif SessionBegin(userId, true); #if DEBUG httpTimer.Stop(); HttpContext.Current.Response.Write(string.Format("<!-- section A.1.a in {0} -->\r\n", httpTimer.ElapsedTicks / 10000000.0)); #endif } }
protected void btnCreateProfile_Click(object sender, EventArgs e) { lblPicCheckSize.Visible = false; lblPicCheckType.Visible = false; int count = Convert.ToInt32(db.CheckIfUsernameExists(txtUsername.Text)); if (valid.IsBlank(txtFirstName.Text) || valid.IsBlank(txtLastName.Text) || valid.IsBlank(txtEmail.Text) || valid.IsBlank(txtUsername.Text) || valid.IsBlank(txtEmail.Text)) { lblRequired.Visible = true; } else if (count >= 1) { lblUsernameCheck.Visible = true; } else { string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName); //uploaded file extension int iFileSize = FileUpload1.PostedFile.ContentLength; //uploaded file size if (FileUpload1.FileContent != null && FileUpload1.HasFile) { if (valid.TestForLegalImageTypes(fileExtension) == false) {//fail lblPicCheckType.Visible = true; lblPicCheckType.Text = fileExtension + " file extension is not allowed. Please use .png, .gif, .jpg, .jpeg, .pdf, .pcd, .fpx, .tif instead"; } else if (iFileSize >= 90000) {//fail lblPicCheckSize.Visible = true; lblPicCheckSize.Text = "Your file size is " + iFileSize + " bytes. Please reduce the size to less than 90 KB (90000 bytes)."; } else { MemoryStream ms = new MemoryStream(); var img = System.Drawing.Image.FromStream(FileUpload1.FileContent); img.Save(ms, System.Drawing.Imaging.ImageFormat.Png); imageBytes = ms.ToArray(); Session.Add("picture", imageBytes); } } else { string FilePath = System.Web.VirtualPathUtility.ToAbsolute("~/Images/TUOwls_logo.png"); FileStream fs = new FileStream(FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); imageBytes = new byte[fs.Length]; fs.Read(imageBytes, 0, Convert.ToInt32(fs.Length)); fs.Close(); MemoryStream ms = new MemoryStream(); Session.Add("picture", imageBytes); } Expert newExpert = new Expert { tuID = (string)Session["TU_ID"], username = txtUsername.Text, firstName = txtFirstName.Text, lastName = txtLastName.Text, college = (string)Session["School"], major = (string)Session["Major_1"], email = txtEmail.Text, dateJoined = DateTime.Now, phoneNumber = txtPhoneNumber.Text, aboutMe = aboutMe.Text, linkedIn = txtLinkedIn.Text, picture = (byte[])Session["picture"], isActive = true, skillGroupID = Int32.Parse(SkillGroupDropdown.SelectedValue), genderID = Int32.Parse(genderDropdown.SelectedValue), ethnicityID = Int32.Parse(ethnicityDropdown.SelectedValue), lastUpdateDate = DateTime.Now, lastUpdateUser = txtLastName.Text + ", " + txtFirstName.Text }; DbMethods dbmethods = new DbMethods(); SessionMethods sessionMethodsObj = new SessionMethods(); int result = dbmethods.CreateExpert(newExpert); sessionMethodsObj.storeExpertDataInSession(); Response.Redirect("ExpertPage.aspx?username=" + newExpert.username); //Response.Write(result); } }
public static void UpdateSessionData(string args) { var sessionMethods = new SessionMethods(); sessionMethods.Session["itisettings"] = args; }
private OperationHandle SubscribeCore(string namespaceName, string queryDialect, string queryExpression, CimOperationOptions operationOptions, CimSubscriptionDeliveryOptions options, CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) { OperationHandle operationHandle = null; SessionMethods.Subscribe(this._handle, operationOptions.GetOperationFlags(), operationOptions.GetOperationOptionsHandle(), namespaceName, queryDialect, queryExpression, options.GetSubscriptionDeliveryOptionsHandle(), operationOptions.GetOperationCallbacks(asyncCallbacksReceiver), out operationHandle); return operationHandle; }
private OperationHandle QueryInstancesCore(string namespaceName, string queryDialect, string queryExpression, CimOperationOptions options, CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) { OperationHandle operationHandle = null; SessionMethods.QueryInstances(this._handle, options.GetOperationFlags(), options.GetOperationOptionsHandle(), namespaceName, queryDialect, queryExpression, options.GetKeysOnly(), options.GetOperationCallbacks(asyncCallbacksReceiver), out operationHandle); return operationHandle; }
private OperationHandle ModifyInstanceCore(string namespaceName, CimInstance instance, CimOperationOptions options, CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) { OperationHandle operationHandle = null; SessionMethods.ModifyInstance(this._handle, options.GetOperationFlags(), options.GetOperationOptionsHandle(), namespaceName, instance.InstanceHandle, options.GetOperationCallbacks(asyncCallbacksReceiver), out operationHandle); return operationHandle; }
private OperationHandle GetClassCore(string namespaceName, string className, CimOperationOptions options, CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) { OperationHandle operationHandle = null; SessionMethods.GetClass(this._handle, options.GetOperationFlags(), options.GetOperationOptionsHandle(), namespaceName, className, options.GetOperationCallbacks(asyncCallbacksReceiver), out operationHandle); return operationHandle; }
private OperationHandle EnumerateReferencingInstancesCore(string namespaceName, CimInstance sourceInstance, string associationClassName, string sourceRole, CimOperationOptions options, CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) { OperationHandle operationHandle = null; SessionMethods.ReferenceInstances(this._handle, options.GetOperationFlags(), options.GetOperationOptionsHandle(), namespaceName, sourceInstance.InstanceHandle, associationClassName, sourceRole, options.GetKeysOnly(), options.GetOperationCallbacks(asyncCallbacksReceiver), out operationHandle); return operationHandle; }
private OperationHandle TestConnectionCore(CimOperationOptions options, CimAsyncCallbacksReceiverBase asyncCallbacksReceiver) { OperationHandle operationHandle = null; SessionMethods.TestConnection(this._handle, options.GetOperationFlags(), options.GetOperationCallbacks(asyncCallbacksReceiver), out operationHandle); return operationHandle; }