public static void setUserLoggedOff(HttpSessionStateBase Session)
 {
     // Overrides data if exists
     Session.Add("isUserLoggedOn", false);
     Session.Add("userID", 0);
     Session.Add("isCurrentUserManager", false);
 }
        public void GetItem()
        {
            _session.Add(GetSessionKeyForFunctionState(), _functionState);

            var functionStateManager = new WxeFunctionStateManager(_session);
            WxeFunctionState actual  = functionStateManager.GetItem(_functionState.FunctionToken);

            Assert.That(actual, Is.SameAs(_functionState));
        }
예제 #3
0
        public ActionResult SignIn([Bind(Include = "email,password")] Account account)
        {
            db.Configuration.ProxyCreationEnabled = false;
            if (ModelState.IsValid)
            {
                string checkEmail    = account.email;
                string checkPassword = account.password;

                //get user's information from database
                Account checkAccount = db.Accounts.Where(a => a.email.Equals(checkEmail) && a.role != 0).FirstOrDefault();
                //check is exsisted account
                if (checkAccount != null)
                {
                    //check if password matches
                    if (BCrypt.Net.BCrypt.Verify(checkPassword, checkAccount.password))
                    {
                        HttpSessionStateBase session = HttpContext.Session;
                        //add user to session
                        session.Add("user", checkAccount.userID);
                        session.Add("role", checkAccount.role);
                        //reload cart
                        if (Session["cart"] != null)
                        {
                            CartsController          cartsController = new CartsController();
                            int                      userId          = Int32.Parse(Session["user"].ToString());
                            Dictionary <string, int> cookieCart      = (Dictionary <string, int>)Session["cart"];
                            cartsController.AddToCartWhenLogin(cookieCart, userId);
                            Session.Remove("cart");
                        }
                        return(RedirectToRoute(new {
                            controller = "Home",
                            action = "Index",
                            id = UrlParameter.Optional
                        }));
                    }
                    else
                    {
                        ViewBag.Message   = "Wrong Password!";
                        ViewData["email"] = account.email;
                    }
                }
                else
                {
                    ViewBag.Message = "Not exsisted account!";
                }
            }
            return(View());
        }
예제 #4
0
        public void SaveCustomerToSession(CustomerModel model)
        {
            HttpSessionStateBase session = HttpContext.Session;

            session.Add("SelectedCustomerId", model.Customer_ID);
            return;
        }
        public void ProcessRequest(HttpContext context)
        {
            _logger.Info($"PL.{nameof(UserAjaxHandler)}: Request received");

            IEnumerator <User> enumerator = HttpSession["Enumerator"] as IEnumerator <User>;

            if (enumerator == null)
            {
                _logger.Info($"PL.{nameof(UserAjaxHandler)}: Creating the enumerator");

                string searchStr = (string)HttpSession["Search"];

                enumerator = _userBll.GetAllUsers()
                             .Where(user => string.IsNullOrEmpty(searchStr) ? true : Regex.IsMatch(user.Id.ToString(), searchStr.ToLower()) ||
                                    Regex.IsMatch(user.Login.ToLower(), searchStr.ToLower()) ||
                                    Regex.IsMatch(user.Name.ToLower(), searchStr.ToLower()))
                             .GetEnumerator();

                HttpSession.Add("Enumerator", enumerator);

                _logger.Info($"PL.{nameof(UserAjaxHandler)}: The enumerator was created");
            }

            var list = GetList(enumerator, 15);

            context.Response.ContentType = "application/json";

            context.Response.Write(JsonConvert.SerializeObject(list));

            _logger.Info($"PL.{nameof(UserAjaxHandler)}: Sent to client a Json");
        }
예제 #6
0
        /// <summary>
        /// Establece el usuario activo (logueado) en la session
        /// </summary>
        /// <param name="session">session actual</param>
        /// <param name="data">objeto a guardar en la session temporalmente</param>
        internal static Guid Push(HttpSessionStateBase session, object data)
        {
            var id = Guid.NewGuid();

            session.Add(PUSHPOP_DATA + id.ToString(), data);
            return(id);
        }
