Created
March 31, 2023 07:52
-
-
Save jack-sparroow/a1cf195ba12a6500e92801dc1056608c to your computer and use it in GitHub Desktop.
Pretoken Lambda function to query data from mongo db and insert user info in custom claims
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const MongoClient = require('mongodb').MongoClient; | |
exports.handler = async (event, context) => { | |
const { sub: userId } = event.request.userAttributes; | |
const uri = '<your-mongodb-uri>'; | |
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); | |
try { | |
await client.connect(); | |
const database = client.db('<your-db-name>'); | |
const usersCollection = database.collection('<your-users-collection-name>'); | |
const user = await usersCollection.findOne({ userId }); | |
if (!user) { | |
throw new Error('User not found'); | |
} | |
const email = user.email; | |
const claims = event.request.groupConfiguration.groupsToOverride.reduce((acc, group) => { | |
acc[group] = true; | |
return acc; | |
}, {}); | |
claims.email = email; | |
event.response = { | |
claimsOverrideDetails: { | |
claimsToAddOrOverride: claims, | |
}, | |
}; | |
} catch (err) { | |
console.error(err); | |
throw new Error('Failed to add user email to token'); | |
} finally { | |
await client.close(); | |
} | |
return event; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment