Example #1
0
            //Set user's id on guild ad
            userService.updateGuildsId(user.id);

            //Set user's id on characters ad
            userService.updateCharactersId(user.id);
            done(null, user);
        });
    }
));

// In order to support login sessions, Passport serialize and
// deserialize user instances to and from the session.
// Only the user ID is serialized to the session.
// noinspection JSUnresolvedFunction
passport.serializeUser(function (user, done) {
    logger.silly("serializeUser id:%s battleTag:%s accessToken:%s", user.id, user.battleTag, user.accessToken);
    done(null, user.id);
});

// When subsequent requests are received, the ID is used to find
// the user, which will be restored to req.user.
// noinspection JSUnresolvedFunction
passport.deserializeUser(function (id, done) {
    logger.silly("deserializeUser for id:%s", id);
    userModel.findById(id, function (error, user) {
        if (user) {
            done(null, {id: user.id, battleTag: user.battleTag});
        } else {
            done(null, false);
        }
    });
});
Example #2
0
'use strict';

const passport = require('passport'),
	YoutubeStrategy = require('passport-youtube-v3').Strategy,
	refresh = require('passport-oauth2-refresh'),
	UserControl = require('libs/user'),
	User = require('models/user');
	
const adminUsers = ['UCugDN9_9V-RKDB_ilYYE4RA'];
	
passport.serializeUser((user, done) => done(null, user));

passport.deserializeUser((user, done) => done(null, user));

/*YoutubeStrategy.prototype.authorizationParams = function(options) {
	return {
		access_type : 'offline'
		//approval_prompt: 'force'
	};
};*/

const youtube = new YoutubeStrategy({
	clientID: process.env.YOUTUBE_CLIENT_ID,
	clientSecret: process.env.YOUTUBE_CLIENT_SECRET,
	callbackURL: '/auth/youtube/callback',
	scope: [
		'https://www.googleapis.com/auth/youtube.readonly',
		'email'
		//'https://www.googleapis.com/auth/userinfo.email',
	]
}, (accessToken, refreshToken, profile, done) => {
Example #3
0
	, http = require('http')
	, path = require('path')
	, cookie = require('express/node_modules/cookie')
	, connect = require('connect')
	, sessions = require('./lib/sessions')
	, User = require('./lib/user')()
	, passport = require('passport')
  	, GoogleStrategy = require('passport-google').Strategy
  	, io = require('socket.io')
	, ioManager = require('./lib/io-manager.js')
	, config = require('./config')
;

// passeport
passport.serializeUser(function(user, done) {
	console.log(user);
	done(null, user.openId);
});

passport.deserializeUser(function(id, done) {
	done(null, id);
});

passport.use(new GoogleStrategy({
    returnURL: 'http://localhost:3000/login/return',
    realm: 'http://localhost:3000'
  },
  function(identifier, profile, done) {
    User.findOrCreate(identifier, profile, function(err, user) {
      done(err, user);
    });
  }
Example #4
0
function StandAloneServer(gmeConfig) {
    var self = this,
        clientConfig = getClientConfig(gmeConfig),

        sockets = [];

    self.id = Math.random().toString(36).slice(2, 11);

    if (mainLogger) {

    } else {
        mainLogger = Logger.createWithGmeConfig('gme', gmeConfig, true);
    }

    this.serverUrl = '';
    this.isRunning = false;

    servers.push(this);

    /**
     * Gets the server's url based on the gmeConfig that was given to the constructor.
     * @returns {string}
     */
    function getUrl() {
        var url = '';

        // use the cached version if we already built the string
        if (self.serverUrl) {
            return self.serverUrl;
        }

        if (gmeConfig.server.https.enable) {
            url += 'https://';
        } else {
            url += 'http://';
        }

        url += '127.0.0.1';
        url += ':';
        url += gmeConfig.server.port;

        // cache it
        self.serverUrl = url;
        return self.serverUrl;
    }

    //public functions
    function start(callback) {
        var serverDeferred = Q.defer(),
            storageDeferred = Q.defer(),
            gmeAuthDeferred = Q.defer();

        if (typeof callback !== 'function') {
            callback = function () {
            };
        }

        if (self.isRunning) {
            // FIXME: should this be an error?
            callback();
            return;
        }

        sockets = {};


        if (gmeConfig.server.https.enable) {
            __httpServer = Https.createServer({
                key: __secureSiteInfo.key,
                cert: __secureSiteInfo.certificate
            }, __app).listen(gmeConfig.server.port, function () {
                // Note: the listening function does not return with an error, errors are handled by the error event
                logger.debug('Https server is listening on ', {metadata: {port: gmeConfig.server.port}});
                serverDeferred.resolve();
            });
        } else {
            __httpServer = Http.createServer(__app).listen(gmeConfig.server.port, function () {
                // Note: the listening function does not return with an error, errors are handled by the error event
                logger.debug('Http server is listening on ', {metadata: {port: gmeConfig.server.port}});
                serverDeferred.resolve();
            });
        }
        __httpServer.on('connection', function (socket) {
            var socketId = socket.remoteAddress + ':' + socket.remotePort;

            sockets[socketId] = socket;
            logger.debug('socket connected (added to list) ' + socketId);

            socket.on('close', function () {
                if (sockets.hasOwnProperty(socketId)) {
                    logger.debug('socket closed (removed from list) ' + socketId);
                    delete sockets[socketId];
                }
            });
        });

        __httpServer.on('error', function (err) {
            if (err.code === 'EADDRINUSE') {
                logger.error('Failed to start server', {metadata: {port: gmeConfig.server.port, error: err}});
                serverDeferred.reject(err);
            } else {
                logger.error('Server raised an error', {metadata: {port: gmeConfig.server.port, error: err}});
            }
        });

        __storage.openDatabase(function (err) {
            if (err) {
                storageDeferred.reject(err);
            } else {
                __webSocket.start(__httpServer);
                storageDeferred.resolve();
            }
        });

        __gmeAuth.connect(function (err) {
            if (err) {
                logger.error(err);
                gmeAuthDeferred.reject(err);
            } else {
                logger.debug('gmeAuth is ready');
                gmeAuthDeferred.resolve();
            }
        });

        __workerManager.start();

        Q.all([serverDeferred.promise, storageDeferred.promise, gmeAuthDeferred.promise, apiReady])
            .nodeify(function (err) {
                self.isRunning = true;
                callback(err);
            });
    }

    function stop(callback) {
        var key;

        if (self.isRunning === false) {
            // FIXME: should this be an error?
            callback();
            return;
        }

        self.isRunning = false;

        try {
            // FIXME: is this call synchronous?
            __webSocket.stop();
            //kill all remaining workers
            __workerManager.stop(function (err) {
                var numDestroyedSockets = 0;

                // close storage
                __storage.closeDatabase(function (err1) {
                    __gmeAuth.unload(function (err2) {
                        logger.debug('gmeAuth unloaded');
                        // request server close - do not accept any new connections.
                        // first we have to request the close then we can destroy the sockets.
                        __httpServer.close(function (err3) {
                            logger.info('http server closed');
                            logger.debug('http server closed');
                            callback(err || err1 || err2 || err3 || null);
                        });

                        // destroy all open sockets i.e. keep-alive and socket-io connections, etc.
                        for (key in sockets) {
                            if (sockets.hasOwnProperty(key)) {
                                sockets[key].destroy();
                                delete sockets[key];
                                logger.debug('destroyed open socket ' + key);
                                numDestroyedSockets += 1;
                            }
                        }

                        logger.debug('destroyed # of sockets: ' + numDestroyedSockets);
                    });
                });
            });
        } catch (e) {
            //ignore errors
            callback(e);
        }
    }

    this.start = start;
    this.stop = stop;


    //internal functions
    function getRedirectUrlParameter(req) {
        //return '?redirect=' + URL.addSpecialChars(req.url);
        return '?redirect=' + encodeURIComponent(req.originalUrl);
    }

    function redirectUrl(req, res) {
        if (req.query.redirect) {
            //res.redirect(URL.removeSpecialChars(req.query.redirect));
            res.redirect(decodeURIComponent(req.query.redirect));
        } else {
            res.redirect('/');
        }
    }


    // TODO: add this back, when google authentication works again
    //function checkGoogleAuthentication(req, res, next) {
    //    if (__googleAuthenticationSet === true) {
    //        return next();
    //    } else {
    //        var protocolPrefix = gmeConfig.server.https.enable === true ? 'https://' : 'http://';
    //        Passport.use(new PassGoogle.Strategy({
    //                returnURL: protocolPrefix + req.headers.host + '/login/google/return',
    //                realm: protocolPrefix + req.headers.host
    //            },
    //            function (identifier, profile, done) {
    //                return done(null, {id: profile.emails[0].value});
    //            }
    //        ));
    //        __googleAuthenticationSet = true;
    //        return next();
    //    }
    //}

    function ensureAuthenticated(req, res, next) {
        var authorization = req.get('Authorization'),
            username,
            password,
            split;

        if (authorization && authorization.indexOf('Basic ') === 0) {
            logger.debug('Basic authentication request');
            // FIXME: ':' should not be in username nor in password
            split = new Buffer(authorization.substr('Basic '.length), 'base64').toString('utf8').split(':');
            username = split[0];
            password = split[1];
            if (username && password) {
                // no empty username no empty password
                __gmeAuth.authenticateUserById(username, password, 'gme', '/', req, res, next);
                return;
            } else {
                res.status(401);
                return next(new Error('Basic authentication failed'));
            }
        }

        if (true === gmeConfig.authentication.enable) {
            if (req.isAuthenticated() || (req.session && true === req.session.authenticated)) {
                return next();
            } else {
                //client oriented new session
                if (req.headers.webgmeclientsession) {
                    // FIXME: used by blob/plugin/executor ???
                    __sessionStore.get(req.headers.webgmeclientsession, function (err, clientSession) {
                        if (!err) {
                            if (clientSession.authenticated) {
                                req.session.authenticated = true;
                                req.session.udmId = clientSession.udmId;
                                res.cookie('webgme', req.session.udmId);
                                return next();
                            } else {
                                res.sendStatus(401); //TODO find proper error code
                            }
                        } else {
                            res.sendStatus(401); //TODO find proper error code
                        }
                    });
                } else if (gmeConfig.authentication.allowGuests) {
                    req.session.authenticated = true;
                    req.session.udmId = gmeConfig.authentication.guestAccount;
                    res.cookie('webgme', req.session.udmId);
                    return next();
                } else if (res.getHeader('X-WebGME-Media-Type')) {
                    // do not redirect with direct api access
                    res.status(401);
                    return next(new Error());
                } else {
                    res.redirect('/login' + getRedirectUrlParameter(req));
                }

            }
        } else {
            // if authentication is turned off we treat everybody as a guest user
            req.session.authenticated = true;
            req.session.udmId = gmeConfig.authentication.guestAccount;
            res.cookie('webgme', req.session.udmId);
            return next();
        }
    }

    function isGoodExtraAsset(name, path) {
        try {
            var file = FS.readFileSync(path + '/' + name + '.js', 'utf-8');
            if (file === undefined || file === null) {
                return false;
            } else {
                return true;
            }
        } catch (e) {
            return false;
        }
    }

    function getPluginBasePathByName(pluginName) {
        for (var i = 0; i < gmeConfig.plugin.basePaths.length; i++) {
            var additional = FS.readdirSync(gmeConfig.plugin.basePaths[i]);
            for (var j = 0; j < additional.length; j++) {
                if (additional[j] === pluginName) {
                    if (isGoodExtraAsset(additional[j], Path.join(gmeConfig.plugin.basePaths[i], additional[j]))) {
                        return gmeConfig.plugin.basePaths[i];
                    }
                }
            }
        }
    }

    function getVisualizersDescriptor() {
        //we merge the contents of the CONFIG.visualizerDescriptors by id
        var indexById = function (objectArray, id) {
                var i,
                    index = -1;
                for (i = 0; i < objectArray.length; i++) {
                    if (objectArray[i].id === id) {
                        index = i;
                        break;
                    }
                }

                return index;
            },
            getVisualizerDescriptor = function (path) {
                try {
                    var descriptor = FS.readFileSync(path, 'utf-8');
                    descriptor = JSON.parse(descriptor);
                    return descriptor;
                } catch (e) {
                    //we do not care much of the error just give back an empty array
                    return [];
                }
            },
            allVisualizersDescriptor = [],
            i, j;

        for (i = 0; i < gmeConfig.visualization.visualizerDescriptors.length; i++) {
            var descriptor = getVisualizerDescriptor(gmeConfig.visualization.visualizerDescriptors[i]);
            if (descriptor.length) {
                for (j = 0; j < descriptor.length; j++) {
                    var index = indexById(allVisualizersDescriptor, descriptor[j].id);
                    if (index !== -1) {
                        allVisualizersDescriptor[index] = descriptor[j];
                    } else {
                        allVisualizersDescriptor.push(descriptor[j]);
                    }
                }
            }
        }
        return allVisualizersDescriptor;
    }

    function setupExternalRestModules() {
        var restComponent,
            keys = Object.keys(gmeConfig.rest.components),
            i;
        logger.debug('initializing external REST modules');
        for (i = 0; i < keys.length; i++) {
            restComponent = require(gmeConfig.rest.components[keys[i]]);
            if (restComponent) {
                logger.debug('adding rest component [' + gmeConfig.rest.components[keys[i]] + '] to' +
                    ' - /rest/external/' + keys[i]);
                if (restComponent.hasOwnProperty('initialize') && restComponent.hasOwnProperty('router')) {
                    // FIXME: initialize may return with a promise
                    restComponent.initialize(middlewareOpts);
                    __app.use('/rest/external/' + keys[i], restComponent.router);
                } else {
                    __app.use('/rest/external/' + keys[i], restComponent(gmeConfig, ensureAuthenticated, logger));
                }
            } else {
                throw new Error('Loading rest component ' + gmeConfig.rest.components[keys[i]] + ' failed.');
            }
        }
    }

    function expressFileSending(httpResult, path) {
        httpResult.sendFile(path, function (err) {
            //TODO we should check for all kind of error that should be handled differently
            if (err) {
                if (err.code === 'EISDIR') {
                    // NOTE: on Linux status is 404 on Windows status is not set
                    err.status = err.status || 404;
                }
                logger.warn('expressFileSending failed for: ' + path + ': ' + (err.stack ? err.stack : err));
                if (httpResult.headersSent === false) {
                    httpResult.sendStatus(err.status || 500);
                }
            }
        });
    }

    //here starts the main part
    //variables
    var logger = null,
        __storage = null,
        __database = null,
        __webSocket = null,
        __gmeAuth = null,
        apiReady,
        __secureSiteInfo = {},
        __app = null,
        __sessionStore,
        __workerManager,
        __users = {},
        //__googleAuthenticationSet = false,
        //__canCheckToken = true,
        __httpServer = null,
        __logoutUrl = gmeConfig.authentication.logOutUrl || '/',
        __baseDir = requireJS.s.contexts._.config.baseUrl,// TODO: this is ugly
        __clientBaseDir = Path.resolve(gmeConfig.client.appDir),
        __requestCounter = 0,
        __reportedRequestCounter = 0,
        __requestCheckInterval = 2500,
        middlewareOpts;

    //creating the logger
    logger = mainLogger.fork('server:standalone');
    self.logger = logger;

    logger.debug('starting standalone server initialization');
    //initializing https extra infos
    if (gmeConfig.server.https.enable === true) { //TODO move this from here
        __secureSiteInfo.key = FS.readFileSync(gmeConfig.server.https.keyFile);
        __secureSiteInfo.certificate = FS.readFileSync(gmeConfig.server.https.certificateFile);
    }

    logger.debug('initializing session storage');
    __sessionStore = new SSTORE(logger, gmeConfig);

    logger.debug('initializing server worker manager');
    __workerManager = new ServerWorkerManager({
        sessionToUser: __sessionStore.getSessionUser,
        globConf: gmeConfig,
        logger: logger
    });

    logger.debug('initializing authentication modules');
    //TODO: do we need to create this even though authentication is disabled?
    // FIXME: we need to connect with gmeAUTH again! start/stop/start/stop
    __gmeAuth = new GMEAUTH(__sessionStore, gmeConfig);

    logger.debug('initializing passport module for user management');
    //TODO in the long run this also should move to some database
    Passport.serializeUser(
        function (user, done) {
            __users[user.id] = user;
            done(null, user.id);
        });
    Passport.deserializeUser(
        function (id, done) {
            done(null, __users[id]);
        });

    logger.debug('initializing static server');
    __app = new Express();

    __database = new Mongo(logger, gmeConfig);
    __storage = new Storage(__database, logger, gmeConfig, __gmeAuth);
    __webSocket = new WebSocket(__storage, logger, gmeConfig, __gmeAuth, __workerManager);

    middlewareOpts = {  //TODO: Pass this to every middleware They must not modify the options!
        gmeConfig: gmeConfig,
        logger: logger,
        ensureAuthenticated: ensureAuthenticated,
        gmeAuth: __gmeAuth,
        safeStorage: __storage,
        workerManager: __workerManager
    };

    //__app.configure(function () {
    //counting of requests works only in debug mode
    if (gmeConfig.debug === true) {
        setInterval(function () {
            if (__reportedRequestCounter !== __requestCounter) {
                __reportedRequestCounter = __requestCounter;
                logger.debug('...handled ' + __reportedRequestCounter + ' requests so far...');
            }
        }, __requestCheckInterval);
        __app.use(function (req, res, next) {
            __requestCounter++;
            next();
        });
    }

    __app.use(compression());
    __app.use(cookieParser());
    __app.use(bodyParser.json());
    __app.use(bodyParser.urlencoded({
        extended: true
    }));
    __app.use(methodOverride());
    __app.use(multipart({defer: true})); // required to upload files. (body parser should not be used!)
    __app.use(session({
        store: __sessionStore,
        secret: gmeConfig.server.sessionCookieSecret,
        key: gmeConfig.server.sessionCookieId,
        saveUninitialized: true,
        resave: true
    }));
    __app.use(Passport.initialize());
    __app.use(Passport.session());

    // FIXME: do we need this code to make sure that we serve requests only if the session is available?
    // Examples: can we lose the connection to mongo or redis, if they are used for storing the sessions?
    //__app.use(function (req, res, next) {
    //    var tries = 3;
    //
    //    if (req.session !== undefined) {
    //        return next();
    //    }
    //
    //    function lookupSession(error) {
    //        if (error) {
    //            return next(error);
    //        }
    //
    //        tries -= 1;
    //
    //        if (req.session !== undefined) {
    //            return next();
    //        }
    //
    //        if (tries < 0) {
    //            return next(new Error('oh no session is not available'));
    //        }
    //
    //        __sessionStore(req, res, lookupSession);
    //    }
    //
    //    lookupSession();
    //});

    if (gmeConfig.executor.enable) {
        ExecutorServer.createExpressExecutor(__app, '/rest/executor', middlewareOpts);
    } else {
        logger.debug('Executor not enabled. Add \'executor.enable: true\' to configuration to activate.');
    }

    setupExternalRestModules();

    // Basic authentication

    logger.debug('creating login routing rules for the static server');
    __app.get('/', ensureAuthenticated, function (req, res) {
        expressFileSending(res, __clientBaseDir + '/index.html');
    });
    __app.get('/logout', function (req, res) {
        res.clearCookie('webgme');
        res.clearCookie('isisforge'); // TODO is this really needed
        req.logout();
        req.session.authenticated = false;
        delete req.session.udmId;
        res.redirect(__logoutUrl);
    });
    __app.get('/login', function (req, res) {
        res.location('/login');
        expressFileSending(res, __clientBaseDir + '/login.html');
    });
    __app.post('/login', function (req, res, next) {
        var queryParams = [],
            url = URL.parse(req.url, true);
        if (req.body && req.body.username) {
            queryParams.push('username=' + encodeURIComponent(req.body.username));
        }
        if (url && url.query && url.query.redirect) {
            queryParams.push('redirect=' + encodeURIComponent(req.query.redirect));
        }
        req.__gmeAuthFailUrl__ = '/login';
        if (queryParams.length) {
            req.__gmeAuthFailUrl__ += '?' + queryParams.join('&');
        }
        req.__gmeAuthFailUrl__ += '#failed';
        next();
    }, __gmeAuth.authenticate, function (req, res) {
        res.cookie('webgme', req.session.udmId);
        redirectUrl(req, res);
    });

    // TODO: review/revisit this part when google authentication is used.
    //__app.get('/login/google', checkGoogleAuthentication, Passport.authenticate('google'));
    //__app.get('/login/google/return', __gmeAuth.authenticate, function (req, res) {
    //    res.cookie('webgme', req.session.udmId);
    //    redirectUrl(req, res);
    //});

    //TODO: only node_worker/index.html and common/util/common are using this
    //logger.debug('creating decorator specific routing rules');
    __app.get('/bin/getconfig.js', ensureAuthenticated, function (req, res) {
        res.status(200);
        res.setHeader('Content-type', 'application/javascript');
        res.end('define([],function(){ return ' + JSON.stringify(clientConfig) + ';});');
    });

    logger.debug('creating gmeConfig.json specific routing rules');
    __app.get('/gmeConfig.json', ensureAuthenticated, function (req, res) {
        res.status(200);
        res.setHeader('Content-type', 'application/json');
        res.end(JSON.stringify(clientConfig));
    });

    logger.debug('creating decorator specific routing rules');
    __app.get(/^\/decorators\/.*/, ensureAuthenticated, function (req, res) {
        var tryNext = function (index) {
            var resolvedPath;
            if (index < gmeConfig.visualization.decoratorPaths.length) {
                resolvedPath = Path.resolve(gmeConfig.visualization.decoratorPaths[index]);
                resolvedPath = Path.join(resolvedPath, req.url.substring('/decorators/'.length));
                res.sendFile(resolvedPath, function (err) {
                    logger.debug('sending decorator', resolvedPath);
                    if (err && err.code !== 'ECONNRESET') {
                        tryNext(index + 1);
                    }
                });
            } else {
                res.sendStatus(404);
            }
        };

        if (gmeConfig.visualization.decoratorPaths && gmeConfig.visualization.decoratorPaths.length) {
            tryNext(0);
        } else {
            res.sendStatus(404);
        }
    });

    logger.debug('creating plug-in specific routing rules');
    __app.get(/^\/plugin\/.*/, function (req, res) {
        //first we try to give back the common plugin/modules
        res.sendFile(Path.join(__baseDir, req.path), function (err) {
            if (err && err.code !== 'ECONNRESET') {
                //this means that it is probably plugin/pluginName or plugin/pluginName/relativePath format
                // so we try to look for those in our config
                //first we check if we have the plugin registered in our config
                var urlArray = req.url.split('/'),
                    pluginName = urlArray[2] || null,
                    basePath = getPluginBasePathByName(pluginName),
                    relPath = '';
                urlArray.shift();
                urlArray.shift();
                urlArray.shift();
                relPath = urlArray.join('/');
                if (relPath.indexOf('.js') === -1) {
                    relPath += '.js';
                }

                if (typeof basePath === 'string' && typeof relPath === 'string') {
                    expressFileSending(res, Path.resolve(Path.join(basePath, relPath)));
                } else {
                    res.sendStatus(404);
                }
            }
        });
    });

    logger.debug('creating external library specific routing rules');
    __app.get(/^\/extlib\/.*/, ensureAuthenticated, function (req, res) {
        //first we try to give back the common extlib/modules

        var urlArray = req.path.split('/');
        urlArray[1] = '.';
        urlArray.shift();

        var relPath = urlArray.join('/');
        var absPath = Path.resolve(Path.join(process.cwd(), relPath));
        // must pass the full path
        if (relPath.lastIndexOf('/') === relPath.length - 1) {
            // if URL ends with /, append / to support sending index.html
            absPath = absPath + '/';
        }

        expressFileSending(res, absPath);
    });

    logger.debug('creating basic static content related routing rules');
    //static contents
    //javascripts - core and transportation related files //TODO: remove config, middleware and bin
    __app.get(/^\/(common|config|bin|middleware)\/.*\.js$/, function (req, res) {
        expressFileSending(res, Path.join(__baseDir, req.path));
    });

    //TODO remove this part as this is only temporary!!!
    __app.get('/docs/*', function (req, res) {
        expressFileSending(res, Path.join(__baseDir, '..', req.path));
    });


    __app.use('/rest/blob', BlobServer.createExpressBlob(middlewareOpts));

    //client contents - js/html/css
    //stuff that considered not protected
    __app.get(/^\/.*\.(css|ico|ttf|woff|js|cur)$/, function (req, res) {
        expressFileSending(res, Path.join(__clientBaseDir, req.path));
    });


    __app.get(/^\/.*\.(_js|html|gif|png|bmp|svg|json|map)$/, ensureAuthenticated, function (req, res) {
        //package.json
        if (req.path === '/package.json') {
            expressFileSending(res, Path.join(__baseDir, '..', req.path));
        } else {
            expressFileSending(res, Path.join(__clientBaseDir, req.path));
        }
    });

    //logger.debug('creating token related routing rules');
    //__app.get('/gettoken', ensureAuthenticated, function (req, res) {
    //    if (gmeConfig.rest.secure) {
    //        __gmeAuth.getToken(req.session.id, function (err, token) {
    //            if (err) {
    //                res.send(err);
    //            } else {
    //                res.send(token);
    //            }
    //        });
    //    } else {
    //        res.sendStatus(410); //special error for the interpreters to know there is no need for token
    //    }
    //});
    //__app.get('/checktoken/:token', function (req, res) {
    //    if (gmeConfig.authentication.enable === true) {
    //        if (__canCheckToken === true) {
    //            setTimeout(function () {
    //                __canCheckToken = true;
    //            }, 10000);
    //            __canCheckToken = false;
    //            __gmeAuth.checkToken(req.params.token, function (isValid) {
    //                if (isValid === true) {
    //                    res.sendStatus(200);
    //                } else {
    //                    res.sendStatus(403);
    //                }
    //            });
    //        } else {
    //            res.sendStatus(403);
    //        }
    //    } else {
    //        res.sendStatus(410); //special error for the interpreters to know there is no need for token
    //    }
    //});

    logger.debug('creating API related routing rules');

    apiReady = api.createAPI(__app, '/api', middlewareOpts);


    logger.debug('creating server-worker related routing rules');

    function sendSimpleResult(res, resultId, filename) {
        logger.debug('worker/simpleResult requested, urlArray', {metadata: {id: resultId, filename: filename}});

        __workerManager.result(resultId, function (err, result) {
            if (err) {
                logger.error('worker/simpleResult err', err);
                res.sendStatus(500);
            } else {
                res.header('Content-Disposition', 'attachment;filename=\'' + filename + '\'');
                res.json(result);
            }
        });
    }

    __app.get('/worker/simpleResult/:resultId', function (req, res) {
        var filename = 'simpleResult-' + req.params.resultId + '.json';
        sendSimpleResult(res, req.params.resultId, filename);
    });

    // FIXME: filename should be in query string
    __app.get('/worker/simpleResult/:resultId/:filename', function (req, res) {
        var filename = req.params.filename;
        if (filename.indexOf('.json') === -1) {
            filename += '.json';
        }
        sendSimpleResult(res, req.params.resultId, filename);
    });


    logger.debug('creating list asset rules');
    __app.get('/listAllDecorators', ensureAuthenticated, function (req, res) {
        var names = []; //TODO we add everything in the directories!!!
        for (var i = 0; i < gmeConfig.visualization.decoratorPaths.length; i++) {
            var additional = FS.readdirSync(gmeConfig.visualization.decoratorPaths[i]);
            for (var j = 0; j < additional.length; j++) {
                if (names.indexOf(additional[j]) === -1) {
                    if (isGoodExtraAsset(additional[j],
                            Path.join(gmeConfig.visualization.decoratorPaths[i],
                                additional[j]))) {
                        names.push(additional[j]);
                    }
                }
            }
        }
        res.status(200);
        res.setHeader('Content-type', 'application/json');
        res.end(JSON.stringify({allDecorators: names}));
    });

    __app.get('/listAllPlugins', ensureAuthenticated, function (req, res) {
        var names = []; //we add only the '*.js' files from the directories
        for (var i = 0; i < gmeConfig.plugin.basePaths.length; i++) {
            var additional = FS.readdirSync(gmeConfig.plugin.basePaths[i]);
            for (var j = 0; j < additional.length; j++) {
                if (names.indexOf(additional[j]) === -1) {
                    if (isGoodExtraAsset(additional[j], Path.join(gmeConfig.plugin.basePaths[i], additional[j]))) {
                        names.push(additional[j]);
                    }
                }
            }
        }
        res.status(200);
        res.setHeader('Content-type', 'application/json');
        res.end(JSON.stringify({allPlugins: names}));
    });

    __app.get('/listAllSeeds', ensureAuthenticated, function (req, res) {
        var names = [],
            result = [],
            seedName,
            i,
            j;
        if (gmeConfig.seedProjects.enable === true) {
            for (i = 0; i < gmeConfig.seedProjects.basePaths.length; i++) {
                names = FS.readdirSync(gmeConfig.seedProjects.basePaths[i]);
                for (j = 0; j < names.length; j++) {
                    seedName = Path.basename(names[j], '.json');
                    if (result.indexOf(seedName) === -1) {
                        result.push(seedName);
                    }
                }
            }
        }
        logger.debug('/listAllSeeds', {metadata: result});
        res.status(200);
        res.setHeader('Content-type', 'application/json');
        res.end(JSON.stringify({allSeeds: result.sort()}));
    });

    __app.get('/listAllVisualizerDescriptors', ensureAuthenticated, function (req, res) {
        var allVisualizerDescriptors = getVisualizersDescriptor();
        res.status(200);
        res.setHeader('Content-type', 'application/javascript');
        res.end('define([],function(){ return ' + JSON.stringify(allVisualizerDescriptors) + ';});');
    });


    // catches all next(new Error()) from previous rules, you can set res.status() before you call next(new Error())
    __app.use(function (err, req, res, next) {
        if (res.statusCode === 200) {
            res.status(err.status || 500);
        }
        res.sendStatus(res.statusCode);
        //res.send(err.stack ? err.stack : err); // FIXME: in dev mode
    });

    // everything else is 404
    logger.debug('creating all other request rule - error 404 -');
    __app.use('*', function (req, res) {
        res.sendStatus(404);
    });


    logger.debug('gmeConfig of webgme server', {metadata: gmeConfig});
    var networkIfs = OS.networkInterfaces(),
        addresses = 'Valid addresses of gme web server: ',
        forEveryNetIf = function (netIf) {
            if (netIf.family === 'IPv4') {
                var address = (gmeConfig.server.https.enable ? 'https' : 'http') + '://' +
                    netIf.address + ':' + gmeConfig.server.port;
                addresses = addresses + '  ' + address;
            }
        };
    for (var dev in networkIfs) {
        networkIfs[dev].forEach(forEveryNetIf);
    }

    logger.info(addresses);

    logger.debug('standalone server initialization completed');

    return {
        getUrl: getUrl,
        start: start,
        stop: stop
    };
}
Example #5
0
'use strict';

var passport = require('passport');
var User = require('../database/models/user');
var LocalStrategy = require('passport-local').Strategy;

passport.serializeUser(function(user, done) {
  done(null, user.get('id'));
});

passport.deserializeUser(function(id, done) {
  User.forge()
  .where({id: id})
  .fetch()
  .then(function(user){
    done(null,user.toJSON());
  });
});

passport.use(new LocalStrategy({
  usernameField: 'email',
  }, function(email, password, done) {
    User.forge()
    .where({email: email})
    .fetch()
    .then(function(user){
      if (!user){
          return done(null, false);
        } else {
          user.verifyPassword(password)
              .then(function(result){
Example #6
0
sequelize.sync().then(() => {
  app.use(session({
    secret: 'alastor je awesome !!!',
    resave: false,
    saveUninitialized: false,
    cookie: { maxAge: 60000 }
  }));

  app.use(bodyParser.json());
  app.use(passport.initialize());
  app.use(passport.session());

  passport.serializeUser((user, done) => done(null, user.id));
  passport.deserializeUser((user, done) => User.findOne({id: user}).then((result) => done(null, result)).catch((err) => done(err)));

  passport.use(new LocalStrategy((username, password, done) => {
    login(username, password).then((response) => done(response.error, response.result, null));
  }));

  app.post('/login/', (req, res, next) => passport.authenticate('local', (dbErr, user) => {
    if (dbErr) {
      res.json({
        result: null,
        error: dbErr,
      });
    } else {
      req.logIn(user, (loginErr) => {
        res.json({
          result: {
            nickname: user.nickname,
            username: user.username
          },
          error: loginErr
        });
      });
    }
  })(req, res, next));

  app.post('/logout/', (req, res) => {
    req.logout();
    res.json({});
  });

  app.post('/register/', (req, res) => {
    const {nickname, username, password} = req.body;
    User.findOne({
      where: {
        username: username
      }
    }).then((data) => {
      if (data) {
        res.json({
          response: 'error',
          msg: 'User already exits'
        });
      } else {
        const user = User.create({
          nickname: nickname,
          username: username,
          password: password,
        });
        user.then((data) => {
          req.logIn(user, (loginErr) => {
          res.json({
            result: {
              nickname: data.nickname,
              username: data.username
            },
            error: loginErr
          });
        });
        })
      }
    });
  });

  app.use((req, res) => {
    const splittedUrlPath = req.url.split('?')[0].split('/').slice(1);

    const {action, params} = mapUrl(actions, splittedUrlPath);

    if (action) {
      action(req, params)
        .then((result) => {
          if (result instanceof Function) {
            result(res);
          } else {
            res.json(result);
          }
        }, (reason) => {
          if (reason && reason.redirect) {
            res.redirect(reason.redirect);
          } else {
            console.error('API ERROR:', pretty.render(reason));
            res.status(reason.status || 500).json(reason);
          }
        });
    } else {
      res.status(404).end('NOT FOUND');
    }
  });

  // GAME GREEDY BOT
  function botPlay(user) {
    rollDices(user, true);
    setTimeout(() => {
      if(canPickSomeDice(user)){
        if(userGame[user].dices.alreadyTakenValues.includes(6) || !userGame[user].dices.values.includes(6)){
          let possibleVal={};
          for(let x=0; x < userGame[user].dices.values.length;x++){
            let val= userGame[user].dices.values[x];
            if(!userGame[user].dices.alreadyTakenValues.includes(val)){
              if(possibleVal[val]){
                possibleVal[val]+=1;
              }
              else {
                possibleVal[val]=1;
              }
            }
          }
          let maxVal=0;
          let maxDice=0;
          Object.keys(possibleVal).forEach(
            (key) => {
              if(+key*possibleVal[key] > maxVal){
                maxVal=+key*possibleVal[key];
                maxDice=+key;
              }
              else if(+key*possibleVal[key] === maxVal){
                if(possibleVal[key] < possibleVal[maxDice]){
                  maxDice=+key;
                }
              }
            }
          );
          pickDice({user: user, value: maxDice}, true);
        }
        else {
          pickDice({user: user, value: 6}, true);
        }
        setTimeout(() => checkStonePick(user), 1000);
      }
      else {
          endTurn(user, true);
      }
    }, 1500);
  }

  function checkStonePick(user) {
    if(pickPlayerStone({user: user, id: userGame[user].playerTurn}, true)){
      isEnd(user);
    }
    else {
      let maxVal = 0;
      for (let x = 21; x < 37; x++) {
        if (isStoneAvailable({user: user, value: x})) {
          maxVal = x;
        }
      }

      if (maxVal !== 0) {
        pickStone({user: user, value: maxVal}, true);
      }
      else {
        botPlay(user);
      }
    }
  }

  function canPickSomeDice(user) {
    let result = false;
    const values = userGame[user].dices.values;
    for(let x=0;x < values.length;x++){
      if(!userGame[user].dices.alreadyTakenValues.includes(values[x])){
        result=true;
      }
    }

    return result;
  }

  // END GAME GREEDY BOT

  // GAME FUNCTIONS
  const userSocket = {};
  const userGame = {};


  function endTurn(user, isBot = false){
    const game = userGame[user];
    if((game.playerList[game.playerTurn].name === user || isBot) && !game.endGame) {
      if (game.playerList[game.playerTurn].stones.length) {
        let stone = game.playerList[game.playerTurn].stones.pop();
        game.grill[stone].taken = false;
        const maxOnGrill = findMaxOnGrill(user);
        if (+stone !== maxOnGrill) {
          for (let index = 36; index >= 21; index--) {
            if (!game.grill[index].taken && game.grill[index].active) {
              game.grill[index].active = false;
              break;
            }
          }
        }

        let score = 0;
        if (stone <= 24)
          score = 1;
        else if (stone <= 28)
          score = 2;
        else if (stone <= 32)
          score = 3;
        else
          score = 4;

        game.playerList[game.playerTurn].score -= score;
      }

      game.dices = {
          remaining: 8,
          rolled: false,
          score: 0,
          alreadyTakenValues: [],
          values: [0, 0, 0, 0, 0, 0, 0, 0]
        };
      game.playerTurn= (game.playerTurn+1) % game.numberOfPlayers;
      userGame[user] = game;
      isEnd(user);
    }
  }

  function isEnd(user) {
    let end = true;
    const game = userGame[user];
    Object.keys(game.grill).forEach((key) =>
      { end= end && (!game.grill[key].active || game.grill[key].taken); }
    );
    userGame[user].endGame= end;
    if(end){
      game.playerList.map((player) => {
        if(!player.isBot){
          createScore({user: player.name, score: player.score, status: "win"});
        }
      });
    }

    game.playerList.map((player) => {
      if(!player.isBot){
        userGame[player.name]=userGame[user];
        userSocket[player.name].emit('update state', userGame[user]);
      }
    });
    if(userGame[user].playerList[userGame[user].playerTurn].isBot){
      botPlay(user, userGame[user].playerTurn);
    }
  }

  function rollDices(user, isBot = false){
    const game = userGame[user];
    if((game.playerList[game.playerTurn].name === user || isBot) && !game.dices.rolled){
      let values=[];
      for(let i=0;i<game.dices.remaining;i++){
        values.push(Math.floor(Math.random() * 6) + 1);
      }
      userGame[user].dices.values=values;
      userGame[user].dices.rolled=true;
      game.playerList.map((player) => {
        if(!player.isBot){
          userGame[player.name]=userGame[user];
          userSocket[player.name].emit('update state', userGame[user]);
        }
      });
    }
  }

  function pickDice(data, isBot = false) {
    const {user, value} = data;
    const game = userGame[user];
    if((game.playerList[game.playerTurn].name === user || isBot) && game.dices.rolled && !game.dices.alreadyTakenValues.includes(value)){
      let numberOfDices=0;
      for(let x=0;x < game.dices.values.length;x++) {
        if(game.dices.values[x] === value){
          numberOfDices+=1;
        }
      }
      const remaining = game.dices.remaining - numberOfDices;
      let sum;
      if(value === 6 )
        sum = numberOfDices*5;
      else
        sum = numberOfDices*value;

      let newScore = game.dices.score;
      newScore += sum;

      let newDices =[];
      for(let i=0;i<remaining;i++){
        newDices.push(0);
      }

      userGame[user].dices.alreadyTakenValues.push(value);
      userGame[user].dices.values = newDices;
      userGame[user].dices.remaining = remaining;
      userGame[user].dices.rolled = false;
      userGame[user].dices.score = newScore;
      game.playerList.map((player) => {
        if(!player.isBot){
          userGame[player.name]=userGame[user];
          userSocket[player.name].emit('update state', userGame[user]);
        }
      });
    }
  }



  function findMaxOnGrill(user){
    const game = userGame[user];
    let maxVal = 0;
    for (let x = 21; x < 37; x++) {
      if (game.grill[x].active && !game.grill[x].taken) {
        maxVal = x;
      }
    }
    return maxVal;
  }

  function isStoneAvailable(data) {
    const {user, value} = data;
    const game = userGame[user];
    return (value <= game.dices.score) &&
            game.grill[value].active &&
            !game.grill[value].taken &&
            !game.dices.rolled &&
            game.dices.alreadyTakenValues.includes(6)
  }

  function pickStone(data, isBot = false) {
    const {user, value} = data;
    const game = userGame[user];
    if((game.playerList[game.playerTurn].name === user || isBot) && isStoneAvailable(data)){
      game.grill[value].taken =true;
      game.playerList[game.playerTurn].stones.push(value);
      let cerv=0;
      if(value <=24)
        cerv=1;
      else if(value <=28)
        cerv=2;
      else if(value <=32)
        cerv=3;
      else
        cerv=4;
      game.playerList[game.playerTurn].score += cerv;
      game.dices = {
          remaining: 8,
          rolled: false,
          score: 0,
          alreadyTakenValues: [],
          values: [0,0,0,0,0,0,0,0]
        };
      game.playerTurn= (game.playerTurn+1) % game.numberOfPlayers;
      isEnd(user);
    }
  }

  function isAvailablePlayerStone(data) {
    const {user, id}= data;
    const player = userGame[user].playerList[id];
    return  player.stones.length !==0 &&
            (+player.stones[player.stones.length-1] === userGame[user].dices.score) &&
            !userGame[user].dices.rolled &&
            userGame[user].dices.alreadyTakenValues.includes(6) &&
            userGame[user].playerTurn !== id
  }

  function pickPlayerStone(data, isBot = false) {
    const {user, id} = data;
    const game = userGame[user];
    let pickPlayerStoneId=-1;

    if(isBot) {
      for(let i=0;i<game.playerList.length;i++) {
        if (isAvailablePlayerStone({user: user, id: i})) {
          pickPlayerStoneId = i;
        }
      }
    }
    else if(isAvailablePlayerStone({user: user, id: id})){
      pickPlayerStoneId=id;
    }

    if (pickPlayerStoneId !== -1) {
      const stone = game.playerList[pickPlayerStoneId].stones.pop();
      game.playerList[game.playerTurn].stones.push(stone);
      let cerv=0;
      if(stone <=24)
        cerv=1;
      else if(stone <=28)
        cerv=2;
      else if(stone <=32)
        cerv=3;
      else
        cerv=4;
      game.playerList[game.playerTurn].score += cerv;
      game.playerList[pickPlayerStoneId].score -= cerv;
      game.dices = {
          remaining: 8,
          rolled: false,
          score: 0,
          alreadyTakenValues: [],
          values: [0,0,0,0,0,0,0,0]
        };
      game.playerTurn= (game.playerTurn+1) % game.numberOfPlayers;
      if(isBot){
        return true;
      }
      else {
        isEnd(user);
      }
    }
    if(isBot)
      return false;
  }

  // END GAME FUNCTIONS

  function createScore(data) {
    const {user, score, status} = data;
    User.findOne({
      where: {
        username: user
      }
    }).then((user) => {
      if(user){
        Score.create({
          UserId: user.dataValues.id,
          date: Date.now(),
          value: score,
          status: status
        }).then((newScore) => {
          if(newScore){
            console.log("Vytvoril som nove score ", newScore);
          }
        })
      }
    });
  }


  const bufferSize = 100;
  const messageBuffer = new Array(bufferSize);
  let messageIndex = 0;

  if (config.apiPort) {
    const runnable = app.listen(config.apiPort, (err) => {
      if (err) {
        console.error(err);
      }
      console.info('----\n==> 🌎  API is running on port %s', config.apiPort);
      console.info('==> 💻  Send requests to http://%s:%s', config.apiHost, config.apiPort);
    });



    io.on('connection', (socket) => {

      socket.on('game started',(username) => {
        userSocket[username]= socket;
        userGame[username]=JSON.parse(JSON.stringify(defaultState));
        userGame[username].playerList[0].name=username;
        socket.emit('update state', userGame[username]);
      });

      socket.on('restart game', (username) => {
        userGame[username]=JSON.parse(JSON.stringify(defaultState));
        userGame[username].playerList[0].name=username;
        userGame[username].playerList.map((player) => {
          if(!player.isBot){
            userGame[player.name]=userGame[username];
            userSocket[player.name].emit('update state', userGame[username]);
          }
        });
      });

      socket.on('end turn', (username) => {
        endTurn(username);
      });


      socket.on('roll dice', (username) => {
        rollDices(username);
      });

      socket.on('pick dice', (data) => {
        pickDice(data);
      });

      socket.on('pick stone', (data) => {
        pickStone(data);
      });

      socket.on('pick player stone', (data) => {
        pickPlayerStone(data);
      });

      socket.on('get lobbies', (user) => {
        Lobby.findAll().then((data) => {
          if(data){
            userSocket[user]= socket;
            userSocket[user].emit('update lobbies', data);
          }
        })
      });

      socket.on('create lobby', (data) => {
        const {user, name} = data;
        const lobby = Lobby.create({
          limit: 4,
          username: user,
          name: name,
          players: {
            playerList: [user]
          }
        });
        lobby.then((newlobby) => {
          if(newlobby){
            Lobby.findOne({
              where: {
                id: newlobby.dataValues.id
              }
            }).then((dbNewLobby) => {
              userSocket[user].emit('update lobbyRoom', dbNewLobby);
            });

            Lobby.findAll().then((data) => {
              if(data){
                userSocket[user]= socket;
                socket.broadcast.emit('update lobbies', data);
              }
            });

          }
        });
      });

      socket.on('join lobby', (data) => {
        const {user, id} = data;
        Lobby.findOne({
          where: {
            id: id
          }
        }).then( (lobby) => {
          if(lobby){
            const newPlayerList = JSON.parse(lobby.dataValues.players).playerList;
            if(newPlayerList.length < 4){
              newPlayerList.push(user);
              lobby.set("players", { playerList: newPlayerList });
              lobby.save();
              Lobby.findOne({
                where: {
                  id: id
                }
              }).then( (newLobby) => {
                if(newLobby){
                  for(let j=0; j< newPlayerList.length;j++)
                    if(newPlayerList[j] !== 'BotPlayer')
                      userSocket[newPlayerList[j]].emit('update lobbyRoom', newLobby);
                }
              });
            }
          }
        })
      });

      socket.on('leave lobby', (data) => {
        const {user, id} = data;
        Lobby.findOne({
          where: {
            id: id
          }
        }).then( (lobby) => {
          if(lobby){
            const newPlayerList = JSON.parse(lobby.dataValues.players).playerList;
            for(let i=0; i< newPlayerList.length;i++){
              if(newPlayerList[i] === user){
                newPlayerList.splice(i,1);
              }
            }
            if(newPlayerList.length){
              lobby.set("players", { playerList: newPlayerList });
              lobby.save();
              //TODO check this
              Lobby.findOne({
                where: {
                  id: lobby.dataValues.id
                }
              }).then( (dbLobby) => {
                if(dbLobby){
                  for(let j=0; j< newPlayerList.length;j++) {
                    if (newPlayerList[j] !== 'BotPlayer')
                      userSocket[newPlayerList[j]].emit('update lobbyRoom', dbLobby);
                  }
                }
              })
            }
            else {
              lobby.destroy();
            }

          }
        });
      });

      socket.on('add bot', (id) => {
        Lobby.findOne({
          where: {
            id: id
          }
        }).then( (lobby) => {
          if(lobby) {
            const newPlayerList = JSON.parse(lobby.dataValues.players).playerList;
            if(newPlayerList.length < 4) {
              newPlayerList.push("BotPlayer");
              lobby.set("players", {playerList: newPlayerList});
              lobby.save();
              Lobby.findOne({
                where: {
                  id: id
                }
              }).then((newLobby) => {
                if (newLobby) {
                  for (let j = 0; j < newPlayerList.length; j++)
                    if(newPlayerList[j] !== 'BotPlayer')
                      userSocket[newPlayerList[j]].emit('update lobbyRoom', newLobby);
                }
              });
            }
          }
        })
      });


      socket.on('start game', (data) => {
        const {user, id} = data;

        Lobby.findOne({
          where: {
            id: id
          }
        }).then( (lobby) => {
          if(lobby){
            const PlayerList = JSON.parse(lobby.dataValues.players).playerList;
            let gamePlayerList=[];
            let botIndex=1;
            PlayerList.map((name) => {
              if(name === 'BotPlayer'){
                gamePlayerList.push(
                  {
                    name: "Bot "+ botIndex,
                    score: 0,
                    isBot: true,
                    stones: []
                  }
                )
              }
              else {
                gamePlayerList.push(
                  {
                    name: name,
                    score: 0,
                    isBot: false,
                    stones: []
                  }
                )
              }
            });


            PlayerList.map((name) => {
              if(name !== 'BotPlayer') {
                userGame[name]=JSON.parse(JSON.stringify(defaultState));
                userGame[name].playerList = gamePlayerList;
                userGame[name].numberOfPlayers = gamePlayerList.length;
                if(name !== user)
                  userSocket[name].emit('go to game');
                userSocket[name].emit('update state', userGame[name]);
              }
            });


            lobby.destroy();
          }
        });
      });

    });
    io.listen(runnable);
  } else {
    console.error('==>     ERROR: No PORT environment variable has been specified');
  }
});
Example #7
0
// Authentication-related methods
// Module Dependencies
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');

// Local Variables
var User = mongoose.model('User');


// Passport session setup
passport.serializeUser(function(user, next) {
  next(null, user._id);
});

passport.deserializeUser(function(id, next) {
  // @TODO what happend if id isn't a castable Mongo ObjectId type? 
  // Hint: it'll break
  User.findById(id, function(err, user) {
    next(err, user);
  });
});

// Passport Strategy methods
passport.use(new LocalStrategy(function(username, password, next) {
  process.nextTick(function() {
    User.authenticate(username, password, next);
  });
}));

module.exports.ensureAuthenticated = function(req, res, next) {
Example #8
0
  usernameField: 'email',
  passwordField: 'password'
 },
  function(email, password, done) {
    User.authenticate(email, password, function(err, user) {
      if (err) {
        return done(null, false, { message: 'Invalid email/password combination.' });
      }
      return done(null, user);
    });
  }
));

passport.serializeUser(function(user, done) {
  ['password', 'created_at'].forEach(function(attribute) {
    delete user[attribute];
  });
  done(null, user);
});

passport.deserializeUser(function(user, done) {
  done(null, user);
});

//
// Routes.
//
app.get('/', function(req, res) {
  res.render('index', { user: req.user });
});

app.get('/checkin', User.authorize, function( req, res ) {
Example #9
0
    (username, password, cb) => {
        var myUser = _.find(users, (user) => {
            return user.username === username
        })
        if (!myUser) {
            console.log('noMyUser')
            return cb(null, false)
        }
        if (myUser.password !== password) {
            console.log('wrongPassword')
            return cb(null, false)
        }
        return cb(null, myUser)
    }))

passport.serializeUser((user, cb) => {
    cb(null, user.id)
})

passport.deserializeUser((id, cb) => {
    var myUser = _.find(users, (user) => {
        return user.id === id
    })
    if (myUser) {
        cb(null, myUser)
    } else {
        cb('ERROR')
    }
})

module.exports = passport
Example #10
0
  var MongoStore = require('connect-mongo')(session)
  var bodyParser = require('body-parser')
  var logger = require('../common/logging.js').logger
  var passport = require('passport')
  var GitHubStrategy = require('passport-github2').Strategy
  var LinkedInStrategy = require('passport-linkedin-oauth2').Strategy
  var proxy = require('./routes/proxy')

  // set up db connection
  var db = require('./models/db')

  console.log('NODE_ENV: ' + config.util.getEnv('NODE_ENV'))

  // Passport session setup
  passport.serializeUser(function (user, done) {
    done(null, user)
  })

  passport.deserializeUser(function (user, done) {
    done(null, user)
  })

  // use GitHubStrategy with Passport
  passport.use(new GitHubStrategy({
    clientID: (process.env.GH_CLIENT_ID || config.github.clientID),
    clientSecret: (process.env.GH_CLIENT_SECRET || config.github.clientSecret),
    callbackURL: config.github.callbackURL,
    passReqToCallback: true
  },
  function (req, accessToken, refreshToken, extProfile, done) {
    auth.passportStrategySetup(req, accessToken, refreshToken, extProfile, done)
Example #11
0
	auth.init = function (app) {

        passport.use(new localStrategy(userVerify));

        passport.serializeUser(function (user, next) {
            console.log(user);
            next(null, user.username);
        });

        passport.deserializeUser(function (key, next) {
            data.getUser(key, function (err, user) {
                if (err) {
                    next(null, false, { message: "Failed to retrieve user."})
                }else{3
                    next(null, user);
                }
            })
        })

        app.use(passport.initialize());
        app.use(passport.session());
        
        app.get("/login", function (req, res) {
            
            res.render("login", {
                title: "Login to The Board.",
                message: req.flash("loginError")
            });              
            
        });
        
        app.post("/login", function(req, res, next) {
            var authFunction = passport.authenticate("local", function (err, user, info) {
                if (err) {
                    next(err);
                }else{
                    req.logIn(user, function(err){
                        
                        if (err) {
                            next(err);
                        }else{
                            res.redirect("/");
                        }
                    })
                }
            });
            authFunction(req, res, next);
        });
		
		app.get("/register", function (req, res) {
            
            res.render("register", {
                title: "Register for The Board.",
                message: req.flash("registrationError")
            });              
            
        });
        

        app.post("/register", function (req, res) {
            
            var salt = hasher.createSalt();
            
            var password = req.body.password
            
            var passwordHash = hasher.computeHash(password, salt);
            
        	var user = {
        		name: req.body.name,
        		email: req.body.email,
        		username: req.body.username,
        		passwordHash: passwordHash,
        		salt: salt
        	};

        	data.addUser(user, function (err) {
        		if (err) {
        			req.flash("registrationError", "Could not save to database.");
        			res.redirect("/register");
        		} else {
        			res.redirect("/login");
        		}
        	})

        });

	};
Example #12
0
module.exports.routes = function(app) {

  app.use(require('express-session')({
    secret: 'eatmyshorts',
    resave: true,
    saveUninitialized: true,
    cookie : { secure : false, maxAge : (4 * 60 * 60 * 1000) }, // 4 hours
  }));


  app.use(passport.initialize());
  app.use(passport.session());

  app.get('/', controller.home);

  app.get('/api/getItems', controller.getItems);

  app.get('/loginInfo', controller.getLogin);

  app.get('/logout', controller.logout);

  app.post('/login', 
    passport.authenticate('local', {
      successRedirect: '/',
      failureRedirect: '/?msg=Login failed'
    })
  );

  app.post('/api/addComment', controller.addComment);

  app.post('/api/newItem', controller.newItem);

  app.put('/api/buyItem', controller.buyItem);




  //passport
  passport.serializeUser(function(user, done) {
    done(null, user);
  });
  passport.deserializeUser(function(user, done) {
    done(null, user);
  });
  // use method as callback when being authenticated
  passport.use(new passportLocal.Strategy(function(username, password, done) {
    // check the password in database
    User.findOne({
      username: username
    }).then(function(user) {
      console.log(user.id);
        // check the password against hash
        if(user){
          bcrypt.compare(password, user.password, function(err, userlogin) {
            if (userlogin) {
                  // if password is valid -- authenticate the user with cookie
                  done(null, {id: user.id, username: user.username});
                } else{
                  done(null, null);
                }
              });
        } else {
          done(null, null);
        }
      });

  }));

}
Example #13
0
'use strict';

var mongoose      = require('mongoose');
var User          = mongoose.model('User');
var passport      = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config        = require('./config');
var utilities     = require('../utilities/utilities');


// Passport configuration

passport.serializeUser( function(user, done) {
	console.log( 'PassportConfig.serializeUser();' );

	var userId = user._id;

	done(null, userId);
});

passport.deserializeUser( function(userId, done) {
	console.log( 'PassportConfig.deserializeUser();' );

	User.findOne({

		'_id': userId
	},
	'-salt -hashedPassword', // don't ever give out the password or salt.
	function(err, user) {
		if(!user) {
			console.log('Invalid user session.');
Example #14
0
          req.logIn(user, function(er) {
            return next(er);
          });
        if (i == (authSchems.length - 1)) {
          // last in the chain and failed authentication.
          return res.send(401);
        } else {
          return next(err);
        }
        ;
      })(req, res, next);
    };
    break;
  case 'basic':
    return passport.authenticate('basic');
    break;
  }
});

passport.serializeUser(function(user, done) {
  done(null, user.authMethod + ";" + user.username);
});

passport.deserializeUser(function(id, done) {
  User.findOne(id.substr(id.indexOf(';') + 1), function(err, user) {
    user.authMethod = id.substr(0, id.indexOf(";"));
    done(err, user);
  });
});

module.exports = passport;
}

if (process.env.GOOGLE_AUTH) {
  googleAuth = JSON.parse(process.env.GOOGLE_AUTH);
} else {
  googleAuth = require('./local.js').socialIds.google;
}

if (process.env.TWITTER_AUTH) {
  twitterAuth = JSON.parse(process.env.TWITTER_AUTH);
} else {
  twitterAuth = require('./local.js').socialIds.twitter;
}

passport.serializeUser(function(user, done) {
  'use strict';
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  'use strict';
  User.findOne({
    id: id
  }, function(err, user) {
    done(err, user);
  });
});

passport.use('local-login', new LocalStrategy({
    // by default, local strategy uses username and password, we will override with email
    usernameField: 'email',
    passwordField: 'password',
Example #16
0
			SIENDO:
				password la clave enviada desde la vista
				response[0].clave la clave (encriptada) en la base de datos.
			LA FUNCIÓN DEVOLVERÁ true, si las claves coinciden y false en caso contrario..
			*/
			//AÑADIR EN EL IF LA CONDICIONAL QUE INDIQUE SI LAS CLAVES COINCIDEN...
			if (err || response.length === 0)
			{
				return done(null, false, {message: 'Usuario o contraseña no válido', usuario : username});
			}
			return done(null, response);
		});
	}));

	passport.serializeUser(function(user, done)
	{
	    done(null, user[0].usuario);
	});

	passport.deserializeUser(function(username, done)
	{
		//CREAR SENTENCIA SQL QUE DADO EL NOMBRE USUARIO (QUE ES ÚNICO)
		//DEVUELVA EL NOMBRE COMPLETO DEL USAURIO Y EL ID DEL MISMO...
		var sql = "";//VARIABLE QUE GUARDARÁ LA SENTENCIA SQL...
		db.queryMysql(sql, function(err, response)
		{
			if(response)
			{
				done(null, response);
			}
		});
	});
Example #17
0
module.exports = function(auth, client) {
  auth.use(passport.initialize());
  auth.use(passport.session());

  passport.serializeUser(function(user, done) {
    done(null, user.user_id);
  });

  passport.deserializeUser(function(id, done) {
    var query = "SELECT * FROM users WHERE user_id = $1";
    client.query(query, [id], function(err, result) {
      if (err) {
        return done(err);
      }

      if (result.rows.length < 1) {
        return done(null, false);
      }

      var user = result.rows[0];
      return done(null, user);
    });
  });

  passport.use(new FacebookTokenStrategy({
    clientID: config.facebook.app_id || null,
    clientSecret: config.facebook.app_secret || null
  }, function(accessToken, refreshToken, profile, done) {
    var query = "SELECT * FROM users WHERE facebook_id = $1";
    client.query(query, [profile.id], function(err, results) {
      if (err) {
        return done(err, null);
      }

      if (results.rows.length > 0) {
        return done(null, results.rows[0]);
      } else {
        query = "INSERT INTO users (first_name, last_name, facebook_id) VALUES ($1, $2, $3) RETURNING *";
        client.query(query, [profile.name.givenName, profile.name.familyName, profile.id], function(err, results) {
          if (err) {
            return done(err, null);
          }

          return done(null, results.rows[0]);
        });
      }
    });
  }));

  passport.use(new LocalStrategy({usernameField: 'email'}, function(email, password, done) {
    var query = "SELECT * FROM users WHERE email = $1";
    client.query(query, [email], function(err, result) {
      if (err) {
        return done(err);
      }

      if (result.rows.length < 1) {
        return done(null, false);
      }

      var user = result.rows[0];

      if (bcrypt.compareSync(password, user.token)) {
        return done(null, user);
      } else {
        return done(null, false);
      }
    });
  }));

  const saltRounds = 10;

  auth.post('/auth/register', function(req, res) {
    // Validate request
    var requirements = ['first_name', 'last_name', 'email', 'password'];
    var data = {};
    requirements.forEach(function(requirement) {
      if (!req.body[requirement]) {
        return res.statusCode(400).json({
          error: 'Invalid request',
          message: 'You need to specify a ' + requirement + ' field.'
        });
      }

      data[requirement] = req.body[requirement];
    });

    // Check if the email is in use
    client.query("SELECT * FROM users WHERE email=$1", [data.email], function(err, result) {
        if (err) {
            return res.status(500).send('Internal server error');
        }

        if (!result.rows || result.rows.length != 0) {
            return res.status(400).json({
                error: 'Email already in use'
            });
        }

        // Hash the password
        bcrypt.hash(data.password, saltRounds, function(err, hash) {
          var query = "INSERT INTO users (first_name, last_name, email, token)"
            + " VALUES ($1, $2, $3, $4)";
          client.query(query, [data.first_name, data.last_name, data.email, hash], function(err, result) {
            if (err) {
              return res.status(500).send('Internal server error');
            }

            return res.json({
              success: true
            });
          });
        });
    });
  });

  auth.post('/auth/login', passport.authenticate('local'), function(req, res) {
    return res.json(req.user);
  });

  auth.get('/auth/loggedIn', function(req, res) {
    return res.json({
      user: req.isAuthenticated() ? req.user : undefined
    });
  });

  auth.get('/auth/facebook', passport.authenticate('facebook-token'), function(req, res) {
    return res.json(req.user);
  });

  auth.get('/auth/logout', function(req, res) {
    req.logout();
    return res.json({
      success: true
    });
  });
};
Example #18
0
var passport = require('passport'),
	LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
	function(username, password, done) {
		if (username === 'root' && password === 'changeme') {
			return done(null, {username: username});
		}

		return done(null, false);
	}
));

passport.serializeUser(function(user, done) {
	done(null, user.username);
});

passport.deserializeUser(function(username, done) {
	done(null, {username: username});
});

module.exports = passport;
Example #19
0
        }
    });
}));



// flash middleware config
//      + passport isAuth to view.
app.use(flash());


app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(user, done) {
	// console.log('dude: ' + user);
	done(null, user.id);
});

