Search code examples
aws-lambdaamazon-cognitoaws-amplifyaws-amplify-sdk-js

Getting AWS cognito authenticated user in post-authentication lambda trigger


I'm using Amplify with the Cognito backend to authenticate my users, essentially as an LDAP impl. This is all configured and working just fine. The users are setup in the user pool, and authenticated properly. (Note: I'm using the default Amplify controls, so it works as expected).

However, now I want to be able to pull the authenticated user and all of their data (including user attributes) so that I can update the user. As a first step, I'm trying to log the authenticated user to the console. Eventually I'll use this hook to update the user attributes by pulling some data from the DB for an update.

This is the code snippet I'm trying to use

exports.handler = async (event, context, callback) => {

    const Amplify = require('@aws-amplify/core')
    const Auth = require('@aws-amplify/auth')

    console.log("Amplify object: %o", Amplify)
    console.log("Auth object: %o", Auth)

    Amplify.configure({
        Auth: {
                identityPoolId: 'XXXX',
                region: event.region,
                userPoolId: event.userPoolId
        }
    });
    
    console.log("about to get current user");
    Auth.currentAuthenticatedUser().then(user => console.log(user));
    console.log("got current user and logged");
}

And here are a couple snippets of the output ...

INFO    Amplify object: {
  [__esModule]: true,
  Amplify: [Function: Amplify] {
    [length]: 0,
    [name]: 'Amplify',
    [prototype]: Amplify { [constructor]: [Circular] },
    register: [Function] {
      [length]: 1,
      [name]: '',
      [prototype]: { [constructor]: [Circular] }
    },
    configure: [Function] {
      [length]: 1,
      [name]: '',
      [prototype]: { [constructor]: [Circular] }
    },
    addPluggable: [Function] {
      [length]: 1,
      [name]: '',
      [prototype]: { [constructor]: [Circular] }
    },
    _components: [

and

INFO    Auth object: {
  [__esModule]: true,
  Auth: AuthClass {
    userPool: null,
    user: null,
    oAuthFlowInProgress: false,
    currentUserCredentials: [Function: bound ] { [length]: 0, [name]: 'bound ' },

and the error I receive is:

ERROR   Invoke Error    
{
    "errorType": "TypeError",
    "errorMessage": "Amplify.configure is not a function",
    "stack": [
        "TypeError: Amplify.configure is not a function",
        "    at Runtime.exports.handler (/var/task/index.js:171:13)",
        "    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
    ]
}

Solution

  • The answer for this one is that I needed to use the aws lib in my package.json. I had included it but it wasn't available. Doh!