Assign role to user on register

Is there any way I can have open registration but instead if assigning a default role, pass a role name or id on registration?

This way i can have users register with different roles

Thanks

Server side scripting can do this. I’m working on exactly the same thing at the moment and the script id you would need to do this is:

event scripts > user/register/user.register.post.pre_process

I’ll share my code when I’ve completed my solution but it’ll be end of the week earliest.

Hey @antonyjsmith

did you manage to do this?

Thanks

Can anyone share an example of how they did this? Assigning role id when registering through api. @antonyjsmith

You would want to do an event script on user.register.post.post_process
there are two key objects you’ll want to get in your testing to see how everything is processed, event.request, and event.response
You can write a script that simply says

var_dump(event.request);
var_dump(event.response);

This will dump the objects into your log so you can look through them and see the structure.

In your script, first you’ll want to check for event.response.success === true
because you only want to set this for successful registrations.
If you’re using email confirmation, then you also want to check if event.request.payload.code exists. If it does then that indicates that this POST was a user confirming their account

From there you just use platform.api to assign the role. You’ll want to familiarize yourself with the system/user response object.
Specifically, the related field user_to_app_to_role_by_user_id (/api/v2/system/user/{id}?related=user_to_app_to_role_by_user_id)
A new user should not have anything in this field.
You can use platform.api.patch to update the user object role assignment.
In this example, my newly created user’s id is 4, and the app and role ids I want to user are both 1.

PATCH /api/v2/system/user/4?relate=user_to_app_to_role_by_user_id

{
    "user_to_app_to_role_by_user_id": [
        {
            "user_id": 4,
            "app_id": 1,
            "role_id": 1
        }
    ]
}
2 Likes

user_to_app_to_role_by_user_id didn’t work for me.

I had to use user_to_app_to_role:

curl -X PATCH --header ‘Content-Type: application/json’ --header ‘Accept: application/json’ --header ‘X-DreamFactory-Api-Key: 36fda24fe5588fa4285ac6c6c2fdfbdb6b6bc9834699774c9bf777f706d05a88’ --header 'X-DreamFactory-Session-Token: ’ --header ‘Authorization: Basic Y3J5c3RhbEBidWlsZG15YXBwLnRvZGF5OmhGOV40WFAyQFJUbQ==’ -d '{

"user_to_app_to_role": [
    {
        "user_id": 14,
        "app_id": 7,
        "role_id": 4
    }
]

}’ ‘http:///api/v2/system/user/14’

1 Like