It depends; the recommended implementation would require knowing all the exact details.
For example, assuming that:
- an end-user may or may not have roles defined in
app_metadata.roles
and if they have then it’s an array of roles. - you want to augment those roles in rules with other roles, but these other roles don’t need to be persisted to metadata as they are only relevant in responses that go through rules.
Then the following simplified rule could do the trick:
function (user, context, callback) {
var roles = user.app_metadata.roles || ];
if (context.stats.loginsCount < 2) { roles.push("new"); }
// do other stuf that can add roles
// add roles to the response (ID token or access token; assuming OIDC/OAuth2)
callback(null, user, context);
}