public ActionResult LogOn(string userName, string password, bool rememberMe, string returnUrl)
        {
            UserModel user = null;

            if (!ValidateLogOn(userName, password, out user))
            {
                return(View());
            }

            string loginSession = RedisHelper.GetLoginSession(user.UserName + ":session", Util.GetRootedUri("").ToString());

            if (!string.IsNullOrEmpty(loginSession) &&
                !string.Equals(loginSession, Session.SessionID, StringComparison.Ordinal))
            {
                Session["_askuser_"]  = true;
                Session["_tempuser_"] = user.UserName;
                Session["_remember_"] = rememberMe;
                //转跳 到询问页面
                return(this.RedirectToAction("askuser", "openid"));
            }

            _formsAuthService.SignIn(user, rememberMe);
            string claimIdentifier = Util.GetUserClaimIdentifier(userName).ToString();

            _logService.Add(new LoginLogModel
            {
                ID       = Guid.NewGuid(),
                AddTime  = DateTime.Now,
                Flag     = 0,
                UserName = user.UserName,
                OpenIdClaimedIdentifier  = claimIdentifier,
                OpenIdFriendlyIdentifier = claimIdentifier
            });

            if (string.IsNullOrEmpty(returnUrl))
            {
                return(RedirectToAction("Index", "Home"));
            }

            return(Redirect(returnUrl));
        }
Exemple #2
0
        public async Task <IResultModel> Login([FromBody] LoginModel model)
        {
            var log = new LoginLogAddModel();

            try
            {
                var result = await _authService.Login(model, _webConfigModel.RefreshTokenExpiredTime);

                log.Result      = result.Successful;
                log.IP          = _loginInfo.IP;
                log.BrowserInfo = _accessor.HttpContext.Request.Headers["User-Agent"];
                log.UserCode    = model.UserCode;
                log.Remark      = result.Msg;

                if (result.Successful)
                {
                    var user      = result.Data.User;
                    var loginInfo = result.Data.AuthInfo;

                    log.UserName = user.UserName;

                    var claims = new[]
                    {
                        new Claim(ClaimsName.UserId, user.Id.ToString()),
                        new Claim(ClaimsName.UserCode, user.UserCode),
                        new Claim(ClaimsName.UserName, user.UserName),
                        new Claim(ClaimsName.OrganizeId, user.OrganizeId.ToString()),
                        new Claim(ClaimsName.LoginTime, loginInfo.LoginTime.ToString()),
                        new Claim(ClaimsName.RoleIds, result.Data.RoleIds),
                        new Claim(ClaimsName.RoleCodes, result.Data.RoleCodes),
                        new Claim(ClaimsName.RoleNames, result.Data.RoleNames)
                    };


                    var token = _jwtHandler.Build(claims, loginInfo.RefreshToken);
                    return(ResultModel.Success(token));
                }

                return(ResultModel.Failed(result.Msg));
            }
            catch (Exception ex)
            {
                log.Remark = ex.Message;
                return(ResultModel.Failed(ex.Message));
            }
            finally
            {
                await _loginLogService.Add(log);
            }
        }
 public Task <IResultModel> Add(LoginLogAddModel model)
 {
     return(_service.Add(model));
 }
Exemple #4
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public Result <UserDto> Login(UserDto dto)
        {
            var res = new Result <UserDto>();

            try
            {
                var user = GetOne(item => item.LoginName == dto.LoginName);
                if (user == null)
                {
                    res.msg = "无效的用户";
                }
                else
                {
                    //记录登录日志
                    loginLogService.Add(new LoginLogDto
                    {
                        UserId    = user.Id,
                        LoginName = user.LoginName,
                        IP        = WebHelper.GetClientIP(),
                        Mac       = WebHelper.GetClientMACAddress()
                    });
                    if (user.Password != dto.Password.ToMD5())
                    {
                        res.msg = "登录密码错误";
                    }
                    else if (user.IsDeleted)
                    {
                        res.msg = "用户已被删除";
                    }
                    else if (user.Status == UserStatus.未激活)
                    {
                        res.msg = "账号未被激活";
                    }
                    else if (user.Status == UserStatus.禁用)
                    {
                        res.msg = "账号被禁用";
                    }
                    else
                    {
                        res.flag = true;
                        res.msg  = "登录成功";
                        res.data = user;

                        //写入注册信息
                        DateTime expiration = dto.IsRememberMe
                            ? DateTime.Now.AddDays(7)
                            : DateTime.Now.Add(FormsAuthentication.Timeout);
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,
                                                                                         user.LoginName,
                                                                                         DateTime.Now,
                                                                                         expiration,
                                                                                         true,
                                                                                         user.Id.ToString(),
                                                                                         FormsAuthentication.FormsCookiePath);

                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
                                                           FormsAuthentication.Encrypt(ticket))
                        {
                            HttpOnly = true,
                            Expires  = expiration
                        };

#if !DEBUG
                        cookie.Domain = FormsAuthentication.CookieDomain;
#endif

                        HttpContext.Current.Response.Cookies.Add(cookie);
                    }
                }
            }
            catch (Exception ex)
            {
                res.msg = ex.Message;
                Logger.Log(ex.Message, ex);
            }
            return(res);
        }
        public async Task <ActionResult> Login(LoginModel model, string returnUrl = "/")
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // 这不会计入到为执行帐户锁定而统计的登录失败次数中
            // 若要在多次输入错误密码的情况下触发帐户锁定,请更改为 shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout : false);

            string ip = "";

            if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
            {
                ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
            }
            else
            {
                ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
            }
            var  place     = SinaIPParser.Parse(ip);
            bool isSuccess = false;
            var  message   = "";

            switch (result)
            {
            case SignInStatus.Success:
                isSuccess = true;
                message   = "登录成功";
                break;

            case SignInStatus.Failure:
                isSuccess = false;
                message   = "登录失败,账号或者密码不正确";
                break;

            case SignInStatus.LockedOut:
                isSuccess = false;
                message   = "登录失败,账户被锁定";
                break;

            case SignInStatus.RequiresVerification:
                isSuccess = false;
                message   = "登录失败,账户需要验证";
                break;

            default:
                isSuccess = false;
                message   = "登录失败,未知因素";
                break;
            }
            var browser          = Request.Browser.Browser.ToString();
            var browser_version  = Request.Browser.MajorVersion.ToString();
            var browser_platform = Request.Browser.Platform.ToString();
            var client           = string.Format("{0}-{1}-{2}", browser, browser_version, browser_platform);

            _loginLogService.Add(new LoginLogViewModel
            {
                IP       = ip,
                Place    = place,
                Result   = isSuccess,
                Client   = client,
                UserName = model.UserName,
                Message  = message,
            });
            if (isSuccess)
            {
                var user       = _userService.GetByUserName(model.UserName);
                var namecookie = new HttpCookie("Name");
                namecookie.Value = user.Name;
                Response.Cookies.Add(namecookie);
                var avatarcookie = new HttpCookie("Avatar");
                avatarcookie.Value = user.Avatar;
                Response.Cookies.Add(avatarcookie);
                return(RedirectToLocal(returnUrl));
            }
            ModelState.AddModelError("", "登录失败");
            return(View(model));
        }