﻿using NetChris.Security.Extensions;

namespace NetChris.Security.Cryptography
{
    /// <summary>
    /// Convenience class to easily validate passwords given Base64-encoded hashes and salts.
    /// </summary>
    public class PasswordValidator
    {
        private readonly string _algorithmIdentifier;
        private readonly string _passwordHashAsBase64String;
        private readonly string _saltAsBase64String;

        /// <summary>
        /// Initializes a new instance of the <see cref="PasswordValidator"/> class.
        /// </summary>
        /// <param name="algorithmIdentifier">The algorithm identifier.</param>
        /// <param name="passwordHashAsBase64String">The password hash as a Base64 string.</param>
        /// <param name="saltAsBase64String">The salt as a Base64 string.</param>
        public PasswordValidator(string algorithmIdentifier, string passwordHashAsBase64String, string saltAsBase64String)
        {
            _algorithmIdentifier = algorithmIdentifier;
            _passwordHashAsBase64String = passwordHashAsBase64String;
            _saltAsBase64String = saltAsBase64String;
        }

        /// <summary>
        /// Validates the specified password.
        /// </summary>
        /// <param name="password">The password.</param>
        /// <returns><c>true</c> if the password is valid, <c>false</c> otherwise.</returns>
        public bool Validate(string password)
        {
            byte[] salt = _saltAsBase64String.FromBase64String();
            IPasswordHasher passwordHasher = PasswordHashing.GetPasswordHasher(_algorithmIdentifier);
            IPasswordHash hash = passwordHasher.Hash(password, salt);
            return hash.GetHash().ToBase64String().Equals(_passwordHashAsBase64String);
        }
    }
}