passport.deserializeUser(function(id, done) {
	User.findById(id, function(err, user) {
		done(err, user);
	});
});


// passport.use(new FacebookStrategy({
// 		clientID: '1604691576425029',
// 		clientSecret: "988d26ec347add1e1c3f18325e1ee853",
// 		// callbackURL: "http://localhost:3000/auth/facebook/callback",
// 		profileFields: [
// 			'id', 'name',
Example #20
0
export default function(app) {
  app.use(session({
    store: new PgSession({
      pg: pg,
      conString: makePgConString({
        user: config.postgresUser,
        password: config.postgresPassword,
        host: config.postgresHost,
        db: config.postgresDb
      }),
      tableName: 'sessions'
    }),
    secret: config.authSecret,
    cookie: {maxAge: 30 * 24 * 60 * 60 * 1000} // 30 days
  }));

  passport.serializeUser((user, done) => {
    done(null, user.facebookId);
  });

  passport.deserializeUser((id, done) => {
    query('select * from users where facebook_id = $1', [id]).then((result) => {
      let row = result.rows[0];
      let user = {
        accessToken: row.access_token,
        refreshToken: row.refresh_token,
        facobookId: row.facebook_id,
        displayName: row.display_name
      };

      done(null, user);
    }).catch(done);
  });

  passport.use(new FacebookStrategy({
    clientID: config.fbClientId,
    clientSecret: config.fbSecret,
    callbackURL: config.fbCallbackUrl
  }, (accessToken, refreshToken, profile, done) => {
    let user = {
      accessToken,
      refreshToken,
      facebookId: profile.id,
      displayName: profile.displayName
    };

    query('select * from users where facebook_id = $1', [profile.id]).then((result) => {
      // if there is already a user record for this id
      if (result.rows.length) {
        return query(`
          update users set
            access_token = $1,
            refresh_token = $2,
            display_name = $3
          where facebook_id = $4
          `,
          [user.accessToken, user.refreshToken, user.displayName, user.facebookId]
        );
      } else {
        // create a new one
        return query(
          `insert into users (access_token, refresh_token, display_name, facebook_id)
           values ($1, $2, $3, $4)`,
           [user.accessToken, user.refreshToken, user.displayName, user.facebookId]
        );
      }
    }).then(() => done(null, user)).catch(done);
  }));

  // Should be added after `app.use(session)`
  app.use(passport.initialize());
  app.use(passport.session());

  app.get('/auth/facebook', passport.authenticate('facebook'));
  app.get('/auth/facebook/callback', passport.authenticate('facebook', {
    successRedirect: '/',
    failureRedirect: '/login'
  }));
};
Example #21
0
app.use(express.static(path.join(__dirname, 'public')));

