Пример #1
2
        public ActionResult SignIn(SignInUser signInUser)
        {
            try
            {
                ActionResult actionResult = ServiceHelper.IsAnyNullOrEmpty(signInUser);
                if (actionResult.Success)
                {
                    actionResult.Success = false;
                    return(actionResult);
                }

                ApplicationSignInManager signinManager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationSignInManager>();

                SignInStatus result = signinManager.PasswordSignIn(signInUser.Username, signInUser.Password, signInUser.RememberMe, false);
                switch (result)
                {
                case SignInStatus.Success:

                    ApplicationUserManager userManager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
                    ApplicationUser        user        = userManager.Find(signInUser.Username, signInUser.Password);
                    if (!userManager.IsEmailConfirmed(user.Id))
                    {
                        return(new ActionResult {
                            Success = false, Message = "You need to confirm your email."
                        });
                    }

                    IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    ClaimsIdentity         userIdentity          = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties {
                        IsPersistent = signInUser.RememberMe
                    }, userIdentity);
                    string token = Security.GenerateSecurityToken(user.Id, signInUser.Username, user.Email);
                    return(new ActionResult
                    {
                        Success = true,
                        Message = token
                    });

                case SignInStatus.LockedOut:
                    userManager         = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
                    user                = userManager.FindByName(signInUser.Username);
                    user.LockoutEnabled = true;
                    userManager.Update(user);
                    return(new ActionResult
                    {
                        Success = false,
                        Message = "Your account has been locked out, please contact your system administrator."
                    });

                case SignInStatus.RequiresVerification:
                    return(new ActionResult
                    {
                        Success = false,
                        Message = "Your account has not yet been verified, please contact your system administrator."
                    });

                case SignInStatus.Failure:
                    ApplicationUserManager manager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
                    ApplicationUser        tryUser = manager.FindByName(signInUser.Username);
                    if (tryUser != null)
                    {
                        manager.AccessFailed(tryUser.Id);
                    }

                    return(new ActionResult
                    {
                        Success = false,
                        Message = "Invalid username/password combination."
                    });

                default:
                    return(new ActionResult
                    {
                        Success = false,
                        Message = "Could not login\r\n" + result
                    });
                }
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = signInUser.ToDictionary();
                ServiceHelper.LogException(exception, dictionary, ErrorSource.Authentication);
                return(new ActionResult
                {
                    Success = false,
                    Message = "Error, Failed to login."
                });
            }
        }
