示例#1
0
  constructor (modules) {
    this.log = modules.log('app')
    this.config = modules.config
    this.db = modules.db
    this.timerWorker = modules.timerWorker
    this.notificationWorker = modules.notificationWorker

    const koaApp = this.koa = websockify(koa())
    const router = this._makeRouter()
    koaApp.use(logger())
    koaApp.use(errorHandler({log: modules.log('error-handler')}))
    koaApp.use(cors({expose: ['link']}))
    koaApp.use(passport.initialize())
    koaApp.use(router.middleware())
    koaApp.use(router.routes())
    // Serve static files
    koaApp.use(serve(path.join(__dirname, 'public')))
    koaApp.use(compress())

    const websocketRouter = this._makeWebsocketRouter()
    koaApp.ws.use(logger())
    koaApp.ws.use(errorHandler({log: modules.log('ws-error-handler')}))
    koaApp.ws.use(passport.initialize())
    koaApp.ws.use(websocketRouter.routes())
    koaApp.ws.use(websocketRouter.allowedMethods())
  }
示例#2
0
  install (server) {
    const app = server.app,
          options = server.options;

    this.app = app;

    passport.serializeUser((user, done) => done(null, user.id));
    passport.deserializeUser(function (id, done) {
      actions.getUser(id).then((user) => done(null, user));
    });

    passport.use(new GoogleStrategy(this.strategyConfig(options), this.onAuth.bind(this)));

    app.use(passport.initialize());
    app.use(passport.session());
    app.use(route.get('/auth/google', passport.authenticate('google')));
    app.use(route.get('/auth/google/callback', passport.authenticate('google', {
      successRedirect: '/',
      failureRedirect: '/login'
    })));
    app.use(route.get('/logout', function *() {
      this.logout();
      this.redirect('/');
    }));
  }
示例#3
0
exports.init = function(app) {

  app.use(function* cleanEmptySessionPassport(next) {
    yield* next;
    if (this.session && this.session.passport && Object.keys(this.session.passport).length === 0) {
      delete this.session.passport;
    }
  });

  app.use(function* defineUserGetter(next) {
    Object.defineProperty(this, 'user', {
      get: function() {
        return this.req.user;
      }
    });
    yield* next;
  });



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

  if (process.env.NODE_ENV == 'test') {
    app.use(testAutoLogin);
  }

};
示例#4
0
db.then(() => {
  const publicDir = './public'
  const app = koa()
  const compiler = webpack(webpackConfig)
  const port = config.get('server.port')

  app.keys = [config.get('server.sessionKey')]

  app.on('error', (err, ctx) => {
    const { request: req, response: res } = ctx
    if (err.code) {
      error({ code: err.code }, err.message)
    } else {
      error({ err, req, res }, 'server error')
    }
  })

  app.use(errorMiddleware)
  app.use(bodyparser())
  app.use(session({
    key: 'koa.sid',
    store: new MongoStore(),
    cookie: {
      path: '/',
      httpOnly: true,
      maxage: 30 * 24 * 60 * 60 * 1000,
      rewrite: true,
      signed: true,
    },
  }))
  app.use(passport.initialize())
  app.use(passport.session())

  app.use(logger)

  app.use(rewrite('/app', '/index.html'))
  app.use(rewrite('/access', '/index.html'))
  app.use(rewrite('/app/*', '/index.html'))
  app.use(rewrite('/access/*', '/index.html'))
  app.use(mount('/api', api))

  if (process.env.NODE_ENV === 'development') {
    app.use(webpackMiddleware(compiler, {
      publicPath: webpackConfig.output.publicPath,
      noInfo: true,
      stats: {
        colors: true,
      },
    }))
    app.use(hotMiddleware(compiler))
  } else {
    app.use(serve(publicDir))
  }

  app.listen(port, () => {
    const host = 'localhost'
    fatal('Server listening at http://%s:%s %s',
      host, port, publicDir)
  })
})
module.exports = (app) => {
  // session
  app.keys = ['secret1', 'secret2', 'secret3'];
  app.use(convert(session()));

  // logger
  app.use(logger());

  // view engine
  app.use(views(path.resolve(__dirname, 'views'), { extension: 'ejs' }));

  // static
  app.use(koaStatic({
    rootDir: path.resolve(__dirname, 'static'),
  }));

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

  app.use(conditional());
  app.use(etag());
  app.use(body());

  app.use(async (ctx, next) => {
    ctx.body = ctx.request.body;
    await next();
  });

  app.use(new CSRF());

  onerror(app);
};
示例#6
0
module.exports = function*(app, usrDir) {

    debug('loading standard application');

    middleware.common(app, usrDir);

    // Authentication
    require('./util/auth');
    var passport = require('koa-passport');
    app.use(passport.initialize());
    app.use(passport.session());

    app.use(function*(next) {
        this.state._isLogged = this.isAuthenticated();
        this.state._user = this.req.user;
        yield next;
    });

    main(app, usrDir);

    debug('middlewares mounted');

    // TODO look for config

    yield hds.init(app.config.db);
    debug('hds ready');

    app.close = function () {
        return hds.close();
    };

};
示例#7
0
/**
 * Initialize an app with the given `opts`.
 *
 * @param {Object} opts
 * @return {Application}
 * @api public
 */
function api(opts) {
  opts = opts || {};
  let app = koa();

  // Oauth2 server init & caching
  let oauthServer = oauth2orize.createServer();
  oauth.init(oauthServer);
  generateAccessToken.cacheOauthServer(oauthServer);

  // querystring
  require('koa-qs')(app);
  app.querystring = require('qs');

  app.use(body());

  app.use(cors({
    methods: 'GET,POST,PUT,PATCH,OPTIONS',
    headers: 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since',
    maxAge: 300000,
    credentials: true
  }));

  // Logging
  if ('test' != env) app.use(logger());

  // Passport
  app.use(passport.initialize());

  // Enable app-wide authentication
  app.use(isAuthenticated());

  // Etag
  app.use(conditional());
  app.use(etag());

  // x-response-time
  app.use(responseTime());

  // compression
  app.use(compress());

  // rate limiting
  app.use(ratelimit({
    max: opts.ratelimit,
    duration: opts.duration,
    db: redis.hiringTicket
  }));

  // routing
  app.use(router(app));

  // Error handling
  app.use(error());

  // boot
  load(app, __dirname + '/api');

  return app;
}
示例#8
0
  constructor (modules) {
    this.log = modules.log.create('app')
    this.config = modules.config
    this.db = modules.db
    this.timerWorker = modules.timerWorker
    this.notificationBroadcaster = modules.notificationBroadcaster

    const koaApp = this.koa = websockify(koa())
    const router = this._makeRouter()
    const isTrace = this.log.trace()
    koaApp.use(logger(this.log))
    koaApp.use(logger.requestIdContext())
    koaApp.use(logger.requestLogger({
      updateRequestLogFields: function (fields) {
        return {
          headers: this.req.headers,
          body: isTrace ? this.body : undefined,
          query: this.query
        }
      },
      updateResponseLogFields: function (fields) {
        return {
          duration: fields.duration,
          status: this.status,
          headers: this.headers,
          body: isTrace ? this.body : undefined
        }
      }
    }))
    koaApp.use(errorHandler({log: modules.log.create('error-handler')}))
    koaApp.use(cors({expose: ['link']}))
    koaApp.use(passport.initialize())
    koaApp.use(router.middleware())
    koaApp.use(router.routes())
    // Serve static files
    koaApp.use(serve(path.join(__dirname, 'public')))
    koaApp.use(compress())

    const websocketRouter = this._makeWebsocketRouter()
    koaApp.ws.use(logger())
    koaApp.ws.use(errorHandler({log: modules.log.create('ws-error-handler')}))
    koaApp.ws.use(passport.initialize())
    koaApp.ws.use(websocketRouter.routes())
    koaApp.ws.use(websocketRouter.allowedMethods())
  }