app.configure('development', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
    app.use(express.errorHandler());
});



// passport config
var Account = require('./models/account');
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());

// mongoose
mongoose.connect('mongodb://localhost/passport_local_mongoose');

schema = new mongoose.Schema({ name: 'string', information: 'string', lat: 'string', lon: 'string', userid: 'string' });
Locations = mongoose.model('Locations', schema);

// routes
require('./routes')(app);

app.listen(app.get('port'), function(){
  console.log(("Express server listening on port " + app.get('port')))
});
module.exports = function(app, models) {

    var flixUserModel = models.flixUserModel;

    var multer = require('multer'); // npm install multer --save
    var upload = multer({ dest: __dirname+'/../../public/uploads' });


    // app.get("/auth/facebook", passport.authenticate('facebook'));
    // app.get("/auth/facebook/callback",
    //     passport.authenticate('facebook', {
    //         successRedirect: '/assignment/#/user',
    //         failureRedirect: '/assignment/#/login'
    //     }));/auth/google
    app.get("/auth/google", passport.authenticate('google', { scope: ['profile', 'email'] }));
    app.get("/auth/google/callback",
        passport.authenticate('google', {
            successRedirect: '/project/#/user',
            failureRedirect: '/project/#/login'
        }));
    app.post ("/api/uploads", upload.single('myFile'), uploadImage);
    app.post("/api/user", createUser);
    app.get("/api/loggedIn", loggedIn);
    app.post("/api/register", register);
    app.post("/api/logout", logout);
    app.post("/api/login", passport.authenticate('project'), login);
    app.get("/api/user", getUser);
    app.get("/api/user/:userId", findUserById);
    app.put("/api/user/:userId", updateUser);
    app.delete("/api/user/:userId", deleteUser);

    passport.use('project', new LocalStrategy(projectLocalStrategy));
    passport.serializeUser(serializeUser);
    passport.deserializeUser(deserializeUser);

    var googleConfig = {
        clientID     : process.env.GOOGLE_CLIENT_ID,
        clientSecret : process.env.GOOGLE_CLIENT_SECRET,
        callbackURL  : process.env.GOOGLE_CALLBACK_URL
    };

    passport.use('google', new GoogleStrategy(googleConfig, googleLogin));

    // var facebookConfig = {
    //     clientID     : process.env.FACEBOOK_CLIENT_ID,
    //     clientSecret : process.env.FACEBOOK_CLIENT_SECRET,
    //     callbackURL  : process.env.FACEBOOK_CALLBACK_URL
    // };
    //
    // passport.use('facebook', new FacebookStrategy(facebookConfig, facebookLogin));


    function projectLocalStrategy(username, password, done) {
        // console.log("Serverservice");
        // console.log(username+" "+password);
        flixUserModel
            .findUserByUsername(username)
            .then(
                function(user) {
                    if(user && bcrypt.compareSync(password, user.password)) {
                        done(null, user);
                    }
                    else {
                        done(null, false);
                    }
                },
                function(error) {
                    done(null, error);
                }
            );
    }

    function serializeUser(user, done) {
        done(null, user);
    }

    function deserializeUser(user, done) {
        flixUserModel
            .findUserById(user._id)
            .then(
                function(user){
                    done(null, user);
                },
                function(err){
                    done(err, null);
                }
            );
    }

    function register(request, response) {
        var username = request.body.username;
        var password = request.body.password;
        // console.log("Register server service");
        // console.log(username + " " + password);
        flixUserModel
            .findUserByUsername(username)
            .then(
                function(user) {
                    if(user){
                        // console.log("Server service");
                        // console.log(user);
                        response.status(400).send("Username already in use");

                        return;
                    }
                    else {
                        request.body.password = bcrypt.hashSync(request.body.password);
                        return flixUserModel.createUser(request.body);
                    }
                },
                function(error) {
                    response.send(error);
                }
            )
            .then(
                function(user) {
                    if(user) {
                        //Utility function provided by passport
                        request.login(user, function(error) {
                            if(error) {
                                response.status(400).send(error);
                            }
                            else {
                                response.json(user);
                            }
                        });
                    }
                },
                function(error) {
                    response.status(400).send(error);
                }
            );
    }
    
    function googleLogin(token, refreshToken, profile, done) {
        // response.send(200);
        flixUserModel
            .findGoogleUser(profile.id)
            .then(
                function(googleUser) {
                    if (googleUser) {
                        return done(null, googleUser);
                    }
                    else {
                        var email = profile.emails[0].value;
                        var splitEmail = email.split("@");
                        var googleUser = {
                            username: splitEmail[0],
                            firstName: profile.name.givenName,
                            lastName: profile.name.familyName,
                            email: email,
                            google: {
                                id: profile.id,
                                token: token
                            }
                        };
                        flixUserModel
                            .createUser(googleUser)
                            .then(
                                function(user) {
                                    done(null, user);
                                }
                            );
                    }
                }
            );
    }
    
    function loggedIn(request, response) {
        if(request.isAuthenticated()) {
            response.json(request.user);
        }
        else {
            response.send('0');
        }
    }
    
    function logout(request, response) {
        //Function added by passport to the request object to invalidate the session,
        // cookie and remove the current logged in user from the session.
        request.logout();
        
        response.send(200);
    }

    function login(request, response) {
        //Passport adds the current user to the request.
        var user = request.user;
        response.json(user);
    }

    function uploadImage(request, response) {
        
        var myFile = request.file;
        var userId = request.body.userId;


        var originalname  = myFile.originalname; // file name on user's computer
        var filename      = myFile.filename;     // new file name in upload folder
        var path          = myFile.path;         // full path of uploaded file
        var destination   = myFile.destination;  // folder where file is saved to
        var size          = myFile.size;
        var mimetype      = myFile.mimetype;

        // for (var i in widgets) {
        //     if (widgets[i]._id === widgetId) {
        //         widgets[i].url = "/uploads/" +filename;
        //     }
        // }

        var url = "/uploads/" +filename;

        flixUserModel
            .uploadImage(userId, url)
            .then(
                function(stat) {
                    response
                        .redirect("/project/#/user");
                },
                function(error) {
                    response.statusCode(404).send(error);
                }
            )


    }
    
    
    function deleteUser(request, response) {
        var id = request.params.userId;
        // for(var i in users) {
        //     if(users[i]._id === id) {
        //         users.splice(i, 1);
        //         //console.log(users);
        //         response.send(200);
        //         return;
        //     }
        // }
        // response.send(400);

        flixUserModel
            .deleteUser(id)
            .then(
                function(stats) {
                    //console.log(stats);
                    response.send(200);
                },
                function(error) {
                    response.statusCode(404).send(error);
                }
            );
    }

    function updateUser(request, response) {
        var id = request.params.userId;
        var newUser = request.body;
        // for(var i in users) {
        //     if(users[i]._id === id) {
        //         users[i].firstName = newUser.firstName;
        //         users[i].lastName = newUser.lastName;
        //         response.send(200);
        //         return;
        //     }
        // }
        // response.send(400);

        flixUserModel
            .updateUser(id, newUser)
            .then(
                function(stat) {
                    //console.log(stat);
                    response.send(200);
                },
                function(error) {
                    response.statusCode(404).send(error);
                }
            );
    }


    function createUser(request, response) {
        var user = request.body;

        flixUserModel
            .createUser(user)
            .then(
                function(user) {
                    // console.log(user);
                    response.json(user);
                },
                function(error) {
                    response.statusCode(400).send(error);
                }
            );


        // console.log("createUser");
        // console.log(user);

        // user._id = (new Date()).getTime()+"";
        // users.push(user);
        // response.send(user);
    }

    function getUser(request, response) {
        var username = request.query['username'];
        var password = request.query['password'];
        //console.log(username);
        //console.log(password);
        if(username && password) {
            findUserByCredentials(username, password, response, request);
            }
        else if(username) {
            findUserByUsername(username, response);
        }
        else {
            response.send(users);
        }
    }

    function findUserByCredentials(username, password, response, request) {
        // for(var i in users) {
        //     if(users[i].username === username && users[i].password === password){
        //         response.send(users[i]);
        //         return;
        //     }
        // }
        // return response.send({});

        flixUserModel
            .findUserByCredentials(username, password)
            .then(
                function(user) {
                    // console.log(request.session);
                    request.session.currentUser = user;
                    response.json(user);
                },
                function(error) {
                    response.statusCode(404).send(error);

                }
            );
    }

    function findUserByUsername(username, response) {
        // for(var i in users) {
        //     if(users[i].username === username){
        //         response.send(users[i]);
        //         return;
        //     }
        // }
        // return response.send({});
        flixUserModel
            .findUserByUsername(username)
            .then(
                function(user) {
                    response.json(user);
                },
                function(error) {
                    response.statusCode(404).send(error);
                }
            );
    }
    
    function findUserById(request, response) {
        var id = request.params.userId;

        //console.log(request.session.currentUser);

        flixUserModel
            .findUserById(id)
            .then(
                function(user) {
                    response.json(user);
                },
                function(error) {
                    response.statusCode(404).send(error);
                }
            )
        // for(var i in users) {
        //     if(users[i]._id === id) {
        //         response.send(users[i]);
        //         return;
        //     }
        // }
        // response.send({});
    }
};
module.exports = function (app, models) {

    var userModel = models.userModel;

    app.get('/auth/facebook/callback/',
        passport.authenticate('facebook', {
            successRedirect: '/assignment/#/user',
            failureRedirect: '/assignment/#/login'
    }));

    app.get ('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));
    app.post("/api/user", createUser);
    app.post("/api/logout", logout);
    app.get ('/api/loggedin', loggedin);
    app.post("/api/login", passport.authenticate('webapp'), login);
    app.post("/api/register", register);
    app.get("/api/user/:uid", findUserById);
    app.get("/api/user", getUsers);
    app.put("/api/user/:uid", updateUser);
    app.delete("/api/user/:uid", authenticate, deleteUser);

    passport.use('webapp', new LocalStrategy(localStrategy));
    passport.serializeUser(serializeUser);
    passport.deserializeUser(deserializeUser);

    var facebookConfig = {
        clientID     : process.env.FACEBOOK_CLIENT_ID,
        clientSecret : process.env.FACEBOOK_CLIENT_SECRET,
        callbackURL  : process.env.FACEBOOK_CALLBACK_URL
    };

    passport.use(new FacebookStrategy(facebookConfig, facebookStrategy));

    function facebookStrategy(token, refreshToken, profile, done) {
        var id = profile.id;
        userModel
            .findFacebookUser(id)
            .then(
                function(user) {
                    if(user) {
                        return done(null, user);
                    }
                    else {
                        var user = {
                            username: profile.displayName.replace(/ /g, ''),
                            facebook: {
                                id: profile.id,
                                displayName: profile.displayName
                            }
                        };
                        return userModel
                            .createUser(user);
                        }
                    }
                )
            .then(
                function (user) {
                    return done(null, user);
                }
            );
    }

    function authenticate(req, res, next) {
        //console.log(req.user);
        //console.log(req.isAuthenticated());
        if(req.isAuthenticated()) {
            next();
        }
        else {
            res.send(403);
        }
    }

    function serializeUser(user, done) {
        done(null, user);
    }

    function deserializeUser(user, done) {
        userModel
            .findUserById(user._id)
            .then(
                function(user){
                    done(null, user);
                },
                function(err){
                    done(err, null);
                }
            );
        }

    function localStrategy(username, password, done) {
        userModel
            .findUserByUsername(username)
            .then(
                function(user) {
                    if(user && bcrypt.compareSync(password, user.password)) {
                        return done(null, user);
                    }
                    else {
                        return done(null, false);
                    }
                },
                function(err) {
                    if (err) { return done(err); }
                }
            );
    }

    function logout(req, res) {
        req.logout();
        res.sendStatus(200);
    }

    function loggedin(req, res) {
        if(req.isAuthenticated()) {
            res.json(req.user);
        }
        else {
            res.send('0');
        }
    }

    function register(req, res) {
        var username = req.body.username;
        var password = req.body.password;
        userModel
            .findUserByUsername(username)
            .then(
                function(user) {
                    if(user) {
                        res.status(400).send("Username already exists");
                        return;
                    }
                    else {
                        req.body.password = bcrypt.hashSync(password);
                        return userModel
                            .createUser(req.body);
                    }
                    //console.log(user);
                    res.send(200);
                },
                function(error) {
                    res.status(400).send(error);
                }
            )
            .then(
                function(user) {
                    if(user){
                        req.login(user, function(err) {
                        if(err) {
                            res.status(400).send(err);
                        }
                        else {
                            res.json(user);
                        }
                        });
                    }
                },
                function(error) {
                    res.status(400).send(error);
                }
            )
    }

    function login(req, res) {
        var user = req.user;
        res.json(user);
    }

    function getUsers(req, res) {
        var username = req.query["username"];
        var password = req.query["password"];
        if(username && password) {
            findUserByCredentials(username, password, req, res);
        } else if(username) {
            findUserByUsername(username, req, res);
        } else {
            res.send(users);
        }
    }

    function findUserById(req, res) {
        var id = req.params["uid"];

        userModel
            .findUserById(id)
            .then(
                function(user) {
                    res.send(user)
                },
                function(error) {
                    res.sendStatus(400).send(error);
                }
            );
    }

    function findUserByCredentials(username, password, req, res) {
        userModel
            .findUserByCredentials(username, password)
            .then(
                function(user) {
                    res.json(user);
                },
                function(error) {
                    res.sendStatus(403).send("User not found")
                }
            );
    }

    function findUserByUsername(username, req, res) {
        userModel
            .findUserByUsername(username)
            .then(
                function(user) {
                    res.json(user);
                },
                function(error) {
                    res.send({});
                }
            );
    }

    function updateUser(req, res) {
        var id = req.params["uid"];
        var newUser = req.body;

        userModel
            .updateUser(id, newUser)
            .then(
                function(user) {
                    res.sendStatus(200);
                },
                function(error) {
                    res.status(404).send("User not found");
                }
            );
    }

    function deleteUser(req, res) {
        var id = req.params["uid"];
        //console.log(id);

        userModel
            .deleteUser(id)
            .then(
                function(status) {
                    res.sendStatus(200);
                },
                function(error) {
                    res.status(404).send("User not found");
                }
            );
    }

    function createUser(req, res) {
        var user = req.body;

        userModel
            .createUser(user)
            .then(
                function(user) {
                    res.json(user);
                },
                function(error) {
                    res.status(400).send("Username already in use");
                }
            );
    }
};
Example #24
0
    proxy: true
  },
  function(accessToken, refreshToken, profile, done) {
    // console.log(profile);
    Poster.findOrCreate({googleId: profile.id}, function (err, poster) {
      poster.username = profile.displayName;
      // console.log('googleAuth', poster);
      return done(err, poster);
    });
  }
));


