index.js 1.69 KB
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const sessions = require("client-sessions");
const querystring = require('querystring');
const render = require('./render');
const config = require('../config/common');

global.config = config;
global.utilPath = path.join(__dirname, '../utils');

global.auth = (req, res, next) => {
    if (!req.session.user) {
        if (req.xhr) {
            res.json({
                code: 401,
                message: '抱歉,您暂未登录!'
            });
            return false;
        }

        res.redirect(`/login.html?${querystring.stringify({ refer: req.originalUrl})}`);
        return false;
    }

    next && next();
    return true;
};

exports.createServer = async() => {
    const app = express();

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(cookieParser());

    app.use(express.static(path.join(__dirname, '../dist')));

    app.use(sessions({
        requestKey: 'session',
        cookieName: 'ufo_stats_session',
        secret: 'yoho_ufo_stats_9646',
        duration: 24 * 60 * 60 * 1000,
        activeDuration: 1000 * 60 * 5
    }));

    // dispatcher
    try {
        require('./dispatch')(app);

        app.all('*', render);

        // 后置中间件
        app.use((err, req, res, next) => {
            console.log(err)
            return res.status(500).end();
        });
    } catch (err) {
        console.error(err);
    }

    // listener
    app.listen(config.port, function () {
        console.log('Project server listening on port ' + config.port);
    });
};