Skip to content

Instantly share code, notes, and snippets.

@sakirtemel
Last active December 22, 2022 02:09
Show Gist options
  • Save sakirtemel/3cbdeea6753def394d5235bc4d66be97 to your computer and use it in GitHub Desktop.
Save sakirtemel/3cbdeea6753def394d5235bc4d66be97 to your computer and use it in GitHub Desktop.
// Requires HASURA_URI and HASURA_TOKEN to be set in configuration.
function (user, context, callback) {
const userId = user.user_id;
const email = user.email;
const userProfileName = user.name || email.split('@')[0].slice(0,5); // if name is not there, use first characters of the email username
const userProfilePictureUrl = user.picture;
const url = configuration.HASURA_URI;
const upsertUserQuery = `
mutation($userId: String!, $email: String, $userProfileName: String, $userProfilePictureUrl: String, $createdAt: timestamp, $updatedAt: timestamp){
insert_users_one(object: { auth0_id: $userId, email: $email, user_profile_name: $userProfileName, user_profile_picture_url: $userProfilePictureUrl, created_at: $createdAt, updated_at: $updatedAt }, on_conflict: { constraint: constraint_users_on_email, update_columns: [user_profile_picture_url, updated_at] }) {
id
}
}`;
const graphqlReq = { "query": upsertUserQuery, "variables": { "userId": userId, "email": email, "userProfileName": userProfileName, "userProfilePictureUrl": userProfilePictureUrl, "createdAt": "now()", "updatedAt": "now()" } };
// TODO: instead of using x-hasura-admin-secret, create a user which can do operations in users table
request.post({
headers: {'content-type' : 'application/json', 'x-hasura-admin-secret': configuration.HASURA_TOKEN},
url: url,
body: JSON.stringify(graphqlReq)
}, function(error, response, body){
const bodyParsed = JSON.parse(body);
context.idToken["https://hasura.io/jwt/claims"] =
{
'x-hasura-default-role': 'user',
// do some custom logic to decide allowed roles
'x-hasura-allowed-roles': ['user'],
'x-hasura-user-id': bodyParsed.data.insert_users_one.id.toString()
};
callback(null, user, context);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment