-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js~
195 lines (165 loc) · 5.15 KB
/
server.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
#!/usr/bin/env node
// Requires {{{
var colors = require('colors');
var bodyParser = require('body-parser');
var express = require('express');
var layouts = require('express-ejs-layouts')
var fspath = require('path');
var fs = require('fs');
var multer = require('multer');
//var done = false;
global.app = express();
// }}}
// Global functions {{{
var requireTree = function(dir) {
dir = fspath.join(__dirname, dir);
fs.readdirSync(dir).forEach(function (file) {
if (/(.*)\.js$/.test(file))
require(fspath.join(dir, file));
});
}
// }}}
// Settings {{{
global.config = require('./config');
require('./config/db');
app.set('title', 'Stem');
app.set('view engine', "html");
app.set('layout', 'layouts/main');
app.engine('.html', require('ejs').renderFile);
app.enable('view cache');
app.use(layouts);
app.use(require('connect-flash')());
// }}}
// Settings / Basic Auth (DEBUGGING) {{{
// app.use(express.basicAuth('user', 'letmein'));
// }}}
// Settings / Parsing {{{
app.use(require('cookie-parser')());
app.use(bodyParser.json());//?????
app.use(bodyParser.urlencoded({extended: false}));//????
/*app.use(multer({ dest: './uploads/',
rename: function (fieldname, filename) {
return filename+Date.now();
},
onFileUploadStart: function (file) {
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
done=true;
//test, access database
}
}));
app.get('./views/partials/users/addOrder.html',function(req,res){
res.sendfile("./views/partials/users/addOrder.html");
});
app.post('/api/photo/',function(req,res){
if(done==true){
console.log(req.files);
//res.end("File uploaded.");
res.redirect("back");
//res.redirect("localhost:4000/#/users/orders");????
}
});*/
// }}}
// Settings / Cookies + Sessions {{{
var session = require('express-session');
var mongoStore = require('connect-mongo')(session);
app.use(session({
secret: config.secret,
store: new mongoStore({db: mongoose.connections[0].db}),
resave: false,
saveUninitialized: false,
cookie: {
expires: new Date(Date.now() + (3600000 * 48)), // 48 hours
maxAge: (3600000 * 48) // 48 hours
}
}));
// }}}
// Settings / Passport {{{
global.passport = require('passport');//?????
var passportLocalStrategy = require('passport-local').Strategy;
var Users = new require('./models/users'); //require is for loading a module in nodejs
passport.use(new passportLocalStrategy({
passReqToCallback: true
}, function(req, username, password, next) {
Users.findByLogin(req, username, password, next); // Delegate to the user model
}));
passport.serializeUser(function(user, next) {
// console.log('SERIAL', user);
next(null, user.username);
});
passport.deserializeUser(function(id, next) {
Users
.findOne({username: id})
.exec(function(err, user) {
return next(err, user);
});
});
// Various security blocks
global.ensure = {
loginFail: function(req, res, next) { // Special handler to reject login and redirect to login screen or raise error depending on context
console.log(colors.red('DENIED'), colors.cyan(req.url));
// Failed login - decide how to return
res.format({
'application/json': function() {
res.status(401).send({err: "Not logged in"}).end();
},
'default': function() {
res.redirect('/login');
},
});
},
login: function(req, res, next) {
if (req.user && req.user._id) { // Check standard passport auth (inc. cookies)
return next();
} else if (req.body.token) { // Token has been provided
Users.findOne({'auth.tokens.token': req.body.token}, function(err, user) {
if (err || !user) return ensure.loginFail(req, res, next);
console.log('Accepted auth token', colors.cyan(req.body.token));
req.user = user;
next();
});
} else { // Not logged in and no method being passed to handle - reject
ensure.loginFail(req, res, next);
}
}
};
app.use(passport.initialize());
app.use(passport.session());
// }}}
// Settings / Restify {{{
global.restify = require('express-restify-mongoose');
restify.defaults({
private: '__v', // CSV of protected properties
version: ''
});
// }}}
// Settings / Logging {{{
var expressLog = require('express-log');
app.use(expressLog());
// }}}
// Controllers {{{
requireTree('controllers');
// }}}
// Static pages {{{
app.use(express.static(__dirname + '/public'));
app.use('/app', express.static(__dirname + '/app'));
app.use('/build', express.static(__dirname + '/build'));
app.use('/data', express.static(__dirname + '/data'));
app.use('/partials', express.static(__dirname + '/views/partials'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use('/uploads', express.static(__dirname + '/uploads'));//!important:to turn off the url hash and can directly use the uploads folder
app.use('/api/email', express.static(__dirname + '/api/email'));
// }}}
// Error catcher {{{
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!').end();
});
// }}}
// Init {{{
var server = app.listen(config.port, config.host, function() {
console.log('Web interface listening on ' + ((config.host || 'localhost') + ':' + config.port).cyan);
});
// }}}