Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- exports = module.exports = function checkAuthentication(Y) {
- var NS = Y.namespace('TDP'),
- /**
- This is our model for handling all authentication. Tt will query against
- two different URLs depending upon if it needs a code or an access token.
- **/
- OAuthModel = Y.Base.create('oauthModel', Y.Model, [ Y.ModelSync.REST ],
- {
- get_token : global.config.webservices.path + '/api/oauth/access_token',
- authorize : global.config.webservices.path + '/api/oauth/authorize',
- getURL : function() {
- if ( this.get('code') ) {
- this.url = this.get_token;
- } else {
- this.url = this.authorize;
- }
- return Y.ModelSync.REST.prototype.getURL.apply(this, arguments);
- }
- },
- {
- ATTRS : {
- email : { },
- password : { },
- // These should *only* be available on the server. They are private!
- client_id : { value : 'your-app-client-id' },
- client_secret : { value : 'your-app-client-secret' },
- access_token : { },
- token_type : { },
- code : { }
- }
- }
- );
- /**
- The Express handler for determining if the user is logged in.
- **/
- return function(req, res, next) {
- // We attach models to the request, so we can load things as we go and
- // keep them
- if ( ! Y.Lang.isObject( req.models ) ) {
- req.models = { };
- }
- var oauth,
- person = new NS.Person();
- // Do we have an auth token to try? If so, use that and try to load the
- // person. If it fails, we go to the login page.
- if ( req.session.oauth && req.session.oauth.access_token ) {
- oauth = new OAuthModel(req.session.oauth);
- person.load(
- { headers : { 'X-Access-Token' : oauth.get('access_token') } },
- function(err, res) {
- if ( err && err.code === 403 ) {
- res.redirect('/login');
- return;
- }
- req.models.Person = person;
- next();
- }
- );
- }
- else if ( req.method === 'POST' && req.body.email && req.body.password ) {
- oauth = new OAuthModel({
- email : req.body.email,
- password : req.body.password
- });
- // The first save is the password test.
- oauth.save( function(err, res) {
- if ( err ) {
- Y.log('Failed authentication, going to login page', 'debug');
- req.session.error = res;
- res.redirect('/login');
- return;
- }
- oauth.save( function(err, res) {
- if ( err ) {
- Y.log('Error fetching user token.', 'debug');
- req.session.error = res;
- res.redirect('/login');
- return;
- }
- req.session.oauth = oauth.toJSON();
- person.load(
- { headers : { 'X-Access-Token' : oauth.get('access_token') } },
- function(err, res) {
- if ( err ) {
- req.session.error = err;
- res.redirect('/login');
- return;
- }
- next();
- }
- );
- });
- });
- } else {
- res.redirect('/login');
- return;
- }
- }
- };
Add Comment
Please, Sign In to add comment