Create users through API using explicit user ids

Hello, I’ve been using Discourse API and OAuth2 plugin to migrate and log-in users from my own SSO service to a private Discourse installation. So far, I’ve managed to programmatically migrate all SSO users to discourse successfully. When migrating programmatically, new users are created with an auto-incrementing Discourse-specific id. My question is: Can I use the API to create a user using an explicit id for that user? meaning that, if assign a user to id:22, then I can query him/her with /admin/users/22.json

I’ve tried passing ‘id’ and ‘external_id’ parameters in the POST body, but it won’t work.

edit: also, is there a way through the API, given a specific user id, to change his/her username?

Thank you

1 Like

You can’t assign the ID.

There is an external ID route:

    get "#{root_path}/by-external/:external_id" => "users#show", constraints: { external_id: /[^\/]+/ }

If you enable site setting sso_overrides_username (I think that’s a thing), you don’t need to change the username with the API.

3 Likes

Thanks, but I don’t have the external_id when the user is created. The user is created programmatically, and the association with the external SSO won’t happen until the user logs in to Discourse. Unless there is a way to programmatically associate the user with that external_id during user migration, I don’t think external_id can be used.

Do you have data in Discourse already that these users need to be associated with? Why do you need to create the users?

I need to migrate a bunch of existing users from my SSO to Discourse. These users may never log-in to Discourse directly, but it should be possible to e.g. send them messages, or retrieve their notifications via the Discourse API. This is why they should be proactively created programmatically. Furthermore, users are able to change their username on SSO, so, given an id, I need to be able to update a user’s username on Discourse as well

Did I start a new topic or did the other stuff get deleted somehow?

It would seem like the SSO would have the account and would know an external ID that you could use to create the user record and then use that in the future. But if that’s impossible somehow, you could try finding the user by email address–you could even create a second email address that was bogus (since what if they change their real email address?) and then maybe hide it somehow so that you could use that as an identifier going forward.