index.js 2.23 KB
/**
 * web ui 模块
 * 
 * @author: jiang
 */
'use strict';
const path = require('path');
const json = require('koa-json')
const Koa = require('koa');

const hbs = require('../../middleware/yoho-koa-hbs');
const helpers = require('../../lib/helpers');
const routers = require('./routers');
const collectData = require('./actions/collect_data');
const profile = require('./actions/profile');
const redis = require('../../lib/redis');

const {
    normalMenus,
    masterMenus,
    businessMenus
} = require('../../config/menus');

const app = new Koa();

app.use(json());

app.use(hbs({
    views: path.join(__dirname, '/views'),
    defaultLayout: 'layout',
    helpers: helpers
}));

const mastersUrl = [
    '/projects/new',
    '/projects/edit',
    '/projects/save',
    '/projects/build',
    '/projects/deploy',
    '/servers',
    '/users'
];

// 日常规则检查
// profile.report();

// 服务器监控数据采集
// collectData.collect();


app.use(async(ctx, next) => {
    ctx.redis = redis.client;

    ctx.locals = {
        title: 'Yoho Node.js 持续集成平台'
    };
    let pjax = ctx.request.get('X-PJAX');
    if (pjax) {
        ctx.locals.layout = null;
    }

    if (ctx.session && ctx.session.user) {
        ctx.locals.is_master = ctx.session.user.role === '1000';
        ctx.locals.is_dev = ctx.session.user.role === '2000';
        ctx.locals.not_business = ctx.session.user.role !== '3000';
        ctx.locals.is_business = ctx.session.user.role === '3000';
        ctx.locals.current_user = ctx.session.user;
    }

    ctx.locals.normalMenus = normalMenus;
    ctx.locals.masterMenus = masterMenus;
    ctx.locals.businessMenus = businessMenus;

    let needMaster = mastersUrl.some(u => {
        return ctx.request.path.indexOf(u) === 0;
    });

    if (needMaster) {
        if (ctx.locals.is_master) {
            await next();
        }
    } else {
        await next();
    }
    // if (pjax && ctx.status == 301) {
    //     let location = ctx.response.get('Location');
    //     ctx.response.set('X-PJAX-URL', ctx.origin + location);
    // }
    ctx.response.set('Cache-Control', 'no-cache, no-store');
    ctx.response.set('Pragma', 'no-cache')
    ctx.response.set('X-PJAX-URL', ctx.href);
});

routers(app);


module.exports = app;