Phonegap Boilerplate support authentication via token. Authentication is opt-in.
Description :
The server Authentication module creates the following routes :
It adds the server.authenticateMiddleware, an express middleware that you must use in your route to require authentication.
Installation :
Require the Authentication module :
var auth = require('../core/server_modules/Authentication');
Add authentication to the server :
auth.addTo(server); // server is a RestServer instance
Configure the authentication (implements 3 methods) :
auth.findUserByToken = function(token, done) {
// Code to search user by token
// Error
done('Error description');
// Success (the user is returned if found)
// /!\ Important, the returned user must have a 'token' property.
done(null, user);
};
auth.findUserByUsernameAndPassword = function(username, password, done) {
// Code to search user by username/password
// Error
done('Error description');
// User found
// /!\ Important, the returned user must have a 'token' property.
done(null, user);
};
auth.updateUserToken = function(user, token, done) {
// Code to update user token
// Error
done('Error description');
// Success
// If for some reason, you want to override the generated token, you can pass
// the new token as the second parameter to the done callback.
done();
};
Authenticate a user :
To authenticate a user, use the authenticate middleware :
server.app.get('/my-route', server.authenticate, function (req, res) {
// If req.user is available, the user is authenticated
});
Require authentication :
If you want your route to be only accessible to authenticated users, use the requireAuthentication middleware :
server.app.get('/my-route', server.requireAuthentication, function (req, res) {
// This method is called if the user is authenticated
// Otherwise, the user get a 401 error
});
Add useAuth: true in your config file (www/js/config.js).
To authenticate a user, require app/singletons/auth, then use :
auth.login(username, password, callback(loginSuccess))
An access token will automatically be added in each GET/POST request.
To check if a user is logged in, use the property : auth.loggedIn.
Later, you can access user information via auth.user.
Finally, to log out a user, use :
auth.logout(callback)
When the user is authenticated, his token is automatically passed in all the HTTP requests made with the ApiHelper :
```js define(['app/singletons/api'], function (api) {
// If the user is authenticated, this send a HTTP request on
// host:port/my-route with the following query string :
// myParameter=toast&access_token=<user-token>
api.get('/my-route', {
data: {
myParameter: 'toast',
}
});
})