<commit_before>/**
 * Shoptology Auth module
 *
 * We secure our API endpoints using OAuth2.
 * Since right now, we are running both the
 * auth server and creating the client consumer,
 * we are focused on the password exchange method
 * for retrieving an access token from a username/password.
 *
 * We'll use the user email address as the username.
 *
 * @todo we'll make the models be passed in via the constructor options
 */


var EventEmitter = require( 'events' ).EventEmitter,
    hat          = require( 'hat' ),
    oauth2orize  = require( 'oauth2orize' ),
    hat          = require( 'hat' ),
    bcrypt       = require( 'bcrypt' ),
    _            = require( 'lodash' ); // @todo should this be underscore?

var Auth = function Auth( options ) {
    this._server = null;
    this.options( options );
};

Auth.prototype.__proto__ = EventEmitter.prototype;

Auth.prototype.options = function options( options ) {
    this._options = _.extend( {
        userModel: null,
        accessTokenModel: null
    }, options );
};

Auth.prototype.server = function server( ) {
    if ( !this._server ) {
        this._server = oauth2orize.createServer();
        this.configureServer( this._server );
    }
    return this._server;
};

Auth.prototype.configureServer = function configureServer( server ) {
    server.grant( oauth2orize.grant.token( this.createToken ) );
    // https://github.com/jaredhanson/oauth2orize/issues/28#issuecomment-15856324
    server.exchange( oauth2orize.exchange.password( this.exchangePassword ) );
};

Auth.prototype.generateToken = function generateToken( ) {
    return hat(512, 16);
};

Auth.prototype.createToken = function createToken( client, user, scope, done ) {
    var AccessToken;

    // we don't really care about clients right now,
    // if we did, we would probably want to verify the client is registered
    if ( !client ) {
        client = { id: '12345' };
    }

    if ( !this._options.accessTokenModel ) {
        throw "AccessToken model must be provided to the auth module.";
    }
    AccessToken = this._options.accessTokenModel;

    // @todo This could become a required static method of the model to decouple this module from the models
    //       We would pass in a method to generate a token so the model doesn't implement that.
    //       ex.
    //       AccessToken.createToken( client, user, scope, this.generateToken, done );
    AccessToken.find( {
        token: token
    } ).then( function( results ) {
        if ( results.length ) { // @todo <-- total guess that results.length checks to see if any were found
                                //           need to look at mongoose docs
            Auth.createToken( user, done );
            return;
        }
        AccessToken.create( {
            token: token,
            userId: user._id, // @todo with mongoose, can this just be user.id?
            clientId: client.id,
            valid: true
        }, function( err ) {
            if ( err ) {
                return done( err );
            }
            done( null, token );
        } );
    } );
};

// SRP would be nice... but requires multiple steps,
// probably just stick with sending passwords over the line.
// We'll be using SSL/TLS anyway.
//
// Here's an example that's not far from what we're doing.
// Except we're not going to bother with the refresh token ( and the refresh
// token example in here is not very secure since it doesn't check the client secret )
// http://rwlive.wordpress.com/2014/06/24/oauth2-resource-owner-password-flow-using-oauth2orize-express-4-and-mongojs/
Auth.prototype.exchangePassword = function exchangePassword( client, username, password, scope, done ) {
    var AccessToken;

    if ( !this._options.accessTokenModel ) {<commit_msg>Binding this inside of auth.js<commit_after>/**
 * Shoptology Auth module
 *
 * We secure our API endpoints using OAuth2.
 * Since right now, we are running both the
 * auth server and creating the client consumer,
 * we are focused on the password exchange method
 * for retrieving an access token from a username/password.
 *
 * We'll use the user email address as the username.
 *
 * @todo we'll make the models be passed in via the constructor options
 */


var EventEmitter = require( 'events' ).EventEmitter,
    hat          = require( 'hat' ),
    oauth2orize  = require( 'oauth2orize' ),
    hat          = require( 'hat' ),
    bcrypt       = require( 'bcrypt' ),
    _            = require( 'lodash' ); // @todo should this be underscore?

var Auth = function Auth( options ) {
    this._server = null;
    this.options( options );
};

Auth.prototype.__proto__ = EventEmitter.prototype;

Auth.prototype.options = function options( options ) {
    this._options = _.extend( {
        userModel: null,
        accessTokenModel: null
    }, options );
};

Auth.prototype.server = function server( ) {
    if ( !this._server ) {
        this._server = oauth2orize.createServer();
        this.configureServer( this._server );
    }
    return this._server;
};

Auth.prototype.configureServer = function configureServer( server ) {
    server.grant( oauth2orize.grant.token( this.createToken.bind( this ) ) );
    // https://github.com/jaredhanson/oauth2orize/issues/28#issuecomment-15856324
    server.exchange( oauth2orize.exchange.password( this.exchangePassword.bind( this ) ) );
};

Auth.prototype.generateToken = function generateToken( ) {
    return hat(512, 16);
};

Auth.prototype.createToken = function createToken( client, user, scope, done ) {
    var AccessToken, auth = this;

    // we don't really care about clients right now,
    // if we did, we would probably want to verify the client is registered
    if ( !client ) {
        client = { id: '12345' };
    }

    if ( !this._options.accessTokenModel ) {
        throw "AccessToken model must be provided to the auth module.";
    }
    AccessToken = this._options.accessTokenModel;

    // @todo This could become a required static method of the model to decouple this module from the models
    //       We would pass in a method to generate a token so the model doesn't implement that.
    //       ex.
    //       AccessToken.createToken( client, user, scope, this.generateToken, done );
    var token = this.generateToken();
    AccessToken.find( {
        token: token
    } ).then( function( results ) {
        if ( results.length ) { // @todo <-- total guess that results.length checks to see if any were found
                                //           need to look at mongoose docs

            // if moved to AccessToken model, this would call AccessToken.createToken instead
            auth.createToken( client, user, scope, done );
            return;
        }
        AccessToken.create( {
            token: token,
            userId: user._id, // @todo with mongoose, can this just be user.id?
            clientId: client.id,
            valid: true
        }, function( err ) {
            if ( err ) {
                return done( err );
            }
            done( null, token );
        } );
    } );
};

// SRP would be nice... but requires multiple steps,
// probably just stick with sending passwords over the line.
// We'll be using SSL/TLS anyway.
//
// Here's an example that's not far from what we're doing.
// Except we're not going to bother with the refresh token ( and the refresh
// token example in here is not very secure since it doesn't check the client secret )
// http://rwlive.wordpress.com/2014/06/24/oauth2-resource-owner-password-flow-using-oauth2orize-express-4-and-mongojs/
Auth.prototype.exchangePassword = function exchangePassword( client, username, password, scope, done ) {
    var AccessToken;

    if ( !this._options.accessTokenModel ) {
{'fraction_non_alphanumeric': 0.10343048749032757, 'fraction_numerical': 0.00980139282950735, 'mean_word_length': 2.4635998213488164, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6224110', 'n_tokens_mistral': 2207, 'n_tokens_neox': 2117, 'n_words': 737}