// Serialize data into the session
passport.serializeUser(function(user, cb) {
  // console.log('serializeUser')
  cb(null, user);
});

passport.deserializeUser(function(obj, cb) {
  // console.log('deserializeUser');
  cb(null, obj);
});




/**********
 * Routes *
 **********/

auth.get('/auth/twitter',
Example #25
0
app.use(cookieParser);
app.use(cookieSession);

// add csrf support
app.use(express.csrf({value: auth.csrf}));
app.use(function(req, res, next) {
   res.cookie('XSRF-TOKEN', req.csrfToken());
   next();
});

// setup passport authentication
app.use(passport.initialize());
app.use(passport.session());

passport.use(auth.localStrategy);
passport.serializeUser(auth.serializeUser);
passport.deserializeUser(auth.deserializeUser);

// add session login|logout routes
app.post('/session/login', auth.login);
app.get('/session/logout', auth.logout);

// add session user request route
app.get('/session/user', auth.ensureAuthenticated, function(req, res, next) {
  return res.json(req.session.user);
});

// add express api routes
app.get('/api/awesomeThings', function(req, res, next) {
  return routes.awesomeThings(req, res, next);
});
Example #26
0
app.use(express.static(path.join(__dirname, 'public')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('express-session')({
    secret: 'melody',
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

// configure passport
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

// routes
app.use('/user/', routes);

// get static pages
app.get('/', function(req, res) {
	console.log('Served up index.html');
	res.sendFile('./public/partials/index.html', {root : __dirname});
});

app.get('/log-in', function(req, res) {
  console.log('Served up log-in.html');
  res.sendFile('./public/partials/authentication/log-in.html', {root : __dirname});
});
Example #27
0
    if (index != -1) {
      clients.splice(index, 1);
      console.info('Client disconnected: ', + socket.id);
      // console.log('All clients: ', clients);
    }
  })

});



//==================================
//PASSPORT SERIALIZATIONS

   passport.serializeUser(function(user, done) {
     console.log('PASSPORT SERIALIZEUSER: ', user.id);
      done(null, user.id);
   });

   passport.deserializeUser(function(id, done) {
      console.log('PASSPORT DE-SERIALIZEUSER: ', id);
      User.findById(id, function(err, user) {
        console.log('PASSPORT DE-SERIALIZEUER user ', user);
          done(err, user);
      });
   });

//==================================

 app.get('/', function(req,res){
   // isLoggedIn();
   res.render('index.ejs', { user: req.user });
Example #28
0
			if (!user) {
				return callback(null,false); // no error, but not valid
			}
			bcrypt.compare(password,user.password,function(err,result){
			if (err || !result) {
				return callback(null,false); // no error, passwords don't match
			}
			return callback(null, user); // no error, user valid
			})
		})
		.catch(function(err){
			return callback(err); // error
		});
	}));

