should I put Cognito delete user logic in frontend or backend?

Viewed 152

For the cognito user creation in my website, the logic will like below.

Register.jsx

import { Auth } from "aws-amplify";
...
            // create user in Cognito User Pool in frontend
            const signUpResponse = await Auth.signUp({
                username,
                password,
                attributes: {
                    email: email
                }
            })
            // using lambda function and api gateway for this request
            // in order to create user in my "User" table in Dynamodb
            const createAdminResponse = await APIHandler.createAdmin(payload)
...

User Table
-id(string): partition key

For the user deletion, I am thinking what is the best way to do it.
This is my current lambda function to delete user in database

'use strict'
const AWS = require('aws-sdk');

exports.handler = async function (event, context, callback) {
    const documentClient = new AWS.DynamoDB.DocumentClient();

    let responseBody = "";
    let statusCode = 0;

    const { id } = event.pathParameters;

    const params = {
        TableName : "User",
        Key: {
            id: id,
        }
    };

    try{
        const data = await documentClient.delete(params).promise();
        responseBody = JSON.stringify(data);
        statusCode = 204
    }catch(err){
        responseBody = `Unabel to delete admin: ${err}`;
        statusCode = 403
    }

    const response = {
        statusCode: statusCode,
        headers:{
            "Content-Type": "application/json",
            "access-control-allow-origin": "*"
        },
        body: responseBody
    }

    return response
}

I am considering whether I delete user in cognito user pool on frontend or include in above lambda function, or create a separate lambda function .

This is copied from the doc.

const AWS = require('aws-sdk');
AWS.config.update({
  accessKeyId: 'access key id',
  secretAccessKey: 'secret access key',
  region: 'region',
});
const cognito = new AWS.CognitoIdentityServiceProvider();

await cognito.adminDeleteUser({
  UserPoolId: 'pool id',
  Username: 'username',
}).promise();

If I use it in lambda function, I also need to include my aws config in the code, isn't it bad practise?

But I am not sure where I should use the code, can anyone give some advice?

1 Answers

The design is really up to you, it depends on multiple factors but I draft here a bit of options

  1. If you have only 1 front-end client and you would like to wrap your feature quickly, so you can put the logic directly to front-end

  2. If you have multiple front-end such as web, app, ... so you better put logic from back-end as api so it can be re-used across

  3. If you are planning to extend your logic so you better put logic from back-end

Related