コード例 #1
0
        /// <summary>
        /// Updates an existing user's password.
        /// </summary>
        /// <param name="newPassword">The new password to set.</param>
        /// <param name="userToUpdate">The user to update the password for.</param>
        public async Task ChangePassword(string newPassword, User userToUpdate)
        {
            _context.Users.Attach(userToUpdate);

            HashUtils.GenerateHashAndSaltFromString(newPassword, out byte[] hash, out byte[] salt);
            userToUpdate.PasswordHash = hash;
            userToUpdate.PasswordSalt = salt;

            _context.Users.Update(userToUpdate);
            await _context.SaveChangesAsync();
        }
コード例 #2
0
        /// <summary>
        /// Creates a new user.
        /// </summary>
        /// <param name="newUser">The new user entity to create.</param>
        /// <param name="password">The password for the user.</param>
        /// <exception cref="UserServiceException">Throws when missing or invalid/reserved values are found.</exception>
        /// <returns>The created user.</returns>
        public async Task <User> CreateAsync(User newUser, string password)
        {
            // ensure username is sent
            if (string.IsNullOrWhiteSpace(newUser.Username))
            {
                throw new UserServiceException("Username is required");
            }

            // ensure password is sent
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new UserServiceException("Password is required");
            }

            // ensure email is sent
            if (string.IsNullOrWhiteSpace(newUser.Email))
            {
                throw new UserServiceException("Email is required");
            }

            // ensure username doesn't already exist
            if (await _context.Users.AnyAsync(x => x.Username == newUser.Username))
            {
                throw new UserServiceException($"Username '{newUser.Username}' is taken");
            }

            // ensure email doesn't already exist
            if (await _context.Users.AnyAsync(x => x.Email == newUser.Email))
            {
                throw new UserServiceException($"Email '{newUser.Email}' is taken");
            }

            // generate hash and salt from the given password
            HashUtils.GenerateHashAndSaltFromString(password, out byte[] hash, out byte[] salt);
            newUser.PasswordHash = hash;
            newUser.PasswordSalt = salt;

            // standard user by default
            newUser.IsAdmin = false;

            // add and save new user
            _context.Users.Add(newUser);
            await _context.SaveChangesAsync();

            return(newUser);
        }