public void Can_get_using_default_key()
 {
     var data = "test";
     _stateData[Utils.BuildFullKey<string>(null)] = data;
     var returned = new HttpSessionState(_context).Get<string>();
     Assert.That(returned, Is.EqualTo(data));
 }
    //处理BeginRequest事件的实际代码
    void Application_AcquireRequestState(object sender, EventArgs e)
    {
        context = ((HttpApplication)sender).Context;
        request = context.Request;
        session = context.Session;

        requestPath = request.Path;
        defaultPath = request.ApplicationPath + "/Default.aspx";

        //仅处理向页面的请求,排除向资源文件的请求,排除非文件夹admin下的所有文件和后台首页
        //admin/index.aspx可以被任何已登陆用户访问,所以排除
        if (requestPath.IndexOf(".aspx") != -1 && !requestPath.StartsWith(defaultPath))
        {
            tbUser user = (tbUser)session[Constant.User];
            if (user == null)
            {
                //还没有登陆
                //context.Response.Redirect("~/Default.aspx");
                context.Response.Write("<script>parent.location.href='" + request.ApplicationPath + "/Default.aspx';</script>");
                context.Response.End();
            }
            else
            {
                bool isGranted = IsGranted(user.usertype, requestPath);
                if (isGranted == false)
                {
                    //没有权限访问
                    context.Response.Redirect("~/403.html");
                }

            }
        }
    }
Example #3
0
 public static void RemoveFrom(HttpSessionState session)
 {
   if (IsIn(session))
   {
     session.Remove(Key);
   }
 }
Example #4
0
    /// <summary>
    /// registerPlayer
    /// This method adds a player as a HttpSessionState object
    /// to the waitinglist.
    /// When there are two players 
    /// they are passed to a new Game object
    /// and removed from the list 
    /// </summary>
    public void registerPlayer(HttpSessionState player)
    {
        waitingList.Add(player);
        // if 2 or more waiting, make a game
        if( waitingList.Count >= 2 )
        {
            //Creates a new game
            //Sends the two session objects in the array
            //to the newly created game

            // Game constructor called passing name and SessionID for each player
            Game newGame = new Game(
                    (string)((HttpSessionState)waitingList[0])["Name"],
                    (string)((HttpSessionState)waitingList[0]).SessionID,
                    (string)((HttpSessionState)waitingList[1])["Name"],
                    (string)((HttpSessionState)waitingList[1]).SessionID );

            // Give each player HttpSessionState object a reference to the Game
            // This is one way communication instead of two way
            ((HttpSessionState)waitingList[0])["Game"] = newGame;
            ((HttpSessionState)waitingList[1])["Game"] = newGame;
            ((HttpSessionState)waitingList[0])["Status"] = "In Game";
            ((HttpSessionState)waitingList[1])["Status"] = "In Game";

            // remove from waiting list
            waitingList.RemoveAt(0);
            waitingList.RemoveAt(0);
        }
    }
Example #5
0
    //--------------------------------------------------------------------------------
    public static void CountVisitor(HttpRequest request, HttpSessionState session)
    {
        string host = request["REMOTE_HOST"];
        long visitorSessionCount;
        using (ISession iSession = NHSessionManager.GetSession())
        {
            using (ITransaction transaction = iSession.BeginTransaction())
            {
                Visitor visitor = iSession.Get<Visitor>(host);
                if (visitor == null)
                    visitor = new Visitor(host);
                visitor.Visits++;
                iSession.SaveOrUpdate(visitor);
                iSession.Flush();
                visitorSessionCount = visitor.Visits;
                transaction.Commit();
                session[VisitorSessionCount] = visitorSessionCount;

            }

            Expression<Func<Visitor, object>> expr = v => v.Visits;
            var criteria = iSession.CreateCriteria<Visitor>()
                    .SetProjection(Projections.Sum(expr), Projections.Count(expr));
            object[] result = criteria.UniqueResult<object[]>();

            session[SessionCount] = Convert.ToInt64(result[0]);
            session[HostCount] = Convert.ToInt64(result[1]);
        }
    }
 public void Can_get()
 {
     var data = "test";
     _stateData[typeof (string).FullName + "test_key"] = data;
     var returned = new HttpSessionState(_context).Get<string>("test_key");
     Assert.That(returned, Is.EqualTo(data));
 }
Example #7
0
    // static ?!?!?!?
    public static XmlDocument Query(HttpRequest req, HttpSessionState session,Hashtable xsltParameters)
    {
        XmlDocument inputDoc = new XmlDocument();

        inputDoc.AppendChild(inputDoc.CreateProcessingInstruction("http-redirect", "/"+xsltParameters["base"].ToString()+"/static.cs?page=index"));

        return inputDoc;
    }
