SupaGu
SupaGu

Reputation: 619

node.js server-side validation of cognito credentials

I am writing some server side login code for aws cognito and I want to verify the user who is logging in exists in the identity pool and to get the attributes assigned to them.

For email login I have this working well using the following code - using the aws-sdk:

let cognitoVerifyUser = null
            try {
                const cognitoIdProvider = new AWS.CognitoIdentityServiceProvider()
                cognitoVerifyUser = await cognitoIdProvider.adminGetUser({
                    UserPoolId: pool.userPoolId,
                    Username: username,
                }).promise()
            } catch (e) { 
                throwError(e, e.message)
            }

            if (!cognitoVerifyUser) {
                throwError(error.unauthorized, e)
            }

            const emailAttrib = cognitoVerifyUser.UserAttributes.find(a => a.Name == 'email')
            if (!cognitoVerifyUser.Enabled || cognitoVerifyUser.UserStatus != 'CONFIRMED' || username != cognitoVerifyUser.Username || email != emailAttrib.Value) {
                throwError(error.unauthorized, e)
            }

But I am stuck trying to do something similar for federated users (login via google for example). Can someone help me out?

Upvotes: 1

Views: 694

Answers (1)

Giuliano
Giuliano

Reputation: 11

import generateResponse from "../../../Utils/generateResponse";
import {
  CognitoUserPool,
  CognitoUser,
  AuthenticationDetails
} from "amazon-cognito-identity-js";
import { APIGatewayEvent } from "aws-lambda";

type LoginType = {
  email: string;
  password: string;
};

export const handler = async (event: APIGatewayEvent) => {
  try {
    const body = JSON.parse(event.body as string) as LoginType;

    const userPool = new CognitoUserPool({
      UserPoolId: process.env.COGNITO_USERPOOLID as string,
      ClientId: process.env.COGNITO_CLIENTID as string
    });

    const user = new CognitoUser({ Username: body.email, Pool: userPool });

    const authenticationData = {
      Username: body.email,
      Password: body.password
    };
    const authenticationDetails = new AuthenticationDetails(authenticationData);

    return new Promise(resolve =>
      user.authenticateUser(authenticationDetails, {
        //@ts-ignore
        onSuccess: result => {
          resolve({ body: JSON.stringify(result) });
        },
        onFailure: err => {
          resolve({ body: JSON.stringify(err) });
        }
      })
    );
  } catch (err) {
    return generateResponse({
      statusCode: 400,
      body: JSON.stringify(err, Object.getOwnPropertyNames(err))
    });
  }
};

i have a login endpoint. try that.

Upvotes: 1

Related Questions