예제 #7
0
        /// <summary>
        /// 登录或注册成功时,保存的用户信息
        /// </summary>
        /// <param name="UserName">用户名</param>
        /// <param name="Session">请求的Session状态对象</param>
        public void LoginSuccess(string UserName, HttpSessionStateBase Session)
        {
            tb_UsersByCustomer MyUsersByCustomer = null;
            tb_ZY_Sex          MyZY_Sex          = null;

            using (DB_BBSEntities db = new DB_BBSEntities())
            {
                MyUsersByCustomer = db.tb_UsersByCustomer.Where(W => W.UserName == UserName).First();
                MyZY_Sex          = db.tb_ZY_Sex.Where(W => W.ID == MyUsersByCustomer.SexID).First();
            }
            if (MyUsersByCustomer != null)
            {
                LoginStatusEntity LSE = new LoginStatusEntity
                {
                    ID        = MyUsersByCustomer.ID,
                    UserName  = MyUsersByCustomer.UserName,
                    NickName  = MyUsersByCustomer.NickName,
                    SexID     = MyUsersByCustomer.SexID,
                    Sex       = MyZY_Sex.Content,
                    Age       = MyUsersByCustomer.Age,
                    PhotoUrl  = MyUsersByCustomer.PhotoUrl,
                    Email     = MyUsersByCustomer.Email,
                    Fatieshu  = MyUsersByCustomer.Fatieshu ?? 0,
                    Huitieshu = MyUsersByCustomer.Huitieshu ?? 0
                };
                Session.Add("LoginSuccess", LSE);
            }
        }
예제 #8
0
        public static int InvalidPasswordAttempts(HttpSessionStateBase session, int increment = 0)
        {
            if (session == null)
            {
                return(0);
            }

            int retVal = 0;

            if (session["InvalidPasswordAttempts"] == null)
            {
                retVal = retVal + increment;
                session.Add("InvalidPasswordAttempts", retVal);
            }
            else
            {
                retVal = Conversion.TryCastInteger(session["InvalidPasswordAttempts"]) + increment;
                session["InvalidPasswordAttempts"] = retVal;
            }


            if (increment > 0)
            {
                Log.Warning("{Count} Invalid attempt to sign in from {Host}/{IP} using {Browser}.", retVal,
                            GetUserHostAddress(), GetUserIpAddress(), GetBrowser().Browsers);
            }

            return(retVal);
        }
예제 #9
0
        public static void RefreshLoggedInUserSession(HttpSessionStateBase currentSession)
        {
            User   currentUser = null;
            string username    = LoggedInUserUsername(currentSession);

            if (username == null)
            {
                return;
            }
            using (var usersRepository = new UsersRepository(new MyTubeDBEntities()))
            {
                currentUser = usersRepository.GetUserByUsername(username);
            }
            if (currentUser == null)
            {
                currentSession.Abandon();
            }
            else
            {
                var currentUserForSession = new UserSessionModel
                {
                    Username = currentUser.Username,
                    UserType = currentUser.UserType,
                    Blocked  = currentUser.Blocked
                };
                currentSession.Add(loggedInUser, currentUserForSession);
            }
        }