Example #8
0
 public Users GetUser(HttpSessionState session)
 {
     if (IsUserLogin(session))
     {
         Users u = session["User"] as Users;
         return u;
     }
     return null;
 }
Example #9
0
		public static void AddHttpSessionStateToContext (HttpContext context, IHttpSessionState container)
		{
			if (context == null || container == null)
				return;
			if (context.Session != null)
				throw new HttpException ("An HttpSessionState object for the current session has already been added to the specified context.");
			
			HttpSessionState state = new HttpSessionState (container);
			context.SetSession (state);
		}
Example #10
0
    public static UserSession FromContext( HttpSessionState session, bool failOnMissing )
    {
        if( session == null )
            throw new ArgumentNullException( "session" );

        UserSession mySession = session[ "UserSession" ] as UserSession;
        if( ( mySession == null ) &&
            ( failOnMissing == false ) )
        {
            mySession = new UserSession();
            session.Add( "UserSession", mySession );
        }
        return mySession;
    }
Example #11
0
    public override bool Login(string username, string password, HttpSessionState session)
    {
        string sql = "select * from [User] where UserName = '******' and [Password] = '" + Utils.Crypto(password) + "'";
        DbDataReader r = DBHelper.INST.ExecuteSqlDR(sql);

        if (!r.Read())
            return false;

        session[IAuthenicable.NameKey] = username;
        session[IAuthenicable.IDKey] = r.GetInt32(0);

        return true;
    }
        public void Update( String Sessionid, HttpSessionState session )
        {
            SessionReference _session = null;
            lock ( sessionCollection )
            _session = sessionCollection.ContainsKey( Sessionid ) ? sessionCollection[ Sessionid ] : new SessionReference();

            _session.Session = session;

            _session.LasAccess = DateTime.Now;
            lock ( sessionCollection )
            {
                sessionCollection[ Sessionid ] = _session;
            }
        }
Example #13
0
 /// <summary>
 /// Process will take all %field% in the loader script and replace them with values from
 /// the HTTPsession
 /// </summary>
 /// <param name="loaderScript"></param>
 /// <param name="session"></param>
 public static string process(ref string loaderScript, HttpSessionState session)
 {
     string newLoaderScript = loaderScript;
     int i = 0;
     while (-1 != (i = loaderScript.IndexOf('%')))
     {
         //int i = loaderScript.IndexOf('%');
         int y = loaderScript.IndexOf('%', i + 1);
         string variableName = loaderScript.Substring(i + 1, y - i - 1);
         string sessionValue = session[variableName] as string;
         newLoaderScript = newLoaderScript.Replace("%" + variableName + "%", sessionValue);
     }
     loaderScript = newLoaderScript;
     return newLoaderScript;
 }
Example #14
0
    /// <summary>コンストラクタ</summary>
    /// <param name="HashtableQueueName">キュー名</param>
    public CustQueue(string HashtableQueueName)
    {
        // セッションからキューを取り出す。
        this.Session = HttpContext.Current.Session;

        // セッションが空の場合は新規作成する。
        if (Session[HashtableQueueName] == null)
        {
            Session[HashtableQueueName] = new Queue();
        }

        // メンバに保持する。
        this._Queue = (Queue)Session[HashtableQueueName];

        // キューのキャパシティ
        this.Capacity = int.Parse(ConfigurationManager.AppSettings["QueueCapacity"]);
    }
Example #15
0
  public static AppState RestoreFrom(HttpSessionState session, bool remove)
  {
    if (IsIn(session))
    {
      AppState appState = FromString((string)session[Key]);

      if (remove)
      {
        RemoveFrom(session);
      }

      return appState;
    }
    else
    {
      return new AppState();
    }
  }
    public static void EnforcePermissions_RequireAll(HttpSessionState session, HttpResponse response, bool requireStakeholder, bool requireMasterAdmin, bool requireAdmin, bool requirePrincipal, bool requireProvider, bool requireStaff)
    {
        UserView userView = UserView.GetInstance();

        if (requireStakeholder && !userView.IsStakeholder)
            response.Redirect(PagePermissions.UnauthorisedAccessPageForward());

        if (requireMasterAdmin && !userView.IsMasterAdmin)
            response.Redirect(PagePermissions.UnauthorisedAccessPageForward());

        if (requireAdmin       && !userView.IsAdmin)
            response.Redirect(PagePermissions.UnauthorisedAccessPageForward());

        if (requirePrincipal   && !userView.IsPrincipal)
            response.Redirect(PagePermissions.UnauthorisedAccessPageForward());

        if (requireProvider    && !userView.IsProvider)
            response.Redirect(PagePermissions.UnauthorisedAccessPageForward());

        if (requireStaff       && !userView.IsStaff)
            response.Redirect(PagePermissions.UnauthorisedAccessPageForward());
    }
Example #17
0
 public abstract bool IsAuthenic(HttpSessionState session);
Example #18
0
 public static void Logoff(HttpResponse Response, HttpSessionState Session)
 {
     Response.Cache.SetCacheability(HttpCacheability.NoCache);
     Session.Clear();
     FormsAuthentication.SignOut();
 }
 public SessionManager(HttpSessionState httpSessionState)
 {
     session = httpSessionState;
 }
Example #20
0
 public static UserSession FromContext( HttpSessionState session )
 {
     return FromContext( session, false );
 }
Example #21
0
 public override void Logout(HttpSessionState session)
 {
     session.Clear();
 }
Example #22
0
 public bool IsUserLogin(HttpSessionState session)
 {
     return session["User"] != null;
 }
Example #23
0
        /// <summary>
        /// 获取实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="session"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T GetObject <T>(this HttpSessionState session, string key)
        {
            var value = session[key]?.ToString();

            return(value == null ? default(T) : value.JsonToEntity <T>());
        }
Example #24
0
 private SessionAdapter()
 {
     _session = HttpContext.Current.Session;
 }
Example #25
0
 public SessionHelperService(HttpSessionState sessionState)
 {
     this._sessionState = sessionState;
 }
Example #26
0
 /// <summary>
 /// 设置实体
 /// </summary>
 /// <param name="session"></param>
 /// <param name="key"></param>
 /// <param name="value"></param>
 public static void SetObject(this HttpSessionState session, string key, object value)
 {
     session[key] = value.ToJson();
 }
Example #27
0
 public static void SetString(this  HttpSessionState session, string key, string value)
 {
     session.Add(key, value);
 }
 //Constructor
 public CultureHelper(HttpSessionState httpSessionState)
 {
     session = httpSessionState;
 }
Example #29
0
        }         //

        /// <summary>
        /// Helper Session method - future use if required to chg to another session provider such as SQL Server
        /// </summary>
        /// <param name="session"></param>
        /// <param name="key"></param>
        /// <param name="sysObject"></param>
        public static void SessionSet(HttpSessionState session, string key, System.Object sysObject)
        {
            session[key] = sysObject;
        }         //
Example #30
0
 public abstract void Logout(HttpSessionState session);
Example #31
0
    void GetRegister()
    {
        if (string.IsNullOrEmpty(this.phone.Value.ToString()))
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('手机还没填呢!');</script>");

            return;
        }


        if (string.IsNullOrEmpty(this.USER_AGE.Value))
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('生日还没填呢!');</script>");

            return;
        }

        if (string.IsNullOrEmpty(this.name.Value))
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('姓名(会员名)还没填呢!');</script>");

            return;
        }

        if (string.IsNullOrEmpty(txtChkCode.Value))
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('请填写验证码!');</script>");
            return;
        }
        else
        {
            HttpSessionState Session = HttpContext.Current.Session;

            if (Session["MobileYzm"] == null)
            {
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('请重新获取验证码!');</script>");
                return;
            }

            if (Session["MobileYzm"].ToString() != txtChkCode.Value)
            {
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('验证码不正确,请重试!');</script>");
                return;
            }
        }

        if (!chkYes.Checked)
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('请接受服务协议!');</script>");
            return;
        }

        if (ddlMD.SelectedValue == "0")
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('请选择所属门店!');</script>");
            return;
        }

        MemberVO memberVO = new MemberVO();

        memberVO.phone = Request.Form["phone"];
        //  memberVO.gender = Request.Form["sex1"] == null ? Request.Form["sex2"] : Request.Form["sex1"];
        //   memberVO.gender = Request.Form["sex1"];
        memberVO.memName = Request.Form["name"];
        //   memberVO.OrgCode = ddlMD.SelectedValue;

        //  memberVO.idx = "2016071800001";
        memberVO.idx      = DateTime.Now.ToString("yyyyMMdd hhmmssfff");
        memberVO.birthday = Request.Form["USER_AGE"];

        int data = APIManage.Register.GetRegister(memberVO);



        if (data == 1223)
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('卡面号重复!');</script>");

            return;
        }
        else if (data == 1221)
        {
            APIManage.UpdateMem.updateM(memberVO.phone);

            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('手机号已存在,请登陆!');</script>");

            return;
        }
        else if (data == 1222)
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('证件号重复!');</script>");

            return;
        }



        else if (data == 0)
        {
            APIManage.UpdateMem.updateM(memberVO.phone);

            HttpCookie cookie = new HttpCookie("cookiePhone");
            cookie.Value   = phone.Value;
            cookie.Expires = DateTime.MaxValue;
            //cookie.Expires = DateTime.Now.Add(TimeSpan.MaxValue);
            HttpContext.Current.Response.Cookies.Add(cookie);
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>sky('成功!');</script>");

            //   Response.Redirect("index.aspx");
        }
        else
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('输入有误!');</script>");
            return;
        }
    }
