Update User

Exercise - Implement UpdateLoggedInUserAsync


Exercise: Implement UpdateLoggedInUserAsync Method

In the Conduit.Repositories Project

Modify AccountRepository.cs by Implementing the following code:

        public async Task<User> UpdateLoggedInUserAsync(UpdateUser model)
            bool genToken = false;
            Account account = await GetLoggedInUserAsync(); // Make sure to rename the method to include Async
            if (!string.IsNullOrWhiteSpace(model.Email)
                && account.Email != model.Email)
                if (!await EmailIsUniqueAsync(model.Email))
                    throw new DuplicateEmailException($"Email {model.Email} is already in use.");

                account.Email = model.Email;
                genToken = true;

            if (!string.IsNullOrWhiteSpace(model.Password)
                && !VerifyPassword(model.Password, account.PasswordHash, account.PasswordSalt))
                byte[] passwordHash, passwordSalt;
                CreatePasswordHash(model.Password, out passwordHash, out passwordSalt);
                account.PasswordHash = passwordHash;
                account.PasswordSalt = passwordSalt;
                genToken = true;

            if (!string.IsNullOrWhiteSpace(model.UserName)
                && account.Person.UserName != model.UserName)
                if (!await UserNameIsUniqueAsync(model.UserName))
                    throw new DuplicateUserNameException($"User name {model.UserName} is already in use.");

                account.Person.UserName = model.UserName;

            if (!string.IsNullOrWhiteSpace(model.Image))
                account.Person.Image = model.Image;
            if (!string.IsNullOrWhiteSpace(model.Bio))
                account.Person.Bio = model.Bio;

            await Context.SaveChangesAsync();
            User user = CreateUser(account);
            if (genToken)
                user.Token = CreateToken(user);
            return user;

You'll notice that there are 2 method that have not been implemented:

  • EmailIsUniqueAsync(model.Email)
  • UserNameIsUniqueAsync(model.UserName)

Your exercise is to implement these private methods in the AccountRepository class.

My recommendation is not to copy and paste. I can't express it enough when I say, "There's value in typing it out." Understand what the logic is doing.

Hint: Review the code in UserExistsAsync method.

In the next video we'll go over the code together & see how I implemented the 2 methods that are missing.


I finished! On to the next chapter