示例#9
0
Auth.prototype.middleware = function() {
    var auth = this;

    return compose([
        session(),
        passport.initialize(),
        passport.session(),
        function *(next) {
            this.auth = auth;
            yield next;
        }
    ]);
}
示例#10
0
export default function(app) {
    passport.serializeUser((user, cb) => cb(null, user));
    passport.deserializeUser((obj, cb) => cb(null, obj));

    app.use(convert(session()));
    passport.use(require('./strategies/local')(app));
    passport.use(require('./strategies/jwt')(app));
    passport.use(require('./strategies/google')(app));

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

    app.passport = passport;
}
示例#11
0
export default function middleware(app) {

    app.proxy = true;

    app.use(cors({ credentials: true }));
    app.use(convert(Logger()))
    app.use(bodyParser())
    app.use(mount("/", convert(Serve(__dirname + '/../public/'))));

    app.keys = ['miaozhen-session-key'];
    app.use(convert(session()))

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

}
示例#12
0
文件: auth.js 项目: WizardL/Misato
export default function auth() {
  return compose([

    // session 
    convert(session({
      store: new mongoStore()
    })),

    // passport initialization
    passport.initialize(),

    // passport session initialization
    passport.session(),
    
  ])
}
示例#13
0
  /**
   * Use middlewares
   */
  use() {
    this.app.server
      .use(passport.initialize())
      .use(passport.session());

    let serializeUser = this.config.serializeUser;
    let deserializeUser = this.config.deserializeUser;

    if (typeof serializeUser == 'function') {
      passport.serializeUser(serializeUser);
    }
    
    if (typeof deserializeUser == 'function') {
      passport.deserializeUser(deserializeUser);
    }    
  }
示例#14
0
文件: index.js 项目: dayAlone/Knauf
export default function (app, models) {
    initStrategies(models)

    passport.serializeUser((user, done) => {
        done(null, user.id) // uses _id as idFieldd
    })
    passport.deserializeUser((id, done) => {
        //done(null, { id: 1, username: '******' })
        models.User.findById(id).then(data => {
            done(null, data)
        })
    })

    app
        .use(passport.initialize())
        .use(passport.session())
        .use(routes)
}
示例#15
0
module.exports = function (app) {
  /**
   * serialize user
   * @param  {object} user  [username and password]
   * @param  {fun}    done
   */
  passport.serializeUser(function (user, done) {
    done(null, user);
  });

  /**
   * deserialize user
   * @param  {object} user  [username and password]
   * @param  {fun}    done
   */
  passport.deserializeUser(function (user, done) {
    done(null, user);
  });

  /**
  *
  * @param  {string} username
  * @param  {string} password
  * @param  {fun}    done
  * @return {boolean}
  */
  passport.use(new LocalStrategy(function (username, password, done) {
    var userInp = { username: username, password: password };
    auth_model.getUser(userInp).then(function (user) {
      if (user.hasOwnProperty('err')) {
        return done(null, false, {message: user['err']});
      }
      return done(null, user);
    });
  }));

  /**
   * initializing passport authentication
   */
  app.use(passport.initialize());
  app.use(passport.session());
};
示例#16
0
module.exports = function(app) {
  // var env = app.get('env');

  app.use(views(config.root+'/server/views', {
    default: 'html'
  }));
  app.use(compression());
  app.use(bodyParser());
  app.use(methodOverride());
  app.use(passport.initialize());
  app.use(passport.session());

  app.keys = [config.secrets.session];
  app.use(session({
    store: mongoStore.create({
      mongoose: mongoose.connection
    })
  }));

  // if ('production' === env) {
  //   app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
  //   app.use(serve(path.join(config.root, 'public')));
  //   app.set('appPath', config.root + '/public');
  //   app.use(morgan('dev'));
  // }

  // if ('development' === env || 'test' === env) {
  //   app.use(require('connect-livereload')());
  //   app.use(serve(path.join(config.root, '.tmp')));
  //   app.use(serve(path.join(config.root, 'client')));
  //   app.set('appPath', 'client');
  //   app.use(morgan('dev'));
  //   app.use(errorHandler()); // Error handler - has to be last
  // }

  // app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
  app.use(require('koa-livereload')());
  app.use(serve(path.join(config.root, '.tmp')));
  app.use(serve(path.join(config.root, 'client')));
  app.use(logger());
  errorHandler(app); // Error handler - has to be last
};
示例#17
0
export function Setup (Server) {
  // TODO: actually serialize users
  Passport.serializeUser((user, done) => {
    done(null, user)
  })

  Passport.deserializeUser((user, done) => {
    done(null, user)
  })

  Passport.use(Github.Strategy)

  Server.use(Passport.initialize())
  Server.use(Passport.session())

  Server.use(async (ctx, next) => {
    ctx.state.user = (ctx.passport.user != null) ? ctx.passport.user : null
    ctx.user = (ctx.passport.user != null) ? ctx.passport.user : null
    await next()
  })

  Log.verbose('Passport Initalized')
}
示例#18
0
function Scaffold(configs) {

    var settings = _.extend(_.clone(defaults), configs || {});

    var devMode = true;
    if (settings.env === 'production') devMode = false;

    // find `views` and `public` abs path
    var dirs = {};
    dirs.views = finder(configs, 'views');
    dirs.uploads = finder(configs, 'uploads');

    var app = koa();

    app.db = monk(settings.database.name);
    app.keys = ['feedr session'];

    app.use(bodyParser());

    app.use(session(app));

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

    app.use(views(settings.views, settings.view_options));
    app.use(logger(devMode ? 'dev' : settings.logformat));
    app.use(router(app));
    if(Array.isArray(settings.publics)) {
        for(var i = 0; i < settings.publics.length; i++) {
            app.use(serve(settings.publics[i]));
        }
    }
    else {
        app.use(serve(settings.publics));
    }

    locale(app);

    // expose locals to template engine
    locals(app, {
        sys: pkg,
        site: settings
    });

    app.use(i18n(app, settings.i18n));

    //app.use(errors());

    app.use(function *(next) {
        try {
            yield next;
        } catch (err) {
            console.log(err);
            if(err.status === 401) {
                this.status = 401;
                this.set('WWW-Authenticate', 'Basic');
                this.body = 'Unauthorized request';
            }
            if(!err.status) {
                this.status = 500;
                yield this.render(settings.error['500']);
            }
            else {
                this.status = err.status;
            }
        }

        if(this.status === 200) {
            return;
        }

        if(!this.status) {
            this.status = 404;
        }

        if(this.status === 404) {
            yield this.render(settings.error['404']);
        }
        if(this.status === 500) {
            yield this.render(settings.error['500']);
        }
    });

    //setting language-cookie if f.e. ?lang=de is added to the url
    app.use(function * (next) {

        this.i18n.setLocaleFromQuery(this.request);
        yield next;

        var currentLocale = this.i18n.getLocale();
        this.cookies.set('lang', currentLocale, { signed: true });
    });

    // setup server settings
    var port = _.isNumber(settings.port) ? settings.port : defaults.port;

    this.app = app;
    this.port = port;

    return new Inner(app, port);
}
示例#19
0
module.exports = function(app) {

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

};
示例#20
0
"use strict";

const passport = require('koa-passport');
const config = require('config');
const User = require('../models/user');

function serialize (user, done) {
	// console.log('user before serialize:', user);
  done(null, user._id);
};

function  deserialize (id, done) {
  User.findById(id, done);
};

passport.serializeUser(serialize);
passport.deserializeUser(deserialize);

passport.use(require('./localStrategy'));
passport.use(require('./facebookStrategy'));
passport.use(require('./googleStrategy'));




module.exports = passport.initialize();
示例#21
0
文件: index.js 项目: nanek/Starboard
import passport from 'koa-passport';
import { wrap } from 'co';
import db from '../../../shared-backend/db';

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

passport.deserializeUser(wrap(function *(id, done) {
  try {
    const [user] = yield db('users').select('id').where({ id }).limit(1);

    if (!user) {
      done(null, false);
    } else {
      done(null, user);
    }
  } catch (err) {
    done(err);
  }
}));

const authInit = passport.initialize();
const authSession = passport.session();

export {
  authInit,
  authSession,
  passport,
};
示例#22
0
// passport.use(new TwitterStrategy({
//   consumerKey: 'your-consumer-key',
//   consumerSecret: 'your-secret',
//   callbackURL:
//     'http://localhost:' + (process.env.PORT || 3000) +
//     '/auth/twitter/callback'
// }, function(token, tokenSecret, profile, done) {
//   // retrieve user ...
//   done(null, user);
// }));

app.base.use(function* (next) {
  if (config.debug)
    logger.log('SESSION_ID', this.cookies.get('wall.id', true));

  // this.getSession = this.session;
  // this.session = yield this.session;
  this.req.session = yield this.session;

  yield next;
});

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

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

app.base.use(function* (next) {
  console.log('GOT HERE1', this.req.user);
  yield next;
});
示例#23
0
 attach(app) {
   // Authentication
   app.use(passport.initialize())
   app.use(passport.session())
 }
示例#24
0
function auth () {
  /**
   * Set up Metry Oauth authentification
   */

  passport.use('metry', new MetryOAuth({
    authorizationURL: url.resolve(process.env.METRY_ENDPOINT, '/oauth/authorize'),
    tokenURL: url.resolve(process.env.METRY_ENDPOINT, '/oauth/token'),
    clientID: process.env.METRY_CLIENT_ID,
    clientSecret: process.env.METRY_CLIENT_SECRET,
    callbackURL: url.resolve(process.env.BRFENERGI_SERVICE_URL, 'auth/callback'),
    scope: [ 'basic', 'add_to_open_channels', 'write_meter_location' ]
  }, (accessToken, refreshToken, profile, done) => {
    Users.model.findOne({ metryId: profile._id }, async (err, user) => {
      if (err) return done(err)

      try {
        // Add missing user
        if (!user) {
          user = await getLegacyUser(accessToken, profile)
          if (!user) {
            user = await addUser(accessToken, profile)
          }
        }

        // Touch account on forum - don't actually care about the response.
        try {
          let token = nodebb.authenticationToken(user)
          await got(process.env.FORUM_URL + '/auth/brf?brfauth=' + token)
          user.forumAuthenticationToken = token
        } catch (e) {
          Log.create({
            category: 'User',
            type: 'forum',
            data: 'Error while touching user forum account: ' + e
          })
        }

        await Cooperatives.sync(user.cooperative, accessToken)
      } catch (err) {
        return done(err)
      }

      user.refreshToken = refreshToken
      user.accessToken = accessToken
      user.save(done)
    })
  }))

  /**
   * Serialize user data by _id
   */

  passport.serializeUser((user, done) => done(null, user._id))
  passport.deserializeUser(function (id, done) {
    Users.get(id).then(function (user) {
      done(null, user)
    }, done)
  })

  return compose([cleanup, passport.initialize(), passport.session()])
}
示例#25
0
        yield next;
    } else {
        this.status = 401;
        this.body = {error: 'Not authorized'};
    }
}, api.routes(), api.allowedMethods());

export default [
    serve(__dirname + '/../public'),
    function*(next) {
        this.app.keys = ['superSecretKey12345'];
        yield next;
    },
    bodyParser(),
    session({
        store: new SessionStore(),
        cookie: {httpOnly: false}
    }),
    passport.initialize(),
    passport.session(),
    publicRoutes.middleware(),
    securedRoutes.middleware(),
    function*(next) {
        let store = this.state.store;
        // Populate user in the store
        store.dispatch({ type: 'USER', user: this.req.user });
        store.dispatch({ type: 'INCREMENT' });
        yield next;
    }
];
示例#26
0
export default function auth() {
    return compose([
        passport.initialize(),
        passport.session(),
    ]);
}
passport.deserializeUser((id, done) => {
    User.findById(id, done); // callback version checks id validity automatically
});

// done(null, user)
// OR
// done(null, false, { message: <error message> })  <- 3rd arg format is from built-in messages of strategies
passport.use(new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password'
    },
    function(email, password, done) {
        User.findOne({ email: email }, function (err, user) {
            if (err) {
                return done(err);
            }
            if (!user || !user.checkPassword(password)) {
                // don't say whether the user exists
                return done(null, false, { message: 'Нет такого пользователя или пароль неверен.' });
            }

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


const passportInitialize = passport.initialize();
module.exports = function() {
    return passport.initialize();
};
module.exports = function() {
    return passport.initialize();
};
示例#29
0
app.proxy = true

// sessions
const convert = require('koa-convert')
const session = require('koa-generic-session')
app.keys = ['your-session-secret']
app.use(convert(session()))

// body parser
const bodyParser = require('koa-bodyparser')
app.use(bodyParser())

// authentication
require('./auth')
const passport = require('koa-passport')
app.use(passport.initialize())
app.use(passport.session())

// routes
const fs    = require('fs')
const route = require('koa-route')

app.use(route.get('/', function(ctx) {
  ctx.type = 'html'
  ctx.body = fs.createReadStream('views/login.html')
}))

app.use(route.post('/custom', function(ctx, next) {
  return passport.authenticate('local', function(user, info, status) {
    if (user === false) {
      ctx.status = 401
示例#30
0
co(function* coWrapper() {
	require("./auth");

	const sessionStore = new RethinkSession({connection: r});
	yield sessionStore.setup();

	const app = new Koa();

	exports.app = app;

	app.proxy = true;

	app.use(bodyParser());

	app.keys = config.site.keys;

	app.use(session({
		store: sessionStore
	}));

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

	// statically serve assets
	app.use(serve("./assets"));

	app.use(hbs.middleware({
		viewPath: `${__dirname}/views`,
		layoutsPath: `${__dirname}/views/layouts`,
		partialsPath: `${__dirname}/views/partials`,
		defaultLayout: "main"
	}));

	app.use(function* appUse(next) {
		try {
			yield next;
		} catch (err) {
			if (this.state.api === true) {
				// if this was an API request, send the error back in a plain response
				this.app.emit("error", err, this);
				this.body = {error: true, message: String(err)};
			} else {
				// this wasn"t an API request, show the error page
				this.app.emit("error", err, this);
				yield this.render("error", {
					dump: err
				});
			}
		}
	});

	require("./routes");

	console.log(`${config.site.name} is now listening on port ${config.site.port}`);
	app.listen(config.site.port);

	if (process.env.NODE_ENV === "local") {
		// react stuff
		const webpack = require("webpack");
		const webpackConfig = require("./webpack.config.js");
		const WebpackDevServer = require("webpack-dev-server");

		// WEBPACK DEV SERVER
		new WebpackDevServer(webpack(webpackConfig), {
			"hot": true,
			"historyApiFallback": true,
			proxy: {
				"*": `http://localhost:${config.site.port}`
			},
			stats: "errors-only"
		}).listen(config.site.port + 1, "localhost", function webpackDevServer(err, result) {
			if (err) {
				console.error(err);
			}
			console.log(`Webpack Dev Server (Hot-Reload) listening on port ${config.site.port + 1}`);
		});
	}

	process.on("SIGINT", function end() {
		process.exit();
	});
});