Example #1
0
        public User Authenticate(UserForLogin userForLogin)
        {
            if (userForLogin == null)
            {
                return(null);
            }
            if (userForLogin.Password == null || userAPI == null)
            {
                return(null);
            }
            var sha256 = new SHA256CryptoServiceProvider();

            var hashedPassword = ConvertByteArrayToString(
                sha256.ComputeHash(ConvertStringToByteArray(userForLogin.Password)));

            sha256.Dispose();
            var user = userAPI.GetUserFromDatabase(userForLogin.Name);

            if (user == null)
            {
                return(null);
            }
            if (user.Password != hashedPassword)
            {
                return(null);
            }

            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(appSettings.Secret);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials =
                    new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            user.Token    = tokenHandler.WriteToken(token);
            user.Password = null;
            return(user);
        }