Пример #1
0
        /// <summary>
        /// Creates a new user.
        /// </summary>
        /// <param name="id">An ID for the user to create.</param>
        /// <param name="name">A name for the user to create.</param>
        /// <param name="password">A password for the user.</param>
        /// <param name="isAdmin">Whether the user is an admin. Defaults to false.</param>
        /// <returns>Returns the newly created user.</returns>
        /// <exception cref="EntityAlreadyExsistsException">Thrown if the ID is already taken.</exception>
        public User CreateUser(string id, string name, string password, bool isAdmin = false)
        {
            if (UserRepository.GetUser(id) != null)
            {
                throw new EntityAlreadyExsistsException("User", id);
            }

            // Hash & salt password, create user!
            (string hash, byte[] salt) = PasswordHashingService.HashAndSaltPassword(password);
            return(UserRepository.CreateUser(id, name, hash, salt, isAdmin));
        }
Пример #2
0
        /// <summary>
        /// Sets up the service with all known authentication providers.
        /// </summary>
        /// <param name="loggerFactory">Fasctory to create loggers from.</param>
        /// <param name="passwordHashingService">Provides password hashing functionalities.</param>
        /// <param name="userRepository">Provides users.</param>
        /// <param name="configuration">App configuration for JWT signing information.</param>
        public AuthService(ILoggerFactory loggerFactory, PasswordHashingService passwordHashingService, IReadOnlyUserRepository userRepository, IConfiguration configuration)
        {
            Logger = loggerFactory.CreateLogger <AuthService>();
            PasswordHashingService = passwordHashingService;
            UserRepository         = userRepository;

            // JWT-related configuration
            SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetValue <string>("Jwt:Secret")));

            SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            JwtLifetime        = TimeSpan.FromMinutes(configuration.GetValue <int>("Jwt:LifetimeInMinutes"));
            JwtIssuer          = configuration.GetValue <string>("Jwt:Issuer");
        }
Пример #3
0
        /// <summary>
        /// Attempts to change a user's password
        /// </summary>
        /// <param name="id">The ID of the user.</param>
        /// <param name="oldPassword">The old password for verification.</param>
        /// <param name="newPassword">The new password to save.</param>
        /// <exception cref="EntityNotFoundException">Thrown if there is no such user.</exception>
        /// <exception cref="UnauthorizedAccessException">Thrown if the submitted old password is wrong!</exception>
        public void ChangePassword(string id, string oldPassword, string newPassword)
        {
            User user = GetUserOrThrowNotFoundException(id);

            // Verify old password
            if (user.Password != PasswordHashingService.HashAndSaltPassword(oldPassword, user.Salt))
            {
                throw new UnauthorizedAccessException();
            }

            // Hash and salt new password
            (string hashedPassword, byte[] salt) = PasswordHashingService.HashAndSaltPassword(newPassword);
            user.Password = hashedPassword;
            user.Salt     = salt;
            UserRepository.UpdateUser(user);
        }
Пример #4
0
        /// <summary>
        /// Attempts to authenticate a user.
        /// </summary>
        /// <param name="id">The user's unique ID.</param>
        /// <param name="password">The user's password.</param>
        /// <param name="serializedToken">The serialized token.</param>
        /// <returns>Returns whether authentication was successful.</returns>
        /// <exception cref="Firefly.Services.Exceptions.EntityNotFoundException">User</exception>
        public bool TryAuthenticate(string id, string password, out string serializedToken)
        {
            serializedToken = null;

            // Get user
            User user = UserRepository.GetUser(id);

            if (user == null)
            {
                throw new EntityNotFoundException("User", id);
            }

            // Check password
            if (user.Password != PasswordHashingService.HashAndSaltPassword(password, user.Salt))
            {
                return(false);
            }

            // Set user claims
            List <Claim> claims = new List <Claim>
            {
                // Add subject, name, role
                new Claim(JwtRegisteredClaimNames.Sub, user.Id),
                new Claim("name", user.Name),
            };

            if (user.IsAdmin)
            {
                claims.Add(new Claim("role", ROLE_ADMINISTRATOR));
            }

            // Generate token
            JwtSecurityToken token = new JwtSecurityToken(JwtIssuer, null, claims, expires: DateTime.Now.Add(JwtLifetime), signingCredentials: SigningCredentials);

            serializedToken = new JwtSecurityTokenHandler().WriteToken(token);

            // Done!
            return(true);
        }
Пример #5
0
 /// <summary>
 /// Sets up the service.
 /// </summary>
 /// <param name="loggerFactory">Fasctory to create loggers from.</param>
 /// <param name="passwordHashingService">Provides hashing features.</param>
 /// <param name="userRepository">Repository for user data.</param>
 public UserService(ILoggerFactory loggerFactory, PasswordHashingService passwordHashingService, IUserRepository userRepository)
 {
     Logger = loggerFactory.CreateLogger <UserService>();
     PasswordHashingService = passwordHashingService;
     UserRepository         = userRepository;
 }