Example #32
0
 public override bool IsAuthenic(HttpSessionState session)
 {
     return session[IAuthenicable.NameKey] != null;
 }
Example #33
0
 public SessionManager()
 {
     session = HttpContext.Current.Session;
 }
Example #34
0
 public SignupProcessor(HttpSessionState session) : base(session)
 {
 }
Example #35
0
 public SessionTools(HttpSessionState session)
 {
     this.Session = session;
 }
 public static string GetAsString(this HttpSessionState pair, string key, string defaultValue = "")
 {
     return((string)Get(pair, key, defaultValue));
 }
Example #37
0
 /// <summary>
 /// 获取Session
 /// </summary>
 /// <typeparam name="T">对象</typeparam>
 /// <param name="session"></param>
 /// <param name="key">键</param>
 /// <returns>对象</returns>
 public static T Get <T>(this HttpSessionState session, string key) => (T)session[key];
Example #38
0
 public static void InitSession(HttpSessionState session)
 {
     session.Add(SESSION_KEY, new Dictionary <string, TempDir>());
 }
Example #39
0
 /// <summary>
 /// 写Session
 /// </summary>
 /// <param name="session"></param>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 public static void Set(this HttpSessionState session, string key, dynamic value) => session[key] = value;
Example #40
0
        private static UserSession CreateFailedSession(BizPortalSessionContext context, HttpSessionState session, iSystem systemApplication,
                                                       String ipAddress, string userName, MemberUser user, string message)
        {
            DateTime    now           = DateTime.Now;
            UserSession failedSession = new UserSession
            {
                ApplicationSessionID = session.SessionID,
                FromIPAddress        = ipAddress,
                LoginFailed          = true,
                LoginMessage         = message,
                SystemID             = systemApplication.SystemID,
                SessionPeriod        = new TimeInterval(now, now),
                User     = user,
                UserName = userName,
            };

            return(failedSession);
        }
Example #41
0
        public static bool SetSession(HttpSessionState session, long signInId)
        {
            if (session != null)
            {
                try
                {
                    if (signInId.Equals(0))
                    {
                        RequestLogOnPage();
                        return(false);
                    }

                    Entities.Office.SignInView signInView = Data.Office.User.GetSignInView(signInId);

                    if (signInView == null || signInView.LoginId == null)
                    {
                        session.Remove("UserName");
                        FormsAuthentication.SignOut();
                        return(false);
                    }

                    session["SignInTimestamp"]    = DateTime.Now;
                    session["LogOnId"]            = signInView.LoginId;
                    session["UserId"]             = signInView.UserId;
                    session["Culture"]            = signInView.Culture;
                    session["UserName"]           = signInView.UserName;
                    session["FullUserName"]       = signInView.FullName;
                    session["Role"]               = signInView.Role;
                    session["IsSystem"]           = signInView.IsSystem;
                    session["IsAdmin"]            = signInView.IsAdmin;
                    session["OfficeCode"]         = signInView.OfficeCode;
                    session["OfficeId"]           = signInView.OfficeId;
                    session["NickName"]           = signInView.NickName;
                    session["OfficeName"]         = signInView.OfficeName;
                    session["RegistrationDate"]   = signInView.RegistrationDate;
                    session["CurrencyCode"]       = signInView.CurrencyCode;
                    session["RegistrationNumber"] = signInView.RegistrationNumber;
                    session["PanNumber"]          = signInView.PanNumber;
                    session["AddressLine1"]       = signInView.AddressLine1;
                    session["AddressLine2"]       = signInView.AddressLine2;
                    session["Street"]             = signInView.Street;
                    session["City"]               = signInView.City;
                    session["State"]              = signInView.State;
                    session["Country"]            = signInView.Country;
                    session["ZipCode"]            = signInView.ZipCode;
                    session["Phone"]              = signInView.Phone;
                    session["Fax"]   = signInView.Fax;
                    session["Email"] = signInView.Email;
                    session["Url"]   = signInView.Url;

                    SetCulture();


                    return(true);
                }
                catch (DbException ex)
                {
                    Log.Warning("Cannot set session for user with SingIn #{SigninId}. {Exception}.", signInId, ex);
                }
            }

            return(false);
        }