Пример #2
0
    public static RBACStatus Login(this ControllerBase controller, LoginViewModel model, ApplicationUserManager userMngr, ApplicationSignInManager signInMngr, out List <string> _errors)
    {
        RBACStatus _retVal = RBACStatus.Failure;

        _errors = new List <string>();
        try
        {
            var user = userMngr.FindByName(model.UserName);
            if (user != null)
            {
                var validCredentials = userMngr.Find(model.UserName, model.Password);
                if (userMngr.IsLockedOut(user.Id))
                {
                    _errors.Add(string.Format(c_AccountLockout, GetConfigSettingAsDouble(cKey_AccountLockoutTimeSpan)));
                    return(RBACStatus.LockedOut);
                }
                else if (userMngr.GetLockoutEnabled(user.Id) && validCredentials == null)
                {
                    userMngr.AccessFailed(user.Id);
                    if (userMngr.IsLockedOut(user.Id))
                    {
                        _errors.Add(string.Format(c_AccountLockout, GetConfigSettingAsDouble(cKey_AccountLockoutTimeSpan)));
                        return(RBACStatus.LockedOut);
                    }
                    else
                    {
                        int _attemptsLeftB4Lockout = (GetConfigSettingAsInt(cKey_MaxFailedAccessAttemptsBeforeLockout) - userMngr.GetAccessFailedCount(user.Id));
                        _errors.Add(string.Format(c_InvalidCredentials, _attemptsLeftB4Lockout));
                        return(_retVal);
                    }
                }
                else if (validCredentials == null)
                {
                    _errors.Add(c_InvalidLogin);
                    return(_retVal);
                }
                else
                {
                    //Valid credentials entered, we need to check whether email verification is required...
                    bool   IsAccountVerificationRequired = GetConfigSettingAsBool(cKey_AccountVerificationRequired);
                    bool   Is2FAEnabled = GetConfigSettingAsBool(cKey_2FAEnabled);
                    string DeviceType   = GetConfigSetting(cKey_2FADeviceType);

                    if ((IsAccountVerificationRequired && DeviceType == c_EmailCode) || (Is2FAEnabled && DeviceType == c_EmailCode))
                    {
                        //Check if email verification has been confirmed!
                        if (!userMngr.IsEmailConfirmed(user.Id))
                        {
                            //Display error message on login page, take no further action...
                            _errors.Add(c_AccountEmailUnconfirmed);
                            return(RBACStatus.EmailUnconfirmed);
                        }
                    }
                    //else if (Is2FAEnabled && DeviceType == c_PhoneCode)
                    else if ((IsAccountVerificationRequired && DeviceType == c_PhoneCode) || (Is2FAEnabled && DeviceType == c_PhoneCode))
                    {
                        if (!userMngr.IsPhoneNumberConfirmed(user.Id))
                        {
                            _errors.Add(c_AccountPhoneNumberUnconfirmed);
                            return(RBACStatus.PhoneNumberUnconfirmed);
                        }
                    }

                    bool _userLockoutEnabled = GetConfigSettingAsBool(cKey_UserLockoutEnabled);

                    //Before we signin, check that our 2FAEnabled config setting agrees with the database setting for this user...
                    if (Is2FAEnabled != userMngr.GetTwoFactorEnabled(user.Id))
                    {
                        userMngr.SetTwoFactorEnabled(user.Id, Is2FAEnabled);
                    }

                    _retVal = (RBACStatus)signInMngr.PasswordSignIn(model.UserName, model.Password, model.RememberMe, shouldLockout: _userLockoutEnabled);
                    switch (_retVal)
                    {
                    case RBACStatus.Success:
                    {
                        userMngr.ResetAccessFailedCount(user.Id);
                        break;
                    }

                    default:
                    {
                        _errors.Add(c_InvalidLogin);
                        break;
                    }
                    }
                }
            }
            else
            {
                _errors.Add(c_InvalidUser);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return(_retVal);
    }
Пример #3
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // all connections from mobile devices as well as web apps
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            var skipClaims = false;

            using (var repo = new ApplicationUserManager(new UserStore <ApplicationUser>()))
                using (var db = new ApplicationDbContext())
                {
                    var identityUser = repo.Users.SingleOrDefault(u => u.UserName == context.Ticket.Identity.Name);

                    var potentialId = "";

                    if (identityUser != null)
                    {
                        potentialId = identityUser.Id;
                    }

                    this.LogInfo("Testing password.");

                    var query = (from dbUser in db.Users
                                 where dbUser.Id == potentialId
                                 select dbUser);

                    var user = query.SingleOrDefault();

                    if (user == null)
                    {
                        context.SetError("invalid_grant", "User name or password is incorrect.");

                        repo.AccessFailed(user.Id);

                        return;
                    }

                    if (!user.LockoutEnabled)
                    {
                        context.SetError("invalid_grant", "Account is disabled.");

                        return;
                    }

                    identity.AddClaim(_defaultClaim);
                    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                    identity.AddClaim(new Claim("FirstName", user.FirstName));
                    identity.AddClaim(new Claim("LastName", user.LastName));
                    identity.AddClaim(new Claim("SessionLogId", Guid.NewGuid().ToString()));

                    foreach (var claim in user.Claims)
                    {
                        identity.AddClaim(new Claim(claim.ClaimType, claim.ClaimValue));
                    }

                    if (user.LockoutEnabled)
                    {
                        await repo.ResetAccessFailedCountAsync(user.Id);
                    }
                }

            this.LogInfo("Successfully authenticated {0}.", identity.Name);

            context.Validated(identity);
        }
Пример #4
0
        public IdentityLoginResult ValidateIdentityUser(string username, string password, bool shouldLockout)
        {
            var user = _userManager.FindByName(username);

            if (user == null)
            {
                return new IdentityLoginResult {
                           CustomerLoginResults = CustomerLoginResults.MemberNotExists
                }
            }
            ;

            if (_userManager.IsLockedOut(user.Id))
            {
                return new IdentityLoginResult {
                           CustomerLoginResults = CustomerLoginResults.IsLockedOut
                }
            }
            ;

            var account = _accountRepository.Table.Where(x => x.Email.ToLower() == user.Email.ToLower());

            if (account == null)
            {
                return new IdentityLoginResult {
                           CustomerLoginResults = CustomerLoginResults.AccountNotExists
                }
            }
            ;

            if (_userManager.CheckPassword(user, password))
            {
                _userManager.ResetAccessFailedCount(user.Id);

                var userIdentity = _userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                return(new IdentityLoginResult
                {
                    ClaimsIdentity = userIdentity,
                    CustomerLoginResults = CustomerLoginResults.Successful,
                });
            }

            if (shouldLockout)
            {
                _userManager.AccessFailed(user.Id);
                if (_userManager.IsLockedOut(user.Id))
                {
                    return new IdentityLoginResult {
                               CustomerLoginResults = CustomerLoginResults.IsLockedOut
                    }
                }
                ;
            }

            return(new IdentityLoginResult {
                CustomerLoginResults = CustomerLoginResults.WrongPassword
            });
        }
    }
}