示例#1
0
        public User To(RegisterDto dto)
        {
            string salt = _crytpoService.GenerateSalt();
            string hash = _crytpoService.GenerateHash(salt, dto.Password);

            return(new User
            {
                Name = dto.Name,
                Surname = dto.Surname,
                Email = dto.Email,
                PasswordHash = hash,
                PasswordSalt = salt,
                Username = dto.Username,
                Role = Role.USER,
                Package = Package.NONE
            });
        }
        public bool IsAuthenticated(LoginDto request, out string token)
        {
            token = string.Empty;
            var user = _userRepo.GetUserByUsername(request.Username);


            if (user is null || !user.Active)
            {
                return(false);
            }
            var newHash = _cryptoService.GenerateHash(user.PasswordSalt, request.Password);

            if (newHash != user.PasswordHash)
            {
                return(false);
            }


            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, user.Username),
                new Claim(ClaimTypes.Name, user.Name + ' ' + user.Surname),
                new Claim(ClaimTypes.Role, _roleMapper.ToString(user.Role))
            };
            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var jwtToken = new JwtSecurityToken(
                _tokenManagement.Issuer,
                _tokenManagement.Audience,
                claims,
                expires: DateTime.Now.AddDays(_tokenManagement.AccessExpiration),
                signingCredentials: credentials
                );

            token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            _userRepo.SetToken(request.Username, token);
            return(true);
        }