-1

I have a class that creates a user by searching for the email and making sure it doesn't exist and it creates a user:

public async Task EnsureSeedDataAsync()
    {
        if (await _userManager.FindByEmailAsync("test@theworld.com") == null)
        {
            // Add the user.
            var newUser = new CRAMSUser()
            {
                UserName = "test",
                Email = "test@crams.com"
            };

            await _userManager.CreateAsync(newUser, "P@ssw0rd!");
        }
    }

I am trying create another class to change the password, with the same method but I am confused as to how to create a currentUser object to be passed into the RemovePassword and AddPassword calls. This is what I have so far :

    public async Task ChangePassword()
    {
        if (await _userManager.FindByEmailAsync("test@theworld.com") != null)
        {
            _userManager.RemovePasswordAsync(currentUser);

            _userManager.AddPasswordAsync(currentUser, "newPassword");
        }
    }

Can someone please direct me in the right direction as I am new to this and don't know how to transfer the currentUser object, that contains the email that is being searched.

enavuio
  • 1,428
  • 2
  • 19
  • 31

2 Answers2

3

FindByEmailAsyc returns the user object, you need to save it to a variable and pass that to the other userManager calls. Also, the RemovePassword and AddPassword methods take the key value of your User object as a parameter, not the whole User object.

public async Task ChangePassword()
{

    var currentUser = await _userManager.FindByEmailAsync("test@theworld.com") 
    if (currentUser != null)
    {
        _userManager.RemovePasswordAsync(currentUser.Id);

        _userManager.AddPasswordAsync(currentUser.Id, "newPassword");
    }
}
jmoerdyk
  • 5,544
  • 7
  • 38
  • 49
  • 1
    Doing it in two operations is not good, if the second operation fails user is effectively w/o a password – Tseng Oct 12 '16 at 00:59
  • 1
    Yeah, using the `ChangePasswordAsync` method is probably better, but I figured that was beyond the scope of the original question. – jmoerdyk Oct 12 '16 at 15:07
1

See my answer in this question. It allows changing the password with just the userId & new password, which is useful to allow Administrators to set a users password and doing it in one single transaction.

It boils down to creating a new method which calls the underlying user store directly.

Community
  • 1
  • 1
Tseng
  • 61,549
  • 15
  • 193
  • 205