Пример #1
0
        public void Logon(LogonModel model)
        {
            try
            {
                // Validate supplied logon credentials
                _authenticationValidator.ValidateLogon(model);

                // Username and password valid, user not locked out. We can continue and log user on.
                User user = _userRepository.ReadUserByEmail(model.TenantId, model.Email.Trim().ToLower());

                // Get user details that we will persist during authenticated session
                AuthenticatedUser authenticatedUser = new AuthenticatedUser
                {
                    Alias    = user.Alias,
                    Email    = user.Email,
                    UserId   = user.UserId,
                    TenantId = model.TenantId,
                    Roles    = user.Roles.Select(r => r.Name).ToList()
                };
                AuthenticatedUserInfo authenticatedUserInfo = new AuthenticatedUserInfo
                {
                    User       = authenticatedUser,
                    RememberMe = model.RememberMe
                };

                // Logon user using authentication provider
                _authenticationProviderService.LogonAuthenticatedUser(authenticatedUserInfo);
            }
            catch (UserLockedOutException)
            {
                Logoff();
                throw;
            }
        }
        /// <summary>
        /// Submits form.
        /// </summary>
        /// <param name="form">View model containing form definition and submitted values.</param>
        /// <returns>Result of form post.</returns>
        public FormResult PostForm(Form form)
        {
            try
            {
                // Get website identifier
                long tenantId = _authenticationService.TenantId;

                // Get confirm user set password model from submitted form values
                LogonModel model = new LogonModel
                {
                    Email      = ((TextField)form.Fields["email"]).Value,
                    Password   = ((PasswordTextField)form.Fields["password"]).Value,
                    RememberMe = ((BooleanField)form.Fields["rememberMe"]).Value,
                    TenantId   = tenantId
                };

                // Log user on
                _authenticationService.Logon(model);

                // Return form result with no errors
                return(_formHelperService.GetFormResult());
            }
            catch (ValidationErrorException ex)
            {
                // Return form result containing errors
                return(_formHelperService.GetFormResultWithValidationErrors(ex.Errors));
            }
            catch (Exception)
            {
                // Return form result containing unexpected error message
                return(_formHelperService.GetFormResultWithErrorMessage(ApplicationResource.UnexpectedErrorMessage));
            }
        }
        /// <summary>
        /// Performs main validation of supplied user credentials. If user credentials not valid, a validation error exception will be thrown by this method.
        /// </summary>
        /// <param name="model">User credentials to validate.</param>
        /// <param name="keyPrefix">Validation key prefix.</param>
        public void ValidateLogon(LogonModel model, string keyPrefix = null)
        {
            // Do initial model checks (valid email, password required etc)
            _modelValidator.Validate(model, keyPrefix);

            // Get user given email address
            User user = _userRepository.ReadUserByEmail(model.TenantId, model.Email.Trim().ToLower());

            // The first condition that causes an invalid user is when user not found due to an invalid email address entered. In this case, user is null.
            if (user == null)
            {
                throw new ValidationErrorException(new ValidationError(null, AuthenticationResource.LogonUserCredentialsInvalidMessage, keyPrefix));
            }

            // If user has not been confirmed, they must first set their password before they can be validated.
            if (!user.Confirmed)
            {
                throw new ValidationErrorException(new ValidationError(null, AuthenticationResource.LogonUserUnconfirmedMessage, keyPrefix));
            }

            // User may have been disabled by an administrator, in which case it will not be possible to validate account.
            if (!user.Enabled)
            {
                throw new ValidationErrorException(new ValidationError(null, AuthenticationResource.LogonUserDisabledMessage, keyPrefix));
            }

            // If account locked out, check to see when last password failure occured. If lockout duration period expired, we can undo the lockout.
            if (user.LockedOut)
            {
                TimeSpan lockOutDuration = _authenticationConfigurationService.GetLockOutDuration(model.TenantId);
                if ((DateTime.UtcNow - (DateTime)user.LastPasswordFailure) > lockOutDuration)
                {
                    // Clear password failures associated with a user and sets user's locked out flag to false
                    user.LockedOut           = false;
                    user.LastPasswordFailure = null;
                    user.PasswordFailures    = 0;

                    // Do the update
                    _userRepository.UpdateUser(user);
                }
                else
                {
                    throw new UserLockedOutException(new ValidationError(null, AuthenticationResource.LogonUserLockedOutMessage, keyPrefix));
                }
            }

            // Finally, check password entered is correct and if not register a password failure which may lock user out
            byte[] userPasswordSalt        = _stringService.GetBytes(user.PasswordSalt);
            byte[] userPasswordSaltedHash  = _stringService.GetBytes(user.PasswordSaltedHash);
            byte[] logonPasswordSaltedHash = _securityService.EncryptPassword(model.Password, userPasswordSalt);
            if (!_stringService.ByteArraysEqual(logonPasswordSaltedHash, userPasswordSaltedHash))
            {
                RegisterPasswordFailure(user);
                if (user.LockedOut)
                {
                    throw new ValidationErrorException(new ValidationError(null, AuthenticationResource.LogonUserLockedOutMessage, keyPrefix));
                }
                else
                {
                    throw new ValidationErrorException(new ValidationError(null, AuthenticationResource.LogonUserCredentialsInvalidMessage, keyPrefix));
                }
            }
        }