예제 #10
0
파일: WebPage.cs 프로젝트: yangwuhan/Wx
        /* 微信授权后跳转到的页面中通过code获取用户信息
         */
        public void SecondPage_RedirectUrl_GetUserInfoByCode(HttpSessionStateBase session, HttpResponseBase response, string code)
        {
            string url = @"https://api.weixin.qq.com/sns/oauth2/access_token" +
                         "?appid=" + _app_id +
                         "&secret=" + _app_secret +
                         "&code=" + code +
                         "&grant_type=authorization_code";

            try
            {
                if (string.IsNullOrEmpty(code))
                {
                    throw new Exception("code为空");
                }
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage res = httpClient.GetAsync(url).Result;
                //string statusCode = response.StatusCode.ToString();
                if (res.IsSuccessStatusCode)
                {
                    string  result = res.Content.ReadAsStringAsync().Result;
                    JObject o      = JObject.Parse(result);
                    JToken  jt_errcode;
                    if (o.TryGetValue("errcode", out jt_errcode))
                    {
                        throw new Exception("微信服务器返回错误:【" + o["errcode"].ToString() + "】" + o["errmsg"].ToString());
                    }
                    else
                    {
                        WxWebApiRetAccessToken at = new WxWebApiRetAccessToken();
                        at.access_token  = o["access_token"].ToString();
                        at.expires_in    = int.Parse(o["expires_in"].ToString());
                        at.refresh_token = o["refresh_token"].ToString();
                        at.openid        = o["openid"].ToString();
                        at.scope         = o["scope"].ToString();
                        for (int i = 0; i < session.Keys.Count; ++i)
                        {
                            if (session.Keys[i] == _session_key_for_openid)
                            {
                                session.Remove(_session_key_for_openid);
                                break;
                            }
                        }
                        session.Add(_session_key_for_openid, at.openid);
                        response.Redirect(_root_url);
                        response.End();
                    }
                }
                else
                {
                    throw new Exception("服务器返回:" + res.StatusCode.ToString());
                }
            }
            catch (System.Exception ex)
            {
                response.Redirect(_error_url + "?error=" + HttpUtility.UrlEncode(ex.Message));
                response.End();
            }
        }
예제 #11
0
        public ActionResult ChangeSoftware_req()
        {
            HttpSessionStateBase session = HttpContext.Session;
            Tbl_User             user    = _userService.GetUserById(Convert.ToInt32(session["UserID"]));

            session.Add("Section_ID", user.Section_ID);
            return(View());
        }
예제 #12
0
 public static void Set(this HttpSessionStateBase state, string key, object value)
 {
     if (string.IsNullOrEmpty(key))
     {
         return;
     }
     state.Add(key, value);
 }
        public void store_the_environment_name_in_the_HttpContextSession_collection()
        {
            var userName = _user.UserName;

            Isolate.WhenCalled(() => LoginServices.IsLoggedIn(userName)).WillReturn(true);

            SetEnvironmentOnController();
            _controller.Login(_user);
            Isolate.Verify.WasCalledWithAnyArguments(() => _sessionState.Add(LoginController.EnvironmentSetting, Testgenform));
        }
        public void SignIn(AdminUser adminUser, HttpSessionStateBase session)
        {
            if (adminUser == null)
            {
                throw new ArgumentNullException("Invalid authentication");
            }

            formsAuthentication.SetAuthCookie(adminUser.Name, false);
            session.Add("adminUser", adminUser);
        }
예제 #15
0
 /// <summary>
 /// Update a value in the session or create it if it does not exist.
 /// </summary>
 /// <param name="key">Item's key</param>
 /// <param name="value">Value of session item</param>
 private void SetSession(string key, object value)
 {
     if (CurrentSession[key] == null)
     {
         CurrentSession.Add(key, value);
     }
     else
     {
         CurrentSession[key] = value;
     }
 }
예제 #16
0
 public static void SetDataToSession <T>(this HttpSessionStateBase session, string key, object value)
 {
     if (session[key] != null)
     {
         session[key] = value;
     }
     else
     {
         session.Add(key, value);
     }
 }
        private static Dictionary <string, CacheMemento> GetCache(this HttpSessionStateBase session, ObjectFlag flag)
        {
            var objs = (Dictionary <string, CacheMemento>)session[Bucket[(int)flag]];

            if (objs == null)
            {
                objs = new Dictionary <string, CacheMemento>();
                session.Add(Bucket[(int)flag], objs);
            }
            return(objs);
        }
예제 #18
0
        public static void SetCurrentUserSessionInfo(HttpRequestBase Request, HttpSessionStateBase Session)
        {
            if (Request.IsAuthenticated)
            {
                using (var db1 = new ApplicationDbContext())
                {
                    // get user
                    var user = (from u in db1.Users
                                where u.UserName.Equals(Request.RequestContext.HttpContext.User.Identity.Name)
                                select new
                    {
                        Name = u.TitleID + " " + u.Intials + " " + u.Surname,
                        Id = u.Id,
                        InstitutionID = u.Institution.InstitutionID
                    }).First();

                    // set session info
                    Session.Add("userName", user.Name);
                    Session.Add("userID", user.Id);
                    Session.Add("institutionID", user.InstitutionID);
                }
            }
        }
