Reputation: 53850
I want to check if a user is authenticated in my app. The issue is I don't want to be cursed by the JS Lord if I use it in synchronous manner. What I want ideally is to have a function
Api.User.isAuthenticated()
which I would run like this:
if (Api.User.isAuthenticated())
{
Views.renderDashboard()
}
else
{
Views.renderLogin()
}
Right now I implemented this function as a promise and it works fine but looks overcomplicated for simple things like checking user login status.
I use qwest library to make XHR requests. It returns promises, code looks like this:
Api.User.isAuthenticated = function(token)
{
return qwest.get('/session', token)
}
Api.User.isAuthenticated(token)
.then(function (response) {
//
})
.catch(function (e, response) {
//
});
How should I approach this problem?
Upvotes: 0
Views: 173
Reputation: 12535
If your authentication method requires async, you could try simply using a callback:
Api.User.checkAuthentication = function(token, callback) {
qwest.get('/session', token).then(function (response) {
// Check your response here, send true or false to the callback as appropriate
callback(true);
})
.catch(function (e, response) {
// You should probably notify the user of the error here, that it wasn't
// just an invalid username/password combo
callback(false);
});
}
Api.User.checkAuthentication('token', function (authenticated) {
if (authenticated) {
Views.renderDashboard();
} else {
Views.renderLogin();
}
})
This whole method could be put into a function, say, checkAuth()
, which can be called when needed. You could go further and pass callbacks to checkAuth, to run custom code when we check if the user is authenticated or not.
Upvotes: 1