aws-sdk#CognitoIdentityServiceProvider TypeScript Examples

The following examples show how to use aws-sdk#CognitoIdentityServiceProvider. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CognitoIdentityService.ts    From affinidi-core-sdk with Apache License 2.0 6 votes vote down vote up
private _normalizeTokensFromCognitoAuthenticationResult(
    AuthenticationResult: AWS.CognitoIdentityServiceProvider.AuthenticationResultType,
  ): CognitoUserTokens {
    const { AccessToken: accessToken, IdToken: idToken, RefreshToken: refreshToken, ExpiresIn } = AuthenticationResult

    // NOTE: ExpiresIn = 3600, in seconds which is 1h
    const expiresIn = Date.now() + ExpiresIn * 1000

    return { accessToken, idToken, refreshToken, expiresIn }
  }
Example #2
Source File: sdk-calls.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
getUserPool = async (userpoolId, region) => {
  config.update({ region });
  let res;
  try {
    res = await new CognitoIdentityServiceProvider().describeUserPool({ UserPoolId: userpoolId }).promise();
  } catch (e) {
    console.log(e);
  }
  return res;
}
Example #3
Source File: sdk-calls.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
getUserPoolClients = async (userPoolId: string, clientIds: string[], region: string) => {
  const provider = new CognitoIdentityServiceProvider({ region });
  const res = [];
  try {
    for (let i = 0; i < clientIds.length; i++) {
      const clientData = await provider
        .describeUserPoolClient({
          UserPoolId: userPoolId,
          ClientId: clientIds[i],
        })
        .promise();
      res.push(clientData);
    }
  } catch (e) {
    console.log(e);
  }
  return res;
}
Example #4
Source File: authHelper.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
export async function addUserToGroup(
  cognitoClient: CognitoIdentityServiceProvider,
  userPoolId: string,
  username: string,
  groupName?: string,
) {
  await cognitoClient
    .adminAddUserToGroup({
      UserPoolId: userPoolId,
      Username: username,
      GroupName: groupName,
    })
    .promise();
}
Example #5
Source File: authHelper.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
export function getConfiguredCognitoClient(): CognitoIdentityServiceProvider {
  const cognitoClient = new CognitoIdentityServiceProvider({ apiVersion: '2016-04-19', region: process.env.CLI_REGION });

  const awsconfig = {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: process.env.CLI_REGION,
  };

  cognitoClient.config.update(awsconfig);

  return cognitoClient;
}
Example #6
Source File: users.ts    From office-booker with MIT License 6 votes vote down vote up
getUserCognito = async (config: Config, userEmail: string) => {
  if (config.authConfig.type !== 'cognito') {
    return { email: userEmail };
  }
  const cognito = new CognitoIdentityServiceProvider();
  try {
    const cognitoUser = await cognito
      .adminGetUser({ UserPoolId: config.authConfig.cognitoUserPoolId, Username: userEmail })
      .promise();
    return {
      email: userEmail,
      created: cognitoUser.UserCreateDate?.toISOString(),
    };
  } catch (err) {
    if (err.code === 'UserNotFoundException') {
      return undefined;
    } else {
      throw err;
    }
  }
}
Example #7
Source File: queryUsers.ts    From office-booker with MIT License 6 votes vote down vote up
getCognitoUsers = async (
  config: Config,
  paginationToken?: string,
  emailPrefix?: string
): Promise<{ users: User[]; paginationToken?: string }> => {
  if (config.authConfig.type !== 'cognito') {
    return { users: [] };
  }
  const cognito = new CognitoIdentityServiceProvider();
  const filter = emailPrefix === undefined ? "status='Enabled'" : `email^='${emailPrefix}'`;
  const cognitoResponse = await cognito
    .listUsers({
      UserPoolId: config.authConfig.cognitoUserPoolId,
      AttributesToGet: ['email'],
      Filter: filter,
      Limit: 60,
      PaginationToken: paginationToken,
    })
    .promise();
  const cognitoEmails = (cognitoResponse.Users ?? [])
    .map((user) => user.Attributes?.[0].Value as string)
    .filter((e) => e !== undefined);
  const dbUsers = await getUsersDb(config, cognitoEmails);
  return {
    users: dbUsers.map((u) => makeUser(config, u)),
    paginationToken: cognitoResponse.PaginationToken,
  };
}
Example #8
Source File: register.ts    From office-booker with MIT License 6 votes vote down vote up
registerUser = async (config: Config, email: string) => {
  if (config.authConfig.type !== 'cognito') {
    return;
  }
  await ensureUserExists(config, {
    email,
    adminOffices: [],
    quota: config.defaultWeeklyQuota,
    autoApproved: false,
    created: new Date().toISOString(),
  });

  const cognito = new CognitoIdentityServiceProvider();
  try {
    await cognito
      .adminCreateUser({
        UserPoolId: config.authConfig.cognitoUserPoolId,
        Username: email,
        MessageAction: 'SUPPRESS',
      })
      .promise();
  } catch (err) {
    if (err.code !== 'UsernameExistsException') {
      throw err;
    }
  }
  return;
}
Example #9
Source File: util.ts    From flect-chime-sdk-demo with Apache License 2.0 6 votes vote down vote up
provider = new CognitoIdentityServiceProvider()
Example #10
Source File: util.ts    From flect-chime-sdk-demo with Apache License 2.0 6 votes vote down vote up
getEmailFromAccessToken = async (accessToken: string) => {
    const tokens = accessToken.split(",");
    if (tokens.length === 1) {
        const p = new Promise<CognitoIdentityServiceProvider.GetUserResponse>((resolve, reject) => {
            provider.getUser({ AccessToken: tokens[0] }, (err, data) => {
                // console.log(err);
                if (err) {
                    console.log("[getEmailFromAccessToken] token is not cognito accessToken");
                    reject("[getEmailFromAccessToken] token is not cognito accessToken");
                }
                console.log(data);
                resolve(data);
            });
        });
        const userData = await p;
        let email;
        let foundEmail = false;
        for (let i = 0; i < userData.UserAttributes.length; i++) {
            const att = userData.UserAttributes[i];
            if (att["Name"] == "email") {
                email = att["Value"];
                foundEmail = true;
            }
        }
        if (foundEmail) {
            return email;
        } else {
            console.log("email not found");
            throw "email not found";
        }
    } else if (tokens.length === 2) {
        if (tokens[0] === "slack") {
            const urlEncrypter = new Encrypter<UserInformation>({
                password: process.env.SLACK_APP_DB_PASSWORD || "pass",
                salt: process.env.SLACK_APP_DB_SALT || "salt",
                secret: process.env.SLACK_APP_DB_SECRET || "secret",
                expireSec: 60 * 60, // 60min
            });
            const userInfo = urlEncrypter.decodeInformation(tokens[1]);
            console.log(`Slack Federated Authentification userInfo: ${JSON.stringify(userInfo)}`);
            return userInfo.userId;
        } else {
            console.log(`unknown provider ${tokens[0]}`);
            throw `unknown provider ${tokens[0]}`;
        }
    } else {
        console.log("this token format is not supported");
        throw "this token format is not supported";
    }
}
Example #11
Source File: CognitoIdentityService.ts    From affinidi-core-sdk with Apache License 2.0 5 votes vote down vote up
constructor({ region, clientId }: { region: string; clientId: string }) {
    this.clientId = clientId
    this.cognitoidentityserviceprovider = new CognitoIdentityServiceProvider({
      region,
      apiVersion: '2016-04-18',
    })
  }