예제 #19
0
        public virtual bool AuthenticationDone(AuthenticationConclusion conclusion)
        {
            bool CST_verified = CST_Ops.Certify(conclusion);

            if (CurrentSession["UserID"] != null)
            {
                CurrentSession["UserID"] = CST_verified?conclusion.SessionUID:"";
            }
            else
            {
                CurrentSession.Add("UserID", CST_verified ? conclusion.SessionUID : "");
            }
            return(CST_verified);
        }
        private void CreateOrUpdateKey(HttpSessionStateBase session)
        {
            var data = session[EncryptFieldData] as Tuple <byte[], byte[]>;

            if (data == null)
            {
                provider.GenerateKey();
                provider.GenerateIV();
                data = new Tuple <byte[], byte[]>(provider.Key, provider.IV);
                session.Add(EncryptFieldData, data);
            }

            key = data.Item1;
            iv  = data.Item2;
        }
예제 #21
0
        public void setSearchSession(HttpRequestBase request, HttpSessionStateBase session)
        {
            NameValueCollection queryStringOriginal = request.QueryString;
            String isSearch            = queryStringOriginal.Get("search");
            String queryString         = "";
            RouteValueDictionary route = new RouteValueDictionary();

            if ("true".Equals(isSearch))
            {
                queryString = queryStringOriginal.ToString();
                String[] keys = queryStringOriginal.AllKeys;
                foreach (String key in keys)
                {
                    route.Add(key, queryStringOriginal.Get(key));
                }
            }
            else
            {
                queryString = "";
                route.Clear();
            }
            session.Add("searchString", queryString);
            session.Add("searchMap", route);
        }
예제 #22
0
        public static Cart GetCartObject(HttpSessionStateBase session)
        {
            Cart cart = null;

            if (session["cart"] == null)
            {
                cart = new Cart();
                session.Add("cart", cart);
            }
            else
            {
                cart = session["cart"] as Cart;
            }
            return(cart);
        }
예제 #23
0
        /// <summary> Adds the <paramref name="functionState"/> to the collection. </summary>
        /// <param name="functionState">
        ///   The <see cref="WxeFunctionState"/> to be added. Must not be <see langword="null"/> or aborted.
        /// </param>
        public void Add(WxeFunctionState functionState)
        {
            ArgumentUtility.CheckNotNull("functionState", functionState);
            if (functionState.IsAborted)
            {
                throw new ArgumentException("An aborted WxeFunctionState cannot be added to the collection.", "functionState");
            }

            lock (_lockObject)
            {
                _functionStates.Add(
                    functionState.FunctionToken,
                    new WxeFunctionStateMetaData(functionState.FunctionToken, functionState.Lifetime, DateTime.Now));
                _session.Add(GetSessionKeyForFunctionState(functionState.FunctionToken), functionState);
            }
        }
예제 #24
0
        /// <summary>
        /// 创建验证证并记录在Session中
        /// </summary>
        /// <param name="session"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static byte[] CreateVerifyImage(HttpSessionStateBase session, int length)
        {
            if (length < 2)
            {
                length = 2;
            }
            if (length > 10)
            {
                length = 10;
            }
            string code = CreateVerifyCode(length);

            session.Remove(VerifyCode);
            session.Add(VerifyCode, code);
            return(CreateVerifyGraphic(code));
        }
        /// <summary>
        /// Ensures the right type is set and returned from session
        /// </summary>
        /// <param name="Session"></param>
        /// <param name="sessionVarName"></param>
        /// <param name="methodsetObject">method where the T value is set to the session with key param:sessionVarName. If null then automatically loads value from storage</param>
        /// <returns></returns>
        public bool use(HttpSessionStateBase Session, out T savedObject, string sessionVarName, useSessionFunc methodsetObject)
        {
            bool newData;

            savedObject = default(T);
            object sessionVar = Session[sessionVarName];

            if ((sessionVar == null || !(sessionVar.GetType() == typeof(T))) && methodsetObject != null)
            {
                newData = false;
                methodsetObject(out savedObject); // set saved to value
                Session.Add(sessionVarName, savedObject);
            }
            else
            {
                newData     = false;
                savedObject = (T)Session[sessionVarName];
            }

            return(newData);
        }
