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.
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 await
ed 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With