用户登录

用户登录:
        [HttpPost]
        [CustomAllowAnonymous]//允许匿名登录(这个是自定义的)
        public ActionResult Login(string name, string password, string verify)
        {
            string formName = base.HttpContext.Request.Form["Name"];

            var result = base.HttpContext.Login(name, password, verify);
            if (result == UserManager.LoginResult.Success)
            {
                if (base.HttpContext.Session["CurrentUrl"] != null)
                {
                    string url = base.HttpContext.Session["CurrentUrl"].ToString();
                    base.HttpContext.Session.Remove("CurrentUrl");
                    return base.Redirect(url);
                }
                else
                    return base.Redirect("/Home/Index");
            }
            else
            {
                ModelState.AddModelError("failed", result.GetRemark());
                return View();
            }
        }

登录验证代码
public static class UserManager
    {
        private static Logger logger = new Logger(typeof(UserManager)); 
        /// <summary>
        /// 用户登录验证
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <param name="verifyCode"></param>
        /// <returns></returns>
        public static LoginResult Login(this HttpContextBase context, string name, string password, string verifyCode)
        {
            if (context.Session["CheckCode"] != null
                && !string.IsNullOrWhiteSpace(context.Session["CheckCode"].ToString())
                && context.Session["CheckCode"].ToString().Equals(verifyCode, StringComparison.CurrentCultureIgnoreCase))
            {
                using (IUserCompanyService servcie = DIFactory.GetContainer().Resolve<IUserCompanyService>())//查找数据库
                {
                    User user = servcie.Set<User>().FirstOrDefault(u => u.Name.Equals(name) || u.Account.Equals(name) || u.Mobile.Equals(name) || u.Email.Equals(name));//账号查找
                    if (user == null)
                    {
                        return LoginResult.NoUser;
                    }
                    else if (!user.Password.Equals(MD5Encrypt.Encrypt(password)))
                    {
                        return LoginResult.WrongPwd;
                    }
                    else if (user.State == 1)
                    {
                        return LoginResult.Frozen;
                    }
                    else
                    {
                        //登录成功  写cookie session
                        CurrentUser currentUser = new CurrentUser()
                        {
                            Id = user.Id,
                            Name = user.Name,
                            Account = user.Account,
                            Email = user.Email,
                            Password = user.Password,
                            LoginTime = DateTime.Now
                        };
                           
                        #region Cookie
                        //context.Request.Cookies

                        //HttpCookie cookie = context.Request.Cookies.Get("CurrentUser");
                        //if (cookie == null)
                        //{
                        HttpCookie myCookie = new HttpCookie("CurrentUser");
                        myCookie.Value = JsonHelper.ObjectToString<CurrentUser>(currentUser);
                        myCookie.Expires = DateTime.Now.AddMinutes(5);
                        //5分钟后  硬盘cookie
                        //不设置就是内存cookie--关闭浏览器就丢失
                        //改成过期 -1 过期
                        //修改cookie:不能修改,只能起个同名的cookie

                        //myCookie.Domain//设置cookie共享域名
                        //myCookie.Path//指定路径能享有cookie
                        context.Response.Cookies.Add(myCookie);//一定要输出
                        //}
                        //前端只能获取name-value
                        #endregion Cookie

                        #region Session
                        //context.Session.RemoveAll();
                        var sessionUser = context.Session["CurrentUser"];
                        context.Session["CurrentUser"] = currentUser;
                        context.Session.Timeout = 3;//minute  session过期等于Abandon
                        #endregion Session

                        logger.Debug(string.Format("用户id={0} Name={1}登录系统", currentUser.Id, currentUser.Name));
                        return LoginResult.Success;
                    }
                }
                //服务端是只靠session--安全
                //cookie一直做登陆
                //cookie+session:验证用session,没有session就看cookie(cookie写个时间)
            }
            else
            {
                return LoginResult.WrongVerify;//这是一个枚举,想返回什么,自定义去吧
            }
        }
    }

用户退出:
        public ActionResult Logout()
        {
            this.HttpContext.UserLogout();
            return RedirectToAction("Index", "Home"); ;
        }

        public static void UserLogout(this HttpContextBase context)
        {
            #region Cookie
            HttpCookie myCookie = context.Request.Cookies["CurrentUser"];
            if (myCookie != null)
            {
                myCookie.Expires = DateTime.Now.AddMinutes(-1);//设置过过期
                context.Response.Cookies.Add(myCookie);
            }

            #endregion Cookie

            #region Session
            var sessionUser = context.Session["CurrentUser"];
            if (sessionUser != null && sessionUser is CurrentUser)
            {
                CurrentUser currentUser = (CurrentUser)context.Session["CurrentUser"];
                logger.Debug(string.Format("用户id={0} Name={1}退出系统", currentUser.Id, currentUser.Name));
            }
            context.Session["CurrentUser"] = null;//表示将制定的键的值清空,并释放掉,
            context.Session.Remove("CurrentUser");
            context.Session.Clear();//表示将会话中所有的session的键值都清空,但是session还是依然存在,
            context.Session.RemoveAll();//
            context.Session.Abandon();//就是把当前Session对象删除了,下一次就是新的Session了   
            #endregion Session
        }

  

上一篇:Apache Shiro安全框架(1)


下一篇:生产环境一次诡异的空指针问题,竟然反转了4次