index.js 1.36 KB
/**
 * web ui 模块
 * 
 * @author: jiang
 */

import path from 'path';
import Koa from 'koa';

import hbs from '../../middleware/yoho-koa-hbs';
import helpers from '../../lib/helpers';
import routers from './routers'

const app = new Koa();

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'
];

app.use(async(ctx, next) => {
    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.current_user = ctx.session.user;
    }

    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('X-PJAX-URL', ctx.href);
});

routers(app);


export default app;