-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.ts
More file actions
465 lines (378 loc) · 13.6 KB
/
app.ts
File metadata and controls
465 lines (378 loc) · 13.6 KB
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/**!
* Copyright (c) 2016 7thCode.(http://seventh-code.com/)
* This software is released under the MIT License.
* //opensource.org/licenses/mit-license.php
*/
"use strict";
//require('sqreen');
import * as express from 'express';
import * as fs from "graceful-fs";
import * as morgan from "morgan";
import * as mongoose from "mongoose";
import * as passport from "passport";
import * as cookieParser from "cookie-parser";
import * as bodyParser from "body-parser";
import * as helmet from "helmet";
import * as session from "express-session";
import * as log4js from 'log4js';
import * as rotatestream from 'logrotate-stream';
import * as _config from'config';
import * as LocalStrategyModule from "passport-local";
import * as FacebookStrategyModule from "passport-facebook";
import * as TwitterStrategyModule from "passport-twitter";
import * as InstagramStrategyModule from "passport-instagram";
import * as LineStrategyModule from "passport-line";
import * as Scheduler from "./server/systems/common/scheduler";
import * as Unix from "./server/systems/common/commandar";
import * as Cipher from "./server/systems/common/cipher";
import * as Event from "./server/systems/common/event";
import * as IO from'./server/systems/common/sio';
import * as LocalAccount from "./models/systems/accounts/account";
import * as Auth from "./server/systems/auth/controllers/auth_controller";
let normal = () => {
morgan.format("original", "[:date] :method :url :status :response-time ms");
mongoose.Promise = global.Promise;
console.log("LC_CTYPE : " + process.env.LC_CTYPE);
console.log("PWD : " + process.env.PWD);
console.log("HOME : " + process.env.HOME);
console.log("Hundred.");
const app: any = express();
// helmet
app.use(helmet());
app.use(helmet.hidePoweredBy({setTo: "JSF/1.2"})); // impersonation
const config: any = _config.get("systems");
//const config: any = require('config').get("systems");
const TCipher: any = Cipher;
const cipher: any = new TCipher();
const TEvent: any = Event;
const event: any = new TEvent();
// view engine setup
app.set('views', './views');
app.set('view engine', 'pug');
// result settings
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(cookieParser());
// logs
log4js.configure("./config/systems/logs.json");
const logger: any = log4js.getLogger('request');
if (config.status !== 'production') {
app.use(morgan('original', {immediate: true}));
} else {
app.use(morgan('combined', {
stream: rotatestream({
file: __dirname + '/logs/access.log',
size: '100k',
keep: 3
})
}));
}
app.use(express.static('./public'));
app.use('/scripts', express.static('./node_modules'));
let definition = JSON.parse(fs.readFileSync('./models/systems/accounts/definition.json', 'utf-8'));
// database
const MongoStore = require('connect-mongo')(session);
const options = {keepAlive: 1, connectTimeoutMS: 1000000, reconnectTries: 30, reconnectInterval: 2000, useNewUrlParser: true};
let connect_url = "mongodb://" + config.db.user + ":" + config.db.password + "@" + config.db.address + "/" + config.db.name;
if (config.db.noauth) {
connect_url = "mongodb://" + config.db.address + "/" + config.db.name;
}
mongoose.connect(connect_url, options)
.catch(error => {
console.log('catch Mongoose exeption. ');
logger.fatal('catch Mongoose exeption. ', error.stack);
process.exit(1);
});
mongoose.connection.once('open', () => {
mongoose.connection.on('connected', () => {
logger.fatal('connected');
});
mongoose.connection.on('disconnected', () => {
console.log('Mongoose default connection disconnected');
logger.fatal('Mongoose default connection disconnected');
process.exit(1);
});
mongoose.connection.on('reconnected', () => {
logger.fatal('reconnected');
});
mongoose.connection.on('error', (error) => {
console.log('Mongoose default connection error');
logger.fatal('Mongoose default connection error: ' + error);
process.exit(1);
});
let sessionMiddleware = session({
name: config.sessionname,
secret: config.sessionsecret,
resave: false,
rolling: true,
saveUninitialized: true,
cookie: {
maxAge: 365 * 24 * 60 * 60 * 1000
},
store: new MongoStore({
mongooseConnection: mongoose.connection,
ttl: 365 * 24 * 60 * 60,
clear_interval: 60 * 60
})
});
app.session = sessionMiddleware;
app.use(sessionMiddleware);
// passport
app.use(passport.initialize());
app.use(passport.session());
// passport
let load_root_module: any = (root: string, modules: any): void => {
if (modules) {
modules.forEach((module) => {
let path = root + module.path;
let name = module.name;
app.use("/", require(path + name + "/api"));
app.use("/", require(path + name + "/pages"));
});
}
};
let load_module: any = (root: string, modules: any): void => {
if (modules) {
modules.forEach((module) => {
let path = root + module.path;
let name = module.name;
app.use("/" + name, require(path + name + "/api"));
app.use("/" + name, require(path + name + "/pages"));
});
}
};
console.log("V1");
let modules = [
{
"type": "required",
"path": "/systems/",
"name": "auth",
"description": {}
},
{
"type": "required",
"path": "/systems/",
"name": "accounts",
"description": {}
},
{
"type": "required",
"path": "/systems/",
"name": "publickey",
"description": {}
},
{
"type": "required",
"path": "/systems/",
"name": "session",
"description": {}
},
{
"type": "required",
"path": "/systems/",
"name": "profile",
"description": {
"display": "Profile"
}
}
];
load_module("./server", modules);
load_module("./server", config.plugin_modules);
load_root_module("./server", config.root_modules);
console.log("VR");
// backup
const TScheduler: any = Scheduler;
const scheduler = new TScheduler();
const TUnix: any = Unix;
const command = new TUnix();
if (config.db.backup) {
scheduler.Add({
timing: config.db.backup, name: "backup", job: () => {
command.Backup(config.db);
}
});
}
const LocalStrategy: any = LocalStrategyModule.Strategy;
const FacebookStrategy: any = FacebookStrategyModule.Strategy;
const TwitterStrategy: any = TwitterStrategyModule.Strategy;
const InstagramStrategy: any = InstagramStrategyModule.Strategy;
const LineStrategy: any = LineStrategyModule.Strategy;
passport.use(new LocalStrategy(LocalAccount.authenticate()));
passport.serializeUser((user: any, done): void => {
switch (user.provider) {
case "facebook":
case "twitter":
case "instagram":
case "googleplus":
case "line":
let objectid: any = new mongoose.Types.ObjectId; // Create new id
user.username = user.id;
user.groupid = user.id;
user.userid = user.id;
user.enabled = true;
user.passphrase = objectid.toString();
user.publickey = cipher.PublicKey(user.passphrase);
user.local = definition.account_content;
break;
case "local":
break;
default:
}
done(null, user);
});
passport.deserializeUser((obj, done): void => {
done(null, obj);
});
// OAuth
if (config.facebook) {
passport.use(new FacebookStrategy(config.facebook.key, (accessToken, refreshToken, profile, done): void => {
process.nextTick((): void => {
done(null, profile);
});
}
));
}
if (config.twitter) {
passport.use(new TwitterStrategy(config.twitter.key, (accessToken, refreshToken, profile, done): void => {
process.nextTick((): void => {
done(null, profile);
});
}
));
}
if (config.instagram) {
passport.use(new InstagramStrategy(config.instagram.key, (accessToken, refreshToken, profile, done): void => {
process.nextTick((): void => {
done(null, profile);
});
}
));
}
if (config.line) {
passport.use(new LineStrategy(config.line.key, (accessToken, refreshToken, profile, done): void => {
process.nextTick((): void => {
done(null, profile);
});
}
));
}
// passport
const TAuth: any = Auth;
const auth = new TAuth();
auth.create_init_user(config.initusers);
let server: any = Serve(config, app);
let TIO:any = IO;
let io = new TIO(server);
io.wait(config, event);
// error handlers
app.use((req, res, next): void => {
let err: any = new Error('Not Found');
err.status = 404;
next(err);
});
if (app.get('env') === 'development') {
app.use((err, req, res, next): void => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
status: err.status
});
});
}
app.use((err, req, res, next): void => {
if (req.xhr) {
res.status(500).send(err);
} else {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
}
});
});
// database
event.emitter.on('socket', (data): void => {
});
event.emitter.on('mail', (mail): void => {
});
process.on('SIGINT', (): void => { // for pm2 cluster.
mongoose.connection.close(() => {
logger.info('Stop by SIGINT.');
process.exit(0);
});
});
process.on('message', (msg): void => { // for pm2 cluster on windows.
if (msg == 'shutdown') {
logger.info('Stop by shutdown.');
setTimeout(function () {
process.exit(0);
}, 1500);
}
});
};
let Serve = (config: any, app: any): any => {
// let debug = require('debug')('a:server');
function normalizePort(val) {
let port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
let bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
function onListening() {
let addr = server.address();
let bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
// debug('Listening on ' + bind);
process.send = process.send || function () {
}; // for pm2 cluster.
process.send('ready');
}
let port = normalizePort(process.env.PORT || config.port);
app.set('port', port);
let server: any = null;
if (config.ssl) {
let ssl: { key: string, cert: string } = config.ssl;
let http = require('spdy');
server = http.createServer({
key: fs.readFileSync(ssl.key),
cert: fs.readFileSync(ssl.cert),
}, app);
} else {
let http = require('http');
server = http.createServer(app);
}
server.on('error', onError);
server.on('listening', onListening);
server.listen(port, '::0');
console.log("V2");
return server;
};
normal();