예제 #26
0
        /// <summary>
        /// 登录或注册成功时,保存的用户信息
        /// </summary>
        /// <param name="UserName">用户名</param>
        /// <param name="Session">请求的Session状态对象</param>
        public void LoginSuccess(string UserName, HttpSessionStateBase Session)
        {
            tb_UsersBySystem MyUsersBySystem = null;

            using (DB_BBSEntities db = new DB_BBSEntities())
            {
                MyUsersBySystem = db.tb_UsersBySystem.Where(W => W.UserName == UserName).First();
            }
            if (MyUsersBySystem != null)
            {
                LoginStatusAdminEntity LSAE = new LoginStatusAdminEntity
                {
                    ID       = MyUsersBySystem.ID,
                    RoleID   = MyUsersBySystem.RoleID,
                    UserName = MyUsersBySystem.UserName,
                    NickName = MyUsersBySystem.NickName,
                    Email    = MyUsersBySystem.Email
                };
                Session.Add("LoginAdminSuccess", LSAE);
            }
        }
예제 #27
0
 public ActionResult CheckLogin([Bind(Include = "email,password")] Account account)
 {
     if (ModelState.IsValid)
     {
         string         checkEmail    = account.email;
         string         checkPassword = account.password;
         List <Account> list          = db.Accounts.Where(a => a.email.Equals(checkEmail)).ToList();
         if (list.Count > 0)
         {
             if (BCrypt.Net.BCrypt.Verify(checkPassword, list[0].password))
             {
                 HttpSessionStateBase session = HttpContext.Session;
                 session.Add("user", list[0].userID);
                 return(RedirectToRoute(new {
                     controller = "Home", action = "Index", id = UrlParameter.Optional
                 }));
             }
         }
     }
     return(RedirectToAction("SignIn"));
 }
예제 #28
0
        /// <summary>
        /// 使用给定的用户名和密码对给定的会话进行登录验证。
        /// </summary>
        /// <param name="session">用户会话。</param>
        /// <param name="username">用户名。</param>
        /// <param name="password">密码。</param>
        /// <exception cref="ArgumentNullException"/>
        public static bool Authorize(HttpSessionStateBase session, string username, string password)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return(false);
            }

            if (UserAuthorization.CheckAuthorization(username, password))
            {
                // 登录验证成功。
                session.Add(SessionUsername, username);
                RenewSession(session);
                return(true);
            }
            else
            {
                // 登录验证失败。
                return(false);
            }
        }
예제 #29
0
        /// <summary>
        /// 返回用户是否已登录,如果已登录返回true,否则返回false
        /// </summary>
        /// <param name="httpContext">过滤器上下文</param>
        /// <returns>如果已登录返回true,否则返回false</returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
#if DEBUG
            string username = WebConfigurationManager.AppSettings["testUser"];
            HttpSessionStateBase Session = httpContext.Session;
            FormsAuthentication.SetAuthCookie(username, false);
            string guid = Guid.NewGuid().ToString();
            Session.Add("loginGuid", guid);
            lock (SingleUserAttribute.UserMap)
            {
                if (SingleUserAttribute.UserMap.ContainsKey(username))
                {
                    SingleUserAttribute.UserMap[username] = guid;
                }
                else
                {
                    SingleUserAttribute.UserMap.Add(username, guid);
                }
            }
            return(true);
#else
            return(httpContext.User.Identity.IsAuthenticated);
#endif
        }
예제 #30
0
 public static void setUserLoggedOn(HttpSessionStateBase Session, int userID, Boolean isManager)
 {
     Session.Add("isUserLoggedOn", true);
     Session.Add("userID", userID);
     Session.Add("isCurrentUserManager", isManager);
 }