Example #42
0
    public static Cart GetCartFromSession(HttpSessionState Session)
    {
        Cart cart = null;
        int site_id;
        bool logged_in = CartUsers.IsUserLoggedIn(Session);
        string user_id = logged_in ? CartUsers.GetUserName(Session) : "";
        if (Session[Constants.SessionKeys.SITE_ID] != null)
        {
            if (Int32.TryParse((string)Session[Constants.SessionKeys.SITE_ID], out site_id) == false)
            {
                throw new CartException("Could not find SiteID in current session");
            }
        }
        else
        {
            throw new CartException("Could not find SiteID in current session");
        }

        // This is a three step process
        // We do this because the current context of the shopping cart, should always override the saved context of the shopping cart.
        // This makes most sense in this scenario:
        /* So say you were browsing the site without logging in, and you've added a bunch of items to your cart.
           Now, you don't hit checkout or anything, but instead decide to log in to your account you remember you had.
           Should the cart you just created override any existing (saved) cart in the user account? */

        // 0. If a user is logged in, and the current session doesn't have any items in it, and a saved session exists, use it.
        if (logged_in)
        {
            cart = Cart.GetCartByUserID(site_id, Session.SessionID);
            if (cart != null && cart.IsLoaded && cart.HasItems == false)
            {
                cart = Cart.GetCartByUserID(site_id, user_id);
                if (cart != null && cart.IsLoaded)
                {
                    return cart;
                }
            }
        }

        // 1. If one exists in the current session, and it actually has items in it, use it. In this case, if the username has not been updated, update it.
        cart = Cart.GetCartByUserID(site_id, Session.SessionID);
        if (cart != null && cart.IsLoaded)
        {
            if (logged_in && cart.UserId == Session.SessionID)
            {
                CartDB db = new CartDB();
                db.CartUpdateUserId(cart.CartId, user_id);
            }
            cart.Refresh();
            return cart;
        }

        // 2. If this is not the case, try loading from the user id.
        if (logged_in)
        {
            cart = Cart.GetCartByUserID(site_id, user_id);
            if (cart != null && cart.IsLoaded)
            {
                return cart;
            }
        }

        // 3. If we still do not have one, just create a new one. If logged in, use the current username, if not, use the session id
        cart = Cart.CreateNew(site_id, logged_in ? user_id : Session.SessionID);
        if (cart != null && cart.IsLoaded)
        {
            return cart;
        }

        throw new CartException("Could not retrieve a cart from the current session");
    }
