Exemple #1
0
        public ResponseDto <bool> IsHashedCredentialsValid(string username, string password)
        {
            var hasher = new PayloadHasher();

            using (var gateway = new AuthenticationGateway())
            {
                var accountResult = gateway.GetUserAccount(username);

                if (accountResult.Error != null)
                {
                    return(new ResponseDto <bool>()
                    {
                        Data = false,
                        Error = accountResult.Error
                    });
                }

                if (password == accountResult.Data.Password)
                {
                    return(new ResponseDto <bool>()
                    {
                        Data = true
                    });
                }
                else
                {
                    return(new ResponseDto <bool>()
                    {
                        Data = false,
                        Error = AuthenticationErrorMessages.USERNAME_PASSWORD_ERROR
                    });
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// The CreateFirstTimeSsoUser method.
        /// Creates a first time user registered from the SSO.
        /// <para>
        /// @author: Jennifer Nguyen
        /// @updated: 04/09/2018
        /// </para>
        /// </summary>
        /// <param name="userAccountDto"></param>
        /// <returns></returns>
        public ResponseDto <bool> CreateFirstTimeSsoUser(UserAccountDto userAccountDto)
        {
            var createFirstTimeSsoUserPreLogicStrategy = new CreateFirstTimeSsoUserPreLogicValidationStrategy(userAccountDto);
            var saltGenerator = new SaltGenerator();
            var payloadHasher = new PayloadHasher();

            // Validate data transfer object
            var result = createFirstTimeSsoUserPreLogicStrategy.ExecuteStrategy();

            if (result.Error != null)
            {
                return(new ResponseDto <bool>
                {
                    Data = false,
                    Error = result.Error
                });
            }

            // Hash password
            var passwordSalt = new PasswordSalt(saltGenerator.GenerateSalt(128));
            var userAccount  = new UserAccount(username: userAccountDto.Username, password: userAccountDto.Password, isActive: true, isFirstTimeUser: true, roleType: userAccountDto.RoleType);

            userAccount.Password = payloadHasher.Sha256HashWithSalt(passwordSalt.Salt, userAccount.Password);

            // Validate domain models
            var createFirstTimeSsoUserPostLogicStrategy = new CreateFirstTimeSsoUserPostLogicValidationStrategy(userAccount, passwordSalt);

            result = createFirstTimeSsoUserPostLogicStrategy.ExecuteStrategy();
            if (result.Error != null)
            {
                return(new ResponseDto <bool>
                {
                    Data = false,
                    Error = result.Error
                });
            }

            // Store a user from Single Sign On registration request
            using (var userGateway = new UserGateway())
            {
                var gatewayResult = userGateway.StoreSsoUser(userAccount, passwordSalt);
                if (gatewayResult.Data == false)
                {
                    return(new ResponseDto <bool>()
                    {
                        Data = gatewayResult.Data,
                        Error = GeneralErrorMessages.GENERAL_ERROR
                    });
                }
            }

            return(new ResponseDto <bool>()
            {
                Data = true
            });
        }
Exemple #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="userAccount"></param>
        /// <param name="passwordSalt"></param>
        /// <param name="userProfile"></param>
        /// <param name="securityQuestions"></param>
        /// <param name="securityAnswerSalts"></param>
        /// <returns></returns>
        private ResponseDto <bool> MapUserDtoToModel(RegisterUserDto dto, out UserAccount userAccount, out PasswordSalt passwordSalt, out UserProfile userProfile, out IList <SecurityQuestion> securityQuestions, out IList <SecurityAnswerSalt> securityAnswerSalts)
        {
            // Map variables to the parameters
            userAccount = new UserAccount(
                username: dto.UserAccountDto.Username,
                password: dto.UserAccountDto.Password,
                isActive: true,
                isFirstTimeUser: false,
                roleType: RoleTypes.PUBLIC);

            securityQuestions = dto.SecurityQuestionDtos
                                .Select(securityQuestionDto => new SecurityQuestion(
                                            securityQuestionDto.Question, securityQuestionDto.Answer))
                                .ToList();

            userProfile = new UserProfile(
                displayPicture: ConfigurationManager.AppSettings["DefaultURLProfileImagePath"],
                displayName: dto.UserProfileDto.DisplayName);

            // Hash password and security questions
            var saltGenerator = new SaltGenerator();
            var payloadHasher = new PayloadHasher();

            passwordSalt         = new PasswordSalt(saltGenerator.GenerateSalt(128));
            userAccount.Password = payloadHasher.Sha256HashWithSalt(passwordSalt.Salt, userAccount.Password);

            securityAnswerSalts = new List <SecurityAnswerSalt>();

            for (var i = 0; i < securityQuestions.Count; i++)
            {
                securityAnswerSalts.Add(new SecurityAnswerSalt {
                    Salt = saltGenerator.GenerateSalt(128)
                });
                securityQuestions[i].Answer = payloadHasher.Sha256HashWithSalt(securityAnswerSalts[i].Salt, securityQuestions[i].Answer);
            }

            return(new ResponseDto <bool>()
            {
                Data = true
            });
        }
Exemple #4
0
        /// <summary>
        /// The CreateAdmin method.
        /// Contains business logic to create an admin user.
        /// <para>
        /// @author: Jennifer Nguyen, Angelica Salas
        /// @updated: 04/26/2018
        /// </para>
        /// </summary>
        /// <param name="registerUserDto"></param>
        /// <returns>ResponseDto</returns>
        public ResponseDto <RegisterUserDto> CreateAdmin(RegisterUserDto registerUserDto)
        {
            var createIndividualPreLogicValidationStrategy = new CreateIndividualPreLogicValidationStrategy(registerUserDto);
            var securityAnswerSalts = new List <SecurityAnswerSalt>();
            var saltGenerator       = new SaltGenerator();
            var payloadHasher       = new PayloadHasher();
            var claimsFactory       = new ClaimsFactory();

            // Validate data transfer object
            var result = createIndividualPreLogicValidationStrategy.ExecuteStrategy();

            if (result.Error != null)
            {
                return(new ResponseDto <RegisterUserDto>
                {
                    Data = registerUserDto,
                    Error = result.Error
                });
            }

            // Map data transfer object to domain models
            var userAccount       = new UserAccount(username: registerUserDto.UserAccountDto.Username, password: registerUserDto.UserAccountDto.Password, isActive: true, isFirstTimeUser: false, roleType: "private");
            var securityQuestions = registerUserDto.SecurityQuestionDtos
                                    .Select(securityQuestionDto => new SecurityQuestion(
                                                securityQuestionDto.Question, securityQuestionDto.Answer))
                                    .ToList();

            //Admin User Profile
            var displayImagePath = ConfigurationManager.AppSettings["DefaultURLProfileImagePath"];
            var userProfile      = new UserProfile(displayPicture: displayImagePath, displayName: registerUserDto.UserProfileDto.DisplayName);

            // Set user claims to be stored in UserClaims table as administrator
            var userClaims = new UserClaims(claimsFactory.Create(AccountTypes.Admin));

            // Hash password
            var passwordSalt = new PasswordSalt(saltGenerator.GenerateSalt(128));

            userAccount.Password = payloadHasher.Sha256HashWithSalt(passwordSalt.Salt, userAccount.Password);

            // Hash security answers
            for (var i = 0; i < securityQuestions.Count; i++)
            {
                securityAnswerSalts.Add(new SecurityAnswerSalt {
                    Salt = saltGenerator.GenerateSalt(128)
                });
                securityQuestions[i].Answer = payloadHasher.Sha256HashWithSalt(securityAnswerSalts[i].Salt, securityQuestions[i].Answer);
            }

            var createIndividualPostLogicValdiationStrategy = new CreateIndividualPostLogicValidationStrategy(userAccount, passwordSalt, userClaims, userProfile, securityQuestions, securityAnswerSalts);
            var validateResult = createIndividualPostLogicValdiationStrategy.ExecuteStrategy();

            if (!validateResult.Data)
            {
                return(new ResponseDto <RegisterUserDto>
                {
                    Data = registerUserDto,
                    Error = GeneralErrorMessages.GENERAL_ERROR
                });
            }

            // Store user in database
            using (var userGateway = new UserGateway())
            {
                var gatewayResult = userGateway.StoreIndividualUser(userAccount, passwordSalt, userClaims, userProfile, securityQuestions, securityAnswerSalts);
                if (gatewayResult.Data == false)
                {
                    return(new ResponseDto <RegisterUserDto>()
                    {
                        Data = registerUserDto,
                        Error = GeneralErrorMessages.GENERAL_ERROR
                    });
                }
            }

            return(new ResponseDto <RegisterUserDto>
            {
                Data = registerUserDto
            });
        }
Exemple #5
0
        /// <summary>
        /// Validates whether the payload's credentials are valid.
        /// <para>
        /// @author: Brian Fann
        /// @updated: 4/24/18
        /// </para>
        /// </summary>
        /// <param name="payload">Payload of token</param>
        /// <returns>True if credentials are valid, false otherwise</returns>
        private ResponseDto <bool> ValidateCredentials(SsoTokenPayloadDto payload)
        {
            // Validate username and password
            var loginDto = new LoginDto(payload.Username, payload.Password);
            var accountValidationStrategy = new LoginPreLogicValidationStrategy(loginDto);
            var accountResult             = accountValidationStrategy.ExecuteStrategy();

            if (!accountResult.Data)
            {
                StoreInvalidToken();

                return(new ResponseDto <bool>()
                {
                    Data = false,
                    Error = accountResult.Error
                });
            }

            using (var gateway = new AuthenticationGateway())
            {
                var userAccountResult = gateway.GetUserAccount(payload.Username);

                if (userAccountResult.Error != null)
                {
                    return(new ResponseDto <bool>()
                    {
                        Data = false,
                        Error = userAccountResult.Error
                    });
                }

                var userAccount = userAccountResult.Data;

                var saltResult = gateway.GetUserPasswordSalt(userAccount.Id);

                // Check if salt exists
                if (saltResult.Error != null)
                {
                    return(new ResponseDto <bool>()
                    {
                        Data = false,
                        Error = saltResult.Error
                    });
                }

                // Hash the password and compare it against the database
                var hashedPassword     = new PayloadHasher().Sha256HashWithSalt(saltResult.Data.Salt, payload.Password);
                var isPasswordMatching = hashedPassword == userAccount.Password;

                if (!isPasswordMatching)
                {
                    return(new ResponseDto <bool>()
                    {
                        Data = false,
                        Error = AuthenticationErrorMessages.USERNAME_PASSWORD_ERROR
                    });
                }
            }

            // Credentials are valid at this point
            return(new ResponseDto <bool>()
            {
                Data = true
            });
        }
Exemple #6
0
        /// <summary>
        /// The ConfirmSecurityQuestionAnswers method.
        /// Confirms security answers pertaining to the security questions of a user.
        /// <para>
        /// @author: Jennifer Nguyen
        /// @updated: 04/25/2018
        /// </para>
        /// </summary>
        /// <returns>A ResponseDto which includes the ResetPasswordDto</returns>
        public ResponseDto <ResetPasswordDto> ConfirmSecurityQuestionAnswers()
        {
            var resetPasswordPreLogicValidationStrategy = new ResetPasswordPreLogicValidationStrategy(_resetPasswordDto,
                                                                                                      ResetPasswordValidationTypes.ConfirmSecurityQuestionAnswersValidation);
            var payloadHasher = new PayloadHasher();

            // Validate data transfer object
            var result = resetPasswordPreLogicValidationStrategy.ExecuteStrategy();

            if (result.Error != null)
            {
                return(new ResponseDto <ResetPasswordDto>
                {
                    Data = null,
                    Error = result.Error
                });
            }

            IList <SecurityQuestionWithSaltDto> securityQuestionWithSalts;

            // Get security questions and security answer hashes
            using (var userGateway = new UserGateway())
            {
                // Get list of SecurityQuestionWithSalt
                var securityAnswerSaltsResult = userGateway.GetSecurityQuestionWithSalt(_resetPasswordDto.Username);
                if (securityAnswerSaltsResult.Error != null)
                {
                    return(new ResponseDto <ResetPasswordDto>()
                    {
                        Data = null,
                        Error = GeneralErrorMessages.GENERAL_ERROR
                    });
                }

                securityQuestionWithSalts = securityAnswerSaltsResult.Data;
            }

            foreach (var securityQuestionWithSalt in securityQuestionWithSalts)
            {
                foreach (var securityQuestion in _resetPasswordDto.SecurityQuestionDtos)
                {
                    // Hash the security answers in data transfer object
                    if (securityQuestionWithSalt.Question == securityQuestion.Question &&
                        securityQuestionWithSalt.Answer != securityQuestion.Answer)
                    {
                        securityQuestion.Answer = payloadHasher.Sha256HashWithSalt(salt: securityQuestionWithSalt.Salt,
                                                                                   payload: securityQuestion.Answer);

                        // Confirm security answers match
                        if (securityQuestionWithSalt.Answer != securityQuestion.Answer)
                        {
                            return(new ResponseDto <ResetPasswordDto>()
                            {
                                Data = null,
                                Error = ResetPasswordErrorMessages.SECURITY_QUESTIONS_AND_ANSWERS_NO_MATCH
                            });
                        }
                    }
                }
            }

            return(new ResponseDto <ResetPasswordDto>()
            {
                Data = _resetPasswordDto
            });
        }
Exemple #7
0
        public ResponseDto <ResetPasswordDto> SsoUpdatePassword()
        {
            var resetPasswordPreLogicValidationStrategy = new ResetPasswordPreLogicValidationStrategy(_resetPasswordDto,
                                                                                                      ResetPasswordValidationTypes.UpdatePasswordValidation);
            var         saltGenerator = new SaltGenerator();
            var         payloadHasher = new PayloadHasher();
            UserAccount userAccount;

            // Validate data transfer object
            var result = resetPasswordPreLogicValidationStrategy.ExecuteStrategy();

            if (result.Error != null)
            {
                return(new ResponseDto <ResetPasswordDto>
                {
                    Data = null,
                    Error = result.Error
                });
            }

            // Get the existing UserAccount model associated with the username
            using (var userGateway = new UserGateway())
            {
                var gatewayResult = userGateway.GetUserByUsername(_resetPasswordDto.Username);
                if (gatewayResult.Error != null)
                {
                    return(new ResponseDto <ResetPasswordDto>()
                    {
                        Data = null,
                        Error = GeneralErrorMessages.GENERAL_ERROR
                    });
                }

                userAccount = gatewayResult.Data;
            }

            // Set the new password to the UserAccount model
            userAccount.Password = _resetPasswordDto.Password;

            // Hash password
            var passwordSalt = new PasswordSalt(saltGenerator.GenerateSalt(128));

            userAccount.Password = payloadHasher.Sha256HashWithSalt(passwordSalt.Salt, userAccount.Password);

            // Update the password in the database
            using (var userGateway = new UserGateway())
            {
                var gatewayResult = userGateway.UpdatePassword(userAccount, passwordSalt);
                if (gatewayResult.Error != null)
                {
                    return(new ResponseDto <ResetPasswordDto>()
                    {
                        Data = null,
                        Error = GeneralErrorMessages.GENERAL_ERROR
                    });
                }
            }

            return(new ResponseDto <ResetPasswordDto>()
            {
                Data = _resetPasswordDto
            });
        }
        /// <summary>
        /// This Method contains all the logic that is implemented to authenticate the user with the database
        /// </summary>
        /// <param name="loginDto"></param>
        /// <returns>
        /// ResponseDto with the updated LoginDto
        /// </returns>
        public ResponseDto <LoginDto> LoginUser(LoginDto loginDto)
        {
            var loginPreLogicValidationStrategy = new LoginPreLogicValidationStrategy(loginDto);

            // Checking if the Dto has all the information it needs
            var validateLoginDtoResult = loginPreLogicValidationStrategy.ExecuteStrategy();

            if (!validateLoginDtoResult.Data)
            {
                return(new ResponseDto <LoginDto>
                {
                    Error = validateLoginDtoResult.Error
                });
            }

            // Pulling attempts from DB
            using (var gateway = new AuthenticationGateway())
            {
                var userAttemptsResult = gateway.GetFailedAttempt(loginDto.Username);
                // Checking if the gateway returns a false
                if (userAttemptsResult.Error != null)
                {
                    return(Error(userAttemptsResult.Error));
                }
                // If there is no Error then take the data out
                var userAttempts = userAttemptsResult.Data;

                // Checking if they already have 5 failed attempts 20 mins ago
                if (userAttempts == null)
                {
                    userAttempts = new FailedAttempts()
                    {
                        LastAttemptTime = DateTime.UtcNow,
                        Count           = 0
                    };
                }
                else if (userAttempts.Count >= 5)
                {
                    var timeToCompare = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(20));
                    if (!(userAttempts.LastAttemptTime.CompareTo(timeToCompare) < 0))
                    {
                        return(Error(AuthenticationErrorMessages.LOCKED_ACCOUNT));
                    }
                    userAttempts.Count = 0;
                }

                // Pull the User From DB
                // Getting the user's ID
                var userAccountResult = gateway.GetUserAccount(loginDto.Username);
                if (userAccountResult.Error != null)
                {
                    return(Error(userAccountResult.Error));
                }

                // If there are no Errors from the gateway assign the data to an object
                var userAccount = userAccountResult.Data;
                // Set UserAttempts Id with the UserAccount Id
                userAttempts.Id = userAccount.Id;

                // Getting the Salt associated with the ID
                var saltResult = gateway.GetUserPasswordSalt(userAccount.Id);
                if (saltResult.Error != null)
                {
                    return(Error(userAccountResult.Error));
                }

                // Check if user is Active
                if (userAccount.IsActive == null || userAccount.IsActive == false)
                {
                    return(Error(AuthenticationErrorMessages.INACTIVE_USER));
                }

                var password = loginDto.Password;
                // Hash and Salting the Password
                var hashedPassword = new PayloadHasher().Sha256HashWithSalt(saltResult.Data.Salt, password);

                // Checking if the Password is equal to what is in the DataBase
                var checkPasswordResult = hashedPassword == userAccount.Password;

                // If Password matches log the attempt and send loginDto back
                if (checkPasswordResult)
                {
                    userAttempts.Count = 0;
                    return(SuccessfulAttempt(userAttempts, loginDto));
                }

                // Checking if this is the 5th attempt to time stamp it
                if (++userAttempts.Count >= 5)
                {
                    userAttempts.LastAttemptTime = DateTime.UtcNow;
                }

                return(FailedAttempt(userAttempts, AuthenticationErrorMessages.USERNAME_PASSWORD_ERROR));
            }
        }