Creating Active Users via the API gem

I just spent the better part of today working on this and found a workaround for it. Here’s the process you have to go through to make this work.

  1. Create the account and set active=true. Note the user_id that is provided from the API call. In your above example, the user_id=7 so we’ll use that in this example.
  2. Make an API call to deactivate the user account. It will be something like this:
    http://discourseURL/admin/users/7/deactivate.json?api_key=xxxx&api_username=yyyy
  3. Make an API call to activate the user account. It will be something like this:
    http://discourseURL/admin/users/7/activate.json?api_key=xxxx&api_username=yyyy

It appears that what happens is that when you deactivate the account, it ends up calling after_save, which makes a call to expire_old_email_tokens. This would normally expire all of the tokens but it doesn’t because of the following if statement inside of that function:

if password_hash_changed? && !id_changed?

Since the password hash hasn’t changed, it doesn’t actually expire the tokens. I assume that there’s some special case that this if statement is handling which is most likely being used to bypass situations where the password was updated.

The third step is to activate the account and the code that activates the user account is as follows:

  def activate
    email_token = self.email_tokens.active.first
    if email_token
      EmailToken.confirm(email_token.token)
    else
      self.active = true
      save
    end
  end

So essentially what this is doing is checking the first active email_token and if it exists, it confirms the token, EVEN if you don’t currently have it available (which via the API, you apparently can’t get at).

Two things to note about this process.

  1. I wouldn’t do other things outside of this code. It’s entirely possible for the expire_old_email_tokens to make things a bit screwy if you deactivate and activate the account more than once or don’t supply the right parameters the first time. It will basically break and you’ll need to validate the email address by sending it to them.
  2. There’s going to be a time-window here based on your installation that could potentially expire the tokens. Don’t wait too long between when you create the account and when you deactivate/activate the account. The default setting is 24 hours so it shouldn’t be a big deal if you’re doing this programmatically, but it’s something to think about.

On a side note, I really feel like if you’re programmatically creating a user, manually setting the password to a known value and are setting the account to ‘active’, the system should NOT be creating that token and forcing it to be confirmed. At the VERY least, there should be an additional parameter you can supply that would allow you to bypass the email validation on account creation.

6 Likes