Example #43
0
        /// <summary>
        /// Log in as a new session.  If success, regardless of expired password, set context.User to the user instance.
        /// If failed, it will throw exception with message in the language specified in context.CurrentLanguage.
        /// The user with expired password, the caller must force the user to change password.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="session"></param>
        /// <param name="application"></param>
        /// <param name="ipAddress"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="userMustChangePassword"></param>
        /// <returns>last log in time of the user</returns>
        //public static void Login(BizPortalSessionContext context, HttpSessionState session, HttpApplicationState application,
        //                            iSystem systemApplication, String ipAddress, String userName, String password, int systemID,
        //                            out bool userMustChangePassword, bool fakeLogin = false)
        public static void Login(BizPortalSessionContext context, HttpSessionState session, HttpApplicationState application, String ipAddress,
                                 String userName, String password, out bool userMustChangePassword)
        {
            userMustChangePassword = false;

            try
            {
                BizPortalConfiguration config = GetConfiguration(context, context.MySystem.SystemID);
                if (config.ID != BizPortalConfiguration.CurrentConfiguration.ID)
                {
                    BizPortalConfiguration.CurrentConfiguration = config;
                    //BizPortalConfiguration.CurrentConfiguration.Security.WebSessionTimeoutValueInMinutes = config.Security.WebSessionTimeoutValueInMinutes;
                    //BizPortalConfiguration.CurrentConfiguration.Security.PasswordPolicy.MinPasswordLength = config.Security.PasswordPolicy.MinPasswordLength;
                    //BizPortalConfiguration.CurrentConfiguration.Security.PasswordPolicy.MaxPasswordLength = config.Security.PasswordPolicy.MaxPasswordLength;
                    //BizPortalConfiguration.CurrentConfiguration.Security.MaxConsecutiveFailedLogonAttempts = config.Security.MaxConsecutiveFailedLogonAttempts;
                    //BizPortalConfiguration.CurrentConfiguration.Security.MaxDaysOfInactivity = config.Security.MaxDaysOfInactivity;
                    //BizPortalConfiguration.CurrentConfiguration.Security.MaxUsernameLength = config.Security.MaxUsernameLength;
                }
            }
            catch (Exception)
            {
                throw new Exception("เกิดข้อผิดพลาดในการติดต่อฐานข้อมูลกรุณาติดต่อผู้ดูแลระบบ");
            }

            MemberUser  mu          = null;
            LoginResult loginResult = LoginResult.IncorrectPassword;

            try
            {
                User user;
                loginResult = context.MySystem.Login(context, userName, password, out user, out userMustChangePassword);
                mu          = (MemberUser)context.PersistenceSession.GetSessionImplementation().PersistenceContext.Unproxy(user);
            }
            catch (Exception exc)
            {
                LogFailureSession(context, session.SessionID, userName, mu, exc.ToString());
                throw exc;
            }

            int    invalidPasswordAttemptLimit;
            string message = null;

            switch (loginResult)
            {
            case LoginResult.AuthenticationSuccess:
                if (mu.IsDisable)
                {
                    message = Messages.Security.UserIsDisable.Format(context.CurrentLanguage.Code);
                    LogFailureSession(context, session.SessionID, userName, mu, message);
                    throw new Exception(Messages.Security.UserIsDisableDisplayScreen.Format(context.CurrentLanguage.Code));
                }
                invalidPasswordAttemptLimit = context.Configuration.Security.MaxConsecutiveFailedLogonAttempts;
                if (mu.NumberOfConsecutiveFailedLoginAttemptsReachesLimit(invalidPasswordAttemptLimit))
                {
                    message = Messages.Security.UserIsSuspended.Format(context.CurrentLanguage.Code, invalidPasswordAttemptLimit);
                    LogFailureSession(context, session.SessionID, userName, mu, message);
                    SendSMSToSelfAuthenticatedUser(context, mu, message);
                    throw new Exception(Messages.Security.UserIsConsecutiveFailedLoginDisplayScreen.Format(context.CurrentLanguage.Code));
                }
                else if (mu.HasBeenInactiveTooLong(context.Configuration.Security.MaxDaysOfInactivity))
                {
                    message = Messages.Security.UserIsInactive.Format(context.CurrentLanguage.Code, context.Configuration.Security.MaxDaysOfInactivity);
                    LogFailureSession(context, session.SessionID, userName, mu, message);
                    SendSMSToSelfAuthenticatedUser(context, mu, message);
                    throw new Exception(Messages.Security.UserIsInactiveDisplayScreen.Format(context.CurrentLanguage.Code));
                }

                //Check for login collision
                var userId = mu.ID;

                var activeUsers = (Dictionary <long, string>)application["ActivingUsers"];
                if (activeUsers.ContainsKey(userId))
                {
                    ForceLogout(context, application, mu);
                    LogFailureSession(context, session.SessionID, userName, mu, Messages.Security.MultipleLogon.Format(context.CurrentLanguage.Code));
                    throw new Exception(Messages.Security.MultipleLogon.Format(context.CurrentLanguage.Code));
                }
                if (activeUsers.ContainsValue(session.SessionID))
                {
                    while (activeUsers.ContainsValue(session.SessionID))
                    {
                        foreach (var pair in activeUsers)
                        {
                            if (session.SessionID.Equals(pair.Value))
                            {
                                ForceLogoutForDIfferenceUserSameSession(context, application, mu);
                                break;
                            }
                        }
                    }
                }

                activeUsers.Add(userId, session.SessionID);
                break;

            case LoginResult.IncorrectPassword:
                invalidPasswordAttemptLimit = context.Configuration.Security.MaxConsecutiveFailedLogonAttempts;
                if (mu.NumberOfConsecutiveFailedLoginAttemptsReachesLimit(invalidPasswordAttemptLimit))
                {
                    message = Messages.Security.UserIsSuspended.Format(context.CurrentLanguage.Code, invalidPasswordAttemptLimit);
                }
                else
                {
                    message = Messages.Security.IncorrectPassword.Format(context.CurrentLanguage.Code, mu.ConsecutiveFailedLoginCount, invalidPasswordAttemptLimit);
                }

                LogFailureSession(context, session.SessionID, userName, mu, message);
                SendSMSToSelfAuthenticatedUser(context, mu, message);
                throw new Exception(Messages.Security.PasswordIsInvalidCode.Format(context.CurrentLanguage.Code));

            case LoginResult.UsernameNotFound:
                LogFailureSession(context, session.SessionID, userName, mu, Messages.Security.UsernameIsInvalidCode.Format(context.CurrentLanguage.Code));
                throw new Exception(Messages.Security.UsernameIsInvalidCode.Format(context.CurrentLanguage.Code));

            default:
                LogFailureSession(context, session.SessionID, userName, mu, Messages.Security.LoginFailed.Format(context.CurrentLanguage.Code));
                throw new Exception(Messages.Security.LoginFailed.Format(context.CurrentLanguage.Code));
            }

            context.User = mu;
            InitializeSession(context, mu, session);

            #region Old
            //}
            //catch (Exception exc)
            //{
            //    LogFailure(context, session, systemApplication, ipAddress, userName, mu, exc.ToString());
            //    if (exc.Message != Messages.Security.MultipleLogon.Format(context.CurrentLanguage.Code) && mu != null)
            //    {
            //        string loginFailed = Messages.Security.UsernameIsInvalidCode.Format(context.CurrentLanguage.Code, mu.ConsecutiveFailedLoginCount);
            //        if (mu is SelfAuthenticatedUser)
            //        {
            //            string messageSMS = "";

            //            if (exc.Message == Messages.Security.UserIsSuspendedForTooManyConsecutiveLoginFailures.Format(context.CurrentLanguage.Code,
            //                                               context.Configuration.Security.MaxConsecutiveFailedLogonAttempts))
            //            {
            //                messageSMS = Messages.Security.UserIsSuspendedForTooManyConsecutiveLoginFailures.Format(context.CurrentLanguage.Code,
            //                                               context.Configuration.Security.MaxConsecutiveFailedLogonAttempts);
            //            }
            //            else if (mu.ConsecutiveFailedLoginCount >= context.Configuration.Security.MaxConsecutiveFailedLogonAttempts)//by kittikun
            //            {
            //                messageSMS = Messages.Security.UserIsSuspendedForTooManyConsecutiveLoginFailures.Format(context.CurrentLanguage.Code,
            //                                               context.Configuration.Security.MaxConsecutiveFailedLogonAttempts);
            //            }
            //            else if (exc.Message == Messages.Security.UserHasBeenInactiveLongerThanLimit.Format(context.CurrentLanguage.Code, context.Configuration.Security.MaxDaysOfInactivity))
            //            {
            //                messageSMS = Messages.Security.UserHasBeenInactiveLongerThanLimit.Format(context.CurrentLanguage.Code,
            //                                                context.Configuration.Security.MaxDaysOfInactivity);
            //            }
            //            else
            //            {
            //                messageSMS = Messages.Security.UserIsDisableForExcessiveConsecutiveFailedLoginUnLimit.Format(
            //                    context.CurrentLanguage.Code,
            //                    mu.ConsecutiveFailedLoginCount,
            //                    context.Configuration.Security.MaxConsecutiveFailedLogonAttempts);
            //            }

            //            try
            //            {
            //                Adapter.SendLoginFailed(context, CIMB.Adapter.CIMBSMS.SmsLanguageType.TH, mu.MobilePhoneNumber, messageSMS);
            //            }
            //            catch (Exception ex)
            //            {
            //                context.Log(SystemFunctionID.Login.ID, 0, 0, ActionLog.SystemFunction.SendSMSFailed, string.Format("<b>ส่ง SMS ไม่สำเร็จ</b><br /><b>ข้อผิดพลาด</b> : {0}", ex.Message));
            //            }
            //        }
            //        context.Log(SystemFunctionID.Login.ID, 0, 0, SystemFunctionID.Login.Action.Failed, string.Format("<b>เข้าสู่ระบบไม่สำเร็จ</b><br /><b>ชื่อเข้าใช้งาน</b> : {0}<br /><b>ข้อผิดพลาด</b> : {1}", userName, exc.Message));

            //        throw;
            //    }
            //context.Log(SystemFunctionID.Login.ID, 0, 0, SystemFunctionID.Login.Action.Failed, string.Format("<b>เข้าสู่ระบบไม่สำเร็จ</b><br /><b>ชื่อเข้าใช้งาน</b> : {0}<br /><b>ข้อผิดพลาด</b> : {1}", userName, exc.Message));
            //throw exc;
            //}
            #endregion Old
        }
