AWS Cognito User pool을 DynamoDB에 저장하기

이경은·2022년 4월 7일
0

0. 들어가기

Cognito user pool은 사용자 정보를 담고 있는 디렉터리이다. 이 정보를 DB로 Export하는 기능은 없고, 회원가입 시에 Post confirm lambda를 트리거해서 Lambda에서 user 정보를 DB에 저장하도록 구현했다.
Cognito user pool의 Lambda에 대해서는 공식 문서를 참조.

1. Create User pool

User Pool은 이미 만들어져 있고, 속성은 아래와 같다.
사용자 ID, Email, name, sub로 구성되어 있다.

2. Create DynamoDB Table

사용자 ID를 파티션 키로 사용하는 테이블 생성.
모든 설정은 기본으로 사용했고, 파티션 키를 ID, 타입은 String으로 설정하고 생성했다.

3. Create Lambda

DB에 저장하는 Lambda를 작성. Lambda 콘솔에서 AddUserFunc이라는 람다를 만들고, 아래의 코드를 작성했다.
index.js

var aws = require('aws-sdk');
var ddb = new aws.DynamoDB({apiVersion: '2012-10-08'});

exports.handler = async (event, context) => {
    console.log(event);

    let date = new Date();

    
    // If the required parameters are present, proceed
    if (event.request.userAttributes.sub) {

        // -- Write data to DDB
        let ddbParams = {
            Item: {
                'id': {"S": event.request.userAttributes.sub},
                '__typename': {"S": 'User'},
                'username': {"S": event.userName},
                'name': {"S": event.request.userAttributes.name},
                'email': {"S": event.request.userAttributes.email}
            },
            TableName: "sampleUserPoolTbl"
        };

        // Call DynamoDB
        try {
            await ddb.putItem(ddbParams).promise()
            console.log("Success");
        } catch (err) {
            console.log("Error", err);
        }

        console.log("Success: Everything executed correctly");
        context.done(null, event);

    } else {
        // Nothing to do, the user's email ID is unknown
        console.log("Error: Nothing was written to DDB or SQS");
        context.done(null, event);
    }
};

4. Post confirm Lambda

사용자 풀 속성에서 Post confirm Lambda 트리거를 추가함.

5. Test

Sign up

구현 해둔 react 앱에서 회원가입.
user pool에는 당연히 사용자가 생성되었고, DB를 확인해보면 사용자 정보가 잘 저장된 것을 확인할 수 있다.

참조

https://docs.amplify.aws/guides/functions/cognito-trigger-lambda-dynamodb/q/platform/js/#create-the-lambda-function

https://velog.io/@seunghwa17/Cognito-User-Pool-정보-DynamoDB에-저장하기

profile
Web Developer

0개의 댓글