{"size": 1478, "ext": "js", "max_stars_repo_path": "backend/controllers/AuthCtrl.js", "max_stars_repo_name": "ega-forever/ots-showcase", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "backend/controllers/AuthCtrl.js", "max_issues_repo_name": "ega-forever/ots-showcase", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "backend/controllers/AuthCtrl.js", "max_forks_repo_name": "ega-forever/ots-showcase", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.4827586207, "max_line_length": 95, "alphanum_fraction": 0.5723951286}
/**
 * @type {controller}
 * @description Authentication controller - handles oauth + bearer flows
 */

const config = require('../config'),
  GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
  UserModel = require('../models').schemas.UserSchema,
  _ = require('lodash'),
  moment = require('moment'),
  BearerStrategy = require('passport-http-bearer');

module.exports = function(passport) {

  passport.use(
    new BearerStrategy((token, done) => {
      UserModel.findOne({
        where: {
          access_token: token,
          updatedAt: {
            $gt: moment().add(-1, 'days').format()
          }
        }
      })
        .then(user => {
          return done(null, user, {scope: 'all'})
        })

    })
  );

  passport.serializeUser((user, callback) =>
    callback(null, user)
  );

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

  passport.use(new GoogleStrategy(config.oauth, (accessToken, refreshToken, profile, done) => {
      UserModel.findOne({where: {googleId: profile.id}})
        .then(user =>
          user ? UserModel.update(
            {access_token: accessToken},
            {where: {googleId: profile.id}}
          ) : UserModel.create(
            {googleId: profile.id, access_token: accessToken}
          )
        )
        .then((record) => {
          done(null, _.merge({access_token: accessToken}, record.dataValues))
        })
        .catch(err => done(err))
    }
  ));

};