Example #44
0
 public abstract Users CurrentUser(HttpSessionState session);
Example #45
0
        public SessionStateContainer(HttpSessionState persistedDataContainer, string contextId)
        {
            DataContainer = persistedDataContainer;

            ContextId = contextId;
        }
Example #46
0
 public abstract bool Login(string username, string password, HttpSessionState session);
Example #47
0
        public void AddSession(string name, object value)
        {
            HttpSessionState state = this.HttpContext.Items["AspSession"] as HttpSessionState;

            state.Add(name, value);
        }
Example #48
0
 public override Users CurrentUser(HttpSessionState session)
 {
     return null;
 }
Example #49
0
        public IHttpActionResult AddToCart(CartDto dto)
        {
            HttpSessionState session = HttpContext.Current.Session;

            List <CartViewModel> carts;

            if (dto.Id == null)
            {
                return(BadRequest());
            }

            var product = _unitOfWork.Products.Get((int)dto.Id);

            if (product == null)
            {
                return(NotFound());
            }

            var productDiscount = _unitOfWork.ProductDiscounts.GetProductDiscountNotDeleted()
                                  .SingleOrDefault(p => p.ProductId == product.Id);

            if (productDiscount != null)
            {
                product.Price = product.Price - (product.Price * productDiscount.Discount / 100);
            }
            var cart = new CartViewModel
            {
                ProductId = product.Id,
                Name      = product.Name,
                ImagePath = product.ImagePath,
                Price     = (decimal)product.Price,
                Quantity  = int.Parse(dto.Quantity ?? "1")
            };

            if (session["cart"] == null)
            {
                carts = new List <CartViewModel>();
                carts.Add(cart);
                session["cart"] = carts;
            }
            else
            {
                carts = session["cart"] as List <CartViewModel>;

                //To see if this item exsists before
                if (carts != null)
                {
                    var productInCart = carts.ToList().FirstOrDefault(c => c.ProductId == product.Id);

                    if (productInCart == null)
                    {
                        carts.Add(cart);
                    }
                    else
                    {
                        productInCart.Quantity += cart.Quantity;
                    }
                }

                session["cart"] = carts;
            }

            return(Ok());
        }
Example #50
0
        private static void InitializeSession(BizPortalSessionContext context, MemberUser user, HttpSessionState session)
        {
            context.StartNewSession(user, session.SessionID);

            UserSession userSession = context.UserSession;

            session["UserPrivilegeLevel"]        = context.User.GetEffectivePrivilegeLevel(context.MySystem);
            session["ASP.modules_selectip_aspx"] = 0;

            MySiteMapProvider siteMap = MenuManager.BuildMenu(context, context.MySystem.GetRootMenus(context));

            session["MenuProvider"] = siteMap;

            MergeUserRoles(context, session);
        }
 public static bool IsLoggedOut(this HttpSessionState instance)
 {
     return(instance[Common.SessionVariables.IsLogout] == true.ToString());
 }
Example #52
0
 public static void StoreSelectedItemsInSession(ListBox lb, HttpSessionState Session, String Key)
 {
     List<ListItem> list = new List<ListItem>();
     foreach (ListItem item in lb.Items)
     {
       list.Add(item);
     }
     Session[Key] = list;
 }
 public static bool SetIsLoggedOut(this HttpSessionState instance, bool value)
 {
     instance[Common.SessionVariables.IsLogout] = value.ToString();
 }
Example #54
0
 public SecurityService(IUserService users, HttpSessionState session = null)
 {
     _users   = users;
     _session = session ?? HttpContext.Current.Session;
 }
Example #55
0
 public SessionManager(HttpSessionState session)
 {
     this._currentSession = session;
 }
Example #56
0
		public static void RaiseSessionEnd (IHttpSessionState session, Object eventSource, EventArgs eventArgs)
		{
			HttpSessionState state = new HttpSessionState (session);
			HttpApplicationFactory.InvokeSessionEnd (state, eventSource, eventArgs);
		}
Example #57
0
        /// <summary>
        /// Stores the querystring parameters found in the request for
        /// later use in the discovery process.
        /// </summary>
        /// <param name="context">HttpContext containing session, request, and response objects.</param>
        /// <returns>
        /// Returns the NameValueCollection containing the parameters stored
        /// into the session from the last invocation of the method
        /// StoreRequestParameters.
        /// </returns>
        public static NameValueCollection RetrieveRequestParameters(HttpContext context)
        {
            HttpSessionState session = context.Session;

            return((NameValueCollection)session[IdentityProviderDiscoveryUtils.OriginalParametersSessionAttribute]);
        }
 public EditChannelWeightingProcessor(HttpSessionState session) : base(session)
 {
 }
Example #59
0
 public SessionStateContainer(HttpSessionState persistedDataContainer)
     : this(persistedDataContainer, "DEFAULT_CONTEXT")
 {
 }