예제 #1
0
        public IActionResult Login(LoginViewModel vm)
        {
            string message = "Internal error";

            if (vm.Reset && (vm.NewPassword == null || vm.NewPassword != vm.ConfirmNewPassword))
            {
                message = vm.NewPassword == null ? "New Password Required." : "Passwords do not match";
            }
            else
            {
                var login = _AppUserRepo.Login(vm.UserName, vm.Password, vm.Reset ? vm.NewPassword : null);
                switch (login.Result)
                {
                case "RESET":
                    vm.Reset = true;
                    ModelState.Clear();
                    message = "Please change your password.";
                    break;

                case "OK":
                    var roles  = _AppUserRepo.GetUserRoles(login.UserId).Where(x => x.Active).Select(x => x.Descr);
                    var claims = new List <Claim>
                    {
                        new Claim(ClaimTypes.Name, vm.UserName),
                        new Claim("UserId", login.UserId.ToString()),
                        new Claim("FullName", login.UserFullName),
                        new Claim("ContractorId", login.ContractorId.ToString())
                    };
                    foreach (var role in roles)
                    {
                        claims.Add(new Claim("Role", role));
                    }
                    var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    var authProperties = new AuthenticationProperties
                    {
                        IsPersistent = vm.RememberMe,
                        IssuedUtc    = login.LastLogin,
                        ExpiresUtc   = DateTimeOffset.Now.AddDays(14),
                    };
                    HttpContext.SignInAsync(
                        CookieAuthenticationDefaults.AuthenticationScheme,
                        new ClaimsPrincipal(claimsIdentity),
                        authProperties);
                    return(Redirect("/Work"));

                case "NO":
                    message = "User Name or Password is invalid.";
                    break;

                case "LOCKOUT":
                    message = "Maximum tries exceeded.";
                    break;
                }
            }

            ModelState.AddModelError("failed", message);
            return(View(vm));
        }