-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
executable file
Β·255 lines (215 loc) Β· 5.97 KB
/
app.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
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
// Configuration
var tori = require('./conf/tori.conf.js');
// Express
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var app = express();
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(session({
secret: tori.core.secret,
resave: true,
saveUninitialized: true
}));
app.use(express.static(path.join(__dirname, 'public')));
// Api Routes
var userApi = require('./routes/api/user');
var permissionApi = require('./routes/api/permission');
var actionApi = require('./routes/api/action');
var roleApi = require('./routes/api/role');
// π Authentication
var jwt = require('jsonwebtoken');
var passport = require('passport');
var localStrategy = require('passport-local').Strategy;
var tokenStrategy = require('passport-token').Strategy;
var account = require('./models/account');
/// local mongoose strategy
passport.use(account.createStrategy());
passport.serializeUser(account.serializeUser());
passport.deserializeUser(account.deserializeUser());
/// token strategy
function tokenAuth(req, res, next) {
// get the token
var token = req.headers['x-access-token'];
// get username
var username = req.headers['x-access-username'];
// if username is missing
if (!username) {
return res.status(403).send({
success: false,
message: 'Missing username.'
});
}
// if token exists, and has at least a char
if (token && token.length > 1) {
jwt.verify(token, tori.core.secret, function(err, decoded) {
if (err) {
return res.status(401).json({
success: false,
message: err.message
});
} else {
// retrieve current user
account.findOne({
username: username,
token: token
}).exec(function(err, user) { // mongoose.lean() transform the Model to Object
if (err) {
return res.status(401).json({
success: false,
message: 'Invalid username.'
});
} else {
if (user) {
req.user = user
next();
} else {
return res.status(401).json({
success: false,
message: 'Invalid token.'
});
}
}
});
}
})
} else {
return res.status(403).send({
success: false,
message: 'Missing token.'
});
}
}
app.use(passport.initialize());
app.use(passport.session());
/// π Database setup
var mongoClient = require('mongodb').MongoClient;
var mongoose = require('mongoose');
var database = null;
app.use(function(req, res, next) {
if (database) {
req.db = database;
next();
} else {
mongoClient.connect('mongodb://' + tori.database.host + '/' + tori.database.data, function(err, db) {
if (db) {
req.db = database = db;
next();
} else {
console.error('β π Database connection problem');
process.exit();
}
});
}
});
mongoose.connect('mongodb://' + tori.database.host + '/' + tori.database.user);
/// π¨ Email
var nodemailer = require('nodemailer');
var transport = null;
if (tori.mail.service == 'smtp') {
transport = require('nodemailer-smtp-transport');
} else {
transport = require('nodemailer-sendmail-transport');
}
if (transport == null) {
console.error('β π¨ Mail transport not setup, please check your configuration file');
process.exit();
}
var mail = null;
app.use(function(req, res, next) {
if (mail) {
req.mail = mail;
next();
} else {
var emailSetup = {};
// check if smtp is supported
if (tori.mail.smtp.host != null) {
emailSetup = tori.mail.smtp;
}
req.mail = mail = nodemailer.createTransport(transport(emailSetup));
next();
}
});
/// Routing
app.get('/', function(req, res) {
res.redirect('/authenticate/login');
});
// remove those
//app.all('/collection/*', tokenAuth);
//app.all('/user/*', tokenAuth);
//app.all('/role/*', tokenAuth);
//app.all('/action/*', tokenAuth);
/*app.all('/admin/*', function (req, res, next){
// checks if user is logged
if(req.user){
return next();
}else{
res.redirect('/authenticate/login');
}
});*/
function isAdmin(req, res, next) {
if (req.user.isAdmin == false) {
return res.status().json({
success: false,
message: 'User has no permission.'
});
}
next();
}
/// Setup Routes
// User
app.post('/api/user/login', passport.authenticate('local'));
app.get('/api/user/logout', tokenAuth);
app.get('/api/user/remove', tokenAuth);
app.get('/api/user/list', tokenAuth);
app.get('/api/user/profile', tokenAuth);
app.put('/api/user/update*', tokenAuth);
app.use('/api/user', userApi);
// Permission
app.all('/api/permission', tokenAuth);
app.use('/api/permission', permissionApi);
// Action
app.all('/api/action*', tokenAuth, isAdmin);
app.use('/api/action', actionApi);
// Role
app.all('/api/role*', tokenAuth, isAdmin);
app.use('/api/role', roleApi);
/// Error handlers
if (app.get('env') === 'development') {
// development error handler, will print stacktrace
app.use(function(err, req, res, next) {
res.status(err.status || 500);
console.log(err.message);
res.render('error', {
message: err.message,
success: false
});
});
}
// production error handler, no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
success: false
});
});
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
module.exports = app;