Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aws-amplify auth currentSession returns no current user

Use: Nodejs + aws-amplify

From the aws amplify documentation, but I have not successfully checked user after they signed in.

index.js

const Amplify = require('aws-amplify');
global.fetch = require('node-fetch'); // [source](https://github.com/aws-amplify/amplify-js/issues/876)
global.navigator = {};

Amplify.default.Auth({
    identityPoolId: IDENTITYPOOLID,
    region: REGION,
    userPoolId: USERPOOLID,
    userPoolWebClientId: APPCLIENTID,
});

Amplify.Auth.signIn(username, password).then(user => {
    localstorage.set('user', JSON.stringify(user));
    console.log(user); // "cognitoUser" object
    return Amplify.Auth.getSession();
}).then(session => {
    console.log(session); // "CognitoSession" object
}).catch(err => {
    console.log(err);
});

// PROBLEM
Amplify.Auth.getSession().then(session => {
    console.log(session);
}).catch(err => {
    console.log(err); // PRINT: no current user
});

It looks like I cannot get user session, unless it is wrapped inside Auth.signIn. I tried to use;

// Problem
let userObj = JSON.parse(localstorage.get('use'));
Amplify.Auth.userSession(userObj).then(data => {
    console.log(data);
});
/// getSession is not a function

console.log(Amplfy.Auth.userSession); // PRINT: [Function]

I can verify that userSession is function and inside the lib, and the problem i see is that getSession() is not inside the CognitoUser object I store in the localstorage.

I cannot find any functions that help me convert the localstorage object to CognitoObj if that is the problem. The only thing i can do is signing user in each time which is neglect the whole purpose of this lib.

Have I missed something? why is Amplify.Auth does not work? Is there a way I can check either user's session is not expired and manually refresh it?

I have similiar issue to github.

like image 865
roger Avatar asked Dec 05 '18 10:12

roger


1 Answers

It looks like I cannot get user session, unless it is wrapped inside Auth.signIn

That's the Node/JS async programming model in a nutshell. If you have some temporal dependency between asynchronous actions, you have to wrap the later actions in callbacks or then, and/or conversely the earlier actions in awaited promises.

In fact, if you have some asynchronous operations that can be run concurrently / have no dependencies between each other, you can optimize your code with the Promise.all API so that it sends all async requests at the same time and resolves when the last one finishes.

Top-level await will probably help resolve use cases like this.

like image 195
jkeys Avatar answered Sep 19 '22 23:09

jkeys