-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathyote.js
More file actions
232 lines (201 loc) · 7.79 KB
/
yote.js
File metadata and controls
232 lines (201 loc) · 7.79 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
/*
••••••••••••••••••••••••••••••••••••••••••••••••••
Welcome to Yote. We hope you like it.
- Fugitive Labs
••••••••••••••••••••••••••••••••••••••••••••••••••
*/
var express = require('express')
, compress = require('compression')
, bodyParser = require('body-parser')
, cookieParser = require('cookie-parser')
, serveStatic = require('serve-static')
, winston = require('winston')
, session = require('express-session')
, favicon = require('serve-favicon')
, timeout = require('connect-timeout')
, errorHandler = require('errorhandler')
, mongoose = require('mongoose')
, passport = require('passport')
, LocalStrategy = require('passport-local').Strategy
, path = require('path')
// , RedisStore = require('connect-redis')(session) //no longer used
, MongoStore = require('connect-mongo')(session)
, fs = require('fs')
// , sass = require('node-sass-middleware') //no longer used
;
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
var config = require('./server/config')[env];
//initialize logger
// generally global is not considered "best practices", but this will allow access to the logger object in the entire app
global.logger = require('./logger');
// LOG EXAMPLES:
logger.debug("DEBUG LOG");
logger.info("INFO LOG");
logger.warn("WARN LOG");
logger.error("ERROR LOG");
//initialize database
require('./server/db')(config);
//init User model
var UserSchema = require('./server/models/User').User
, User = mongoose.model('User')
//use express compression plugin
app.use(compress());
//configure express
app.set('views', __dirname + '/server/views');
app.set('view engine', 'pug');
app.use(timeout(30000)); //upper bound on server connections, in ms.
// app.use(logger('dev'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// mongoose.connect(config.db);
app.use(session({
//TODO: configure mongo to use the same database connection
store: new MongoStore({mongooseConnection: mongoose.connection})
, secret: config.secrets.sessionSecret
}));
// app.use(favicon(path.join(__dirname, 'public','favicon.ico')));
app.use(passport.initialize());
app.use(passport.session());
//allow file uploads
// app.use(multipart({}));
//sass middleware
//only enable for development env - npm module can be buggy
//NOW rendered via webpack only on changes
// if (app.get('env') == 'development') {
// console.log("using sass");
// console.log(__dirname);
// app.use(sass({
// src: __dirname + '/client'
// , dest: __dirname + '/public/css'
// , prefix: '/css'
// , debug: true
// , outputStyle: 'compressed'
// , includePaths: ['/client/global/sass/', '/client/modules/', '/client/static']
// }));
// }
//serve static assets, incl. react bundle.js
app.use(serveStatic(__dirname + '/public'));
//request checks
app.use(function(req, res, next) {
//to allow CORS access to the node APIs, follow these steps:
// 1. know what you are doing.
// 2. uncommente the following 3 lines.
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, token");
// ref https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
//test user:
logger.info("YOTE USER: " + (req.user ? req.user.username : "none"));
//no mongo connection
if(mongoose.connection.readyState !== 1) {
mongoose.connect(config.db);
res.send("mongoose error, hold your horses...");
}
//check for OPTIONS method
if(req.method == 'OPTIONS') {
res.send(200);
} else {
next();
}
});
//initialize passport
passport.use('local', new LocalStrategy(
function(username, password, done) {
var projection = {
username: 1, password_salt: 1, password_hash: 1, roles: 1
}
User.findOne({username:username}, projection).exec(function(err, user) {
if(user && user.authenticate(password)) {
logger.debug("authenticated!");
return done(null, user);
} else {
logger.debug("NOT authenticated");
return done(null, false);
}
})
}
));
passport.serializeUser(function(user, done) {
logger.warn("SERIALIZE USER");
if(user) {
done(null, user._id);
}
});
passport.deserializeUser(function(id, done) {
logger.warn("DESERIALIZE USER");
//we want mobile user to have access to their api token, but we don't want it to be select: true
User.findOne({_id:id}).exec(function(err, user) {
if(user) {
return done(null, user);
} else {
return done(null, false);
}
})
})
// development only
if (app.get('env') == 'development') {
logger.debug("DEVELOPMENT");
// app.use(errorHandler());
} else if(app.get('env') == 'production') {
logger.debug("PRODUCTION");
//log express http requests in production. way to much in dev.
app.use(require('morgan')({"stream":logger.stream}));
}
//configure server routes
var router = express.Router();
// require('./server/routes/api-routes')(router);
require('./server/router/server-router')(router, app);
//some notes on router: http://scotch.io/tutorials/javascript/learn-to-use-the-new-router-in-expressjs-4
app.use('/', router);
//check for the server timeout. must be last in the middleware stack
app.use(haltOnTimedout);
function haltOnTimedout(req, res, next){
//http://stackoverflow.com/questions/21708208/express-js-response-timeout
if (!req.timedout) next();
}
//SSL
//Yote comes out of the box with https support! Check the readme for instructions on how to use.
var useHttps = false;
var httpsOptional = false;
if(app.get('env') == 'production' && useHttps) {
logger.info("starting production server WITH ssl");
require('https').createServer({
key: fs.readFileSync('../projectName/ssl/yourSsl.key') //so it works on server and local
, cert: fs.readFileSync('../projectName/ssl/yourCertFile.crt')
, ca: [fs.readFileSync('../projectName/ssl/yourCaFile.crt')] // godaddy splits certs into two
// this should all be taken care of by default in Node v4.
// //disallow ciphers that have security flaws
// , honorCipherOrder: true
// , ciphers: 'ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:AES128-GCM-SHA256:!RC4:HIGH:!MD5:!aNULL'
// //https://nodejs.org/docs/latest/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
// //https://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT
// //https://sites.google.com/site/jimmyxu101/testing/openssl
// }, app).listen(9191);
}, app).listen(443);
//need to catch for all http requests and redirect to httpS
var http = require('http');
if(httpsOptional) {
require('http').createServer(app).listen(80);
} else {
require('http').createServer(function(req, res) {
logger.info("REDIRECTING TO HTTPS");
res.writeHead(302, {
'Location': 'https://YOUR-URL.com:443' + req.url
// 'Location': 'https://localhost:9191' + req.url
});
res.end();
// }).listen(3030);
}).listen(80);
}
logger.info('Yote is listening on port ' + 80 + ' and ' + 443 + '...');
} else if(app.get('env') == 'production') {
logger.info("starting yote production server WITHOUT ssl");
require('http').createServer(app).listen(config.port);
logger.info('Yote is listening on port ' + config.port + '...');
} else {
logger.info("starting yote dev server");
require('http').createServer(app).listen(config.port);
logger.info('Yote is listening on port ' + config.port + '...');
}