passport.serializeUser(function(user,callback){
	callback(null, user.username);
});

passport.deserializeUser(function(id,callback){
	models.User.findById(id)
	.then(function(user){
		callback(null,user);
	})
	.catch(function(err){
		callback(err);
	});
});

module.exports = passport;
Example #29
0
    // reason. Connect anyway.
    var tlsOptions = {rejectUnauthorized: false};
    client.starttls(tlsOptions, null, function(err) {
        var dn = username + '@illinois.edu';
        client.bind(dn, password, function(err, user) {
            if (err) {
                if (err.name === 'InvalidCredentialsError') {
                    return done(null, false);
                }
                return done(err);
            }

            getAuthenticatedUser(username, done);
        });
    });
}));

passport.serializeUser(function(user, done) {
    done(null, user.netid);
});

passport.deserializeUser(function(netid, done) {
    db.User.find({
        where: {netid: netid}
    }).then(function(user) {
        done(null, user);
    });
});

module.exports = passport;
Example #30
0
  	var args = {
	   data: {id:player.id,handle:player.username,name:player.displayName,photo:photo,chosenTeam:team},
	   headers: { "Content-Type": "application/json" }
	};
	   
	client.post("http://yourwebsite.com/player", args, function (data, response) {
		//console.log(data);
		//console.log(response);
	});
  	
    return cb(null, player);
}));

// Configure Passport authenticated session persistence.
passport.serializeUser(function(user, cb) {
  cb(null, user);
});

passport.deserializeUser(function(obj, cb) {
  cb(null, obj);
}); 

// Initialize Passport and restore authentication state, if any, from the session.
app.use(passport.initialize());
app.use(passport.session());

// Manually handling login for each side with a login1 and login2
app.get('/login1', function(req, res) {
	team = 1;
	res.redirect('/login/twitter');
});