UNPKG

warrior-code-api

Version:
69 lines (53 loc) 1.98 kB
'use strict'; const fs = require('fs'); const Hapi = require('hapi'); const Promise = require('bluebird'); const mongoose = require('mongoose'); const config = require('config'); const server = new Hapi.Server(); // Initialize the connection to MongoDB. mongoose.connect(`${config.get('MongoDB.uri')}/${config.get('MongoDB.dbName')}`); console.log(`Database running at: ${config.get('MongoDB.uri')}/${config.get('MongoDB.dbName')}`); // Load all the models. let models = fs.readdirSync(`${__dirname}/models`); for (let model of models) { require(`${__dirname}/models/${model}`); } // Specify the connection. server.connection({ host: config.get('Server.host'), port: process.env.PORT || config.get('Server.port') }); server.register([require('bell'), require('hapi-auth-jwt')], (err) => { // Register the authentication strategy. server.auth.strategy('github', 'bell', { provider: 'github', password: config.get('Secrets.GitHub.password'), clientId: config.get('Secrets.GitHub.clientId'), clientSecret: config.get('Secrets.GitHub.clientSecret'), isSecure: false }); server.auth.strategy('token', 'jwt', { key: config.get('Secrets.JWT.privateKey'), validateFunc: (req, decodedToken, callback) => { // Return false if there is no token. if (!decodedToken) { return callback(null, false); } // Check if the token is valid. let isValidToken = mongoose.Types.ObjectId.isValid(decodedToken._id); // Get the authenticated user. mongoose.models.User.findById(decodedToken._id, (err, user) => { // Execute the callback passing the parsed user. callback(null, isValidToken, user); }); } }); // Register all the routes. require('./routes').forEach((route) => server.route(route)); // Start the server. server.start((err) => { if (err) throw err; console.log(`Server running at: http://${server.info.host}:${server.info.port}`); }); });