Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import AWS from 'aws-sdk/global';
- import S3 from 'aws-sdk/clients/s3';
- import {
- AuthenticationDetails,
- CognitoUser,
- CognitoUserPool,
- } from 'amazon-cognito-identity-js';
- const REGION = 'some-string-value';
- const USER_POOL_ID = 'some-string-value';
- const IDENTITY_POOL_ID = 'some-string-value';
- const APP_CLIENT_ID = 'some-string-value';
- const POOL_KEY = `cognito-idp.${REGION}.amazonaws.com/${USER_POOL_ID}`;
- let Username = 'some-string-value';
- let Password = 'some-string-value';
- let authenticationDetails = new AuthenticationDetails({
- Username,
- Password
- });
- let userPool = new CognitoUserPool({
- UserPoolId: USER_POOL_ID,
- ClientId: APP_CLIENT_ID
- });
- let cognitoUser = new CognitoUser({
- Username,
- Pool: userPool
- });
- let skateboards = {
- mfaRequired(codeDeliveryDetails) {
- let mfaCode = prompt('MFA code is required!');
- cognitoUser.sendMFACode(mfaCode, mfaRequired);
- },
- newPasswordRequired(userAttributes, requiredAttributes) {
- delete userAttributes.email_verified; // it's returned but not valid to submit
- let newPassword = prompt('A new password is required!');
- cognitoUser.completeNewPasswordChallenge(newPassword, userAttributes, newPasswordRequired);
- }
- };
- let updateAWSCreds = (jwtToken) => {
- AWS.config.credentials = new AWS.CognitoIdentityCredentials({
- IdentityPoolId: IDENTITY_POOL_ID,
- Logins: {
- [POOL_KEY]: jwtToken
- }
- });
- };
- let authenticateCognitoUser = async ({mfaRequired, newPasswordRequired} = skateboards) => {
- return new Promise((resolve, reject) => {
- cognitoUser.authenticateUser(authenticationDetails, {
- onSuccess(result) {
- let jwtToken = result.getIdToken().getJwtToken();
- updateAWSCreds(jwtToken);
- resolve();
- },
- onFailure(err) {
- reject(err);
- },
- mfaRequired,
- newPasswordRequired
- });
- });
- };
- let doSomethingInS3ForExample = async () => {
- await authenticateCognitoUser();
- // now do your stuff
- };
- doSomethingInS3ForExample();
Add Comment
Please, Sign In to add comment