示例#1
0
        public ProfileAuthenticationResponseDto Authenticate(ProfileAuthenticationRequestDto profileFromUi)
        {
            // Validating parameters
            var invalidParams = new List <string>();

            if (!IsValidEmail(profileFromUi.Email)) // TODO: Do I need email validation on login?
            {
                invalidParams.Add(nameof(profileFromUi.Email));
            }

            if (invalidParams.Any())
            {
                throw new ValidationException(invalidParams);
            }

            var profileFromDb = _profileRepository.GetProfileByEmail(profileFromUi.Email);

            if (profileFromDb == null)
            {
                throw new AuthenticationException();
            }

            if (profileFromDb.LockDate.HasValue &&
                profileFromDb.LockDate.Value < DateTime.Now.AddDays(1))// TODO: Magic number
            {
                throw new DomainModelException("Account locked");
            }

            if (!VerifyPasswordHash(profileFromUi.Password,
                                    profileFromDb.PasswordHash, profileFromDb.PasswordSalt))
            {
                _profileRepository.AddAttempt(profileFromDb.Email);
                if (profileFromDb.IncorrectAttempts >= 5)// TODO: Magic number
                {
                    _profileRepository.LockProfile(profileFromDb.Email);
                    throw new DomainModelException("Account locked");
                }
                throw new AuthenticationException();
            }

            // Generating response
            var responseProfile = new ProfileAuthenticationResponseDto
            {
                Email = profileFromDb.Email
            };

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new []
                {
                    new Claim(ClaimTypes.Name, profileFromDb.Id.ToString()),
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials
                                     (
                    new SymmetricSecurityKey(key),
                    SecurityAlgorithms.HmacSha256Signature
                                     )
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            responseProfile.Token = tokenHandler.WriteToken(token);

            return(responseProfile);
        }