AWS:列出Lambda函数中的Cognito用户

时间:2018-02-07 10:51:14

标签: amazon-web-services aws-lambda amazon-cognito

我尝试从Lambda函数访问AWS Cognito UserPool。该功能配置为池的PreSignUp触发器。这是我的lambda代码(注意,我用TypeScript开发):

import { CognitoUserPoolEvent, Handler, Context, Callback } from 'aws-lambda';
import { CognitoIdentityServiceProvider } from 'aws-sdk';

export const onPreSignUp: Handler =
  (event: CognitoUserPoolEvent, context: Context, cb: Callback | undefined) => {
    context.callbackWaitsForEmptyEventLoop = false;
    const userAttr = event.request.userAttributes || undefined;
    console.log(userAttr);

    if (cb) {
      const cognitoPoolId = process.env.COGNITO_USER_POOL_ID;
      const email = userAttr.email || userAttr['cognito:email_alias'];

      if (!cognitoPoolId) {
        console.warn('No user pool id defined', cognitoPoolId);
        return cb(new Error('Can not create user'));
      }

      const identityService = new CognitoIdentityServiceProvider();

      const params = {
        UserPoolId: cognitoPoolId,
        Filter: `email = "${email}"`,
      };

      console.log("try to list users", params);
      identityService.listUsers(params, (err, data) => {
        console.log('list users');
        if (err) {
          console.warn('listUsers Error', err);
          return cb(new Error('Can not create user'));
        }
        console.log("data", data);
        return cb(null, 'todo');
      });
    }
  }

不幸的是listUsers的回调永远不会回来。如果我传递了无效的params对象,则回调会立即返回。

我还尝试将lambdas超时设置为max(5分钟)并增加RAM。什么都没有帮助。 lambda执行角色具有AmazonCognitoReadOnly,它提供完全读取访问权限。如果这是一个问题,我也会发现授权错误。

编辑:我发布这个之后就解决了我的问题:lambda配置为在VPC中运行。将VPC设置为无解决方案。

1 个答案:

答案 0 :(得分:1)

此代码对我有用:

module.exports.getUserByAttribute = async (attributeName, attributeValue) => {
  const params = {
      UserPoolId: process.env.userPoolId,
      Filter: `${attributeName} = "${attributeValue}"`,
  }
  try {
      const data = await cognitoIdentityService.listUsers(params).promise()
      const existingUser = data.Users.filter(user => user.UserStatus !== 'EXTERNAL_PROVIDER')[0]
      if (existingUser == null) {
          console.log('Error', 'User not found')
      }
      return existingUser
  } catch (error) {
      console.log('Error: getUserByAttribute', error)
  }
}