Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { CognitoIdentityServiceProvider } = require("@aws-sdk/client-cognito-identity-provider");
- const openfort = require('@openfort/openfort-node').default;
- const openfortClient = new openfort("SECRET");
- exports.handler = async function(event, context, callback) {
- try {
- // Extract the ID token from the event
- const idToken = getIdTokenFromEvent(event);
- // If ID token is not found, log an error and return an error response
- if (!idToken) {
- console.error("ID token not found in the event.");
- const response = {
- statusCode: 400,
- body: JSON.stringify({ success: false, message: 'ID token not found in the event.' })
- };
- return callback(null, response);
- }
- // Use the ID token to decode and get user information
- const userId = await getUserIdFromToken(idToken);
- // Use the userId as the thirdPartyUserId in your request
- const req = {
- preGenerateEmbeddedAccount: true,
- thirdPartyProvider: "oidc",
- thirdPartyUserId: userId,
- };
- const embeddedReq = {
- shieldAuthProvider: openfort.ShieldAuthProvider.Openfort,
- apiKey: "SECRET",
- apiSecret: "SECRET",
- encryptionPart: "SECRET",
- };
- // Invoke the Lambda function
- const openfortSession = await openfortClient.iam.createAuthPlayer(req, embeddedReq);
- // Return the updated event back to Amazon Cognito
- return callback(null, event);
- } catch (error) {
- // Handle any errors
- console.error("Error occurred:", error);
- const response = {
- statusCode: 500,
- body: JSON.stringify({ success: false, message: 'An error occurred while processing the request.' })
- };
- return callback(null, response);
- }
- };
- // Function to extract the ID token from the event
- function getIdTokenFromEvent(event) {
- if (event && event.requestContext && event.requestContext.identity && event.requestContext.identity.cognitoAuthenticationProvider) {
- return event.requestContext.identity.cognitoAuthenticationProvider.split(':').pop();
- } else {
- return null; // Return null if required properties are not present
- }
- }
- // Function to get the user ID from the access token
- async function getUserIdFromToken(token) {
- try {
- const cognitoIdentityServiceProvider = new CognitoIdentityServiceProvider();
- const params = { AccessToken: token };
- const data = await cognitoIdentityServiceProvider.getUser(params);
- return data.sub;
- } catch (error) {
- console.error("Error decoding token:", error);
- throw new Error("Failed to decode token");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement