-
Notifications
You must be signed in to change notification settings - Fork 0
/
app_router.js
113 lines (90 loc) · 2.82 KB
/
app_router.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/**
* Roteamentos da aplicação
*/
var router = require('koa-router')()
, fs = require('fs-extra')
, extend = require('extend')
, cookies = require('tshark/cookie')
, reload = require('require-reload')(require)
;
//region :: Home page
router.get('/', function *(next) {
// Renderiza index
this.body = yield this.app.engine.render('index', this);
// this.body = 'Acesso negado';
});
/**
* Clientes sem filial
*/
router.get(/^\/(\w+)$/, function *(next) {
yield initCliente(this);
});
/**
* Clientes com filial
*/
router.get(/^\/(\w+)\/(\w+)$/, function *(next) {
yield initCliente(this);
});
/**
* Inicializa um cliente na primeira carga
* e seta os cookies necessários para a utilização
* do aplicativo
* @param ctx
*/
function *initCliente(ctx){
var path = 'apps' + ctx.originalUrl + '/'
, engine = ctx.app.engine
, clientes = ctx.app.context.clientes
, app = ctx.captures[0]
;
// Registra o contexto do cliente
var novo = engine.assurePath(clientes, ctx.captures, {
_log: {
_last_access : '',
_logged_users : { }
},
app: ctx.captures,
flowPaths: {
up: [
global.appRoot + '/apps/' + ctx.captures.join('/') + '/',
global.appRoot + '/apps/' + ctx.captures[0] + '/_common/',
global.appRoot + '/_common/'
],
down: [
global.appRoot + '/_common/',
global.appRoot + '/apps/' + ctx.captures[0] + '/_common/',
global.appRoot + '/apps/' + ctx.captures.join('/') + '/'
]
}
});
// Seta o config no request para o cliente atual
ctx.state.config = engine.getObjPath(clientes, ctx.captures);
// limpa cache de config
ctx.state.config.flowPaths.down.forEach((path) => {
if (fs.existsSync(path + '/config.js')) {
// delete require.cache[require.resolve(path + '/config.js')];
extend(true, ctx.state.config, reload(path + '/config.js') || {});
}
});
// Verifica o usuário logado
var user_key = cookies.getLoggedUser(ctx, ctx.captures.join('/'));
if (!user_key){
// Verifica segurança
if (ctx.state.config.security.active){
ctx.body = yield engine.render('login', ctx);
// Seta aleatório
} else {
user_key = cookies.setLoggedUser(ctx, ctx.captures.join('/'));
}
}
if (user_key){
// Registra running
if (!ctx.app.context.running[user_key]) {
ctx.app.context.running[user_key] = ctx.state.config;
}
// Renderiza index
ctx.body = yield engine.render('index', ctx);
}
}
//endregion
module.exports = router;