-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
289 lines (247 loc) · 9.19 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
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
/**
* MODULE DEPENDENCIES
* -------------------------------------------------------------------------------------------------
* include any modules you will use through out the file
**/
const express = require('express')
, http = require('http')
, nconf = require('nconf')
, path = require('path')
, everyauth = require('everyauth')
, Recaptcha = require('recaptcha').Recaptcha
, mongoose = require('mongoose')
, moment = require('moment');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const flash = require('express-flash');
/**
* CONFIGURATION
* -------------------------------------------------------------------------------------------------
* load configuration settings from ENV, then settings.json. Contains keys for OAuth logins. See
* settings.example.json.
**/
nconf.env().file({ file: 'settings.json' });
mongoose.connect(nconf.get('mongodb'), { useMongoClient: true });
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
mongoose.connection.once('open', function() {
console.log('Connected to database');
});
/**
* EVERYAUTH AUTHENTICATION
* -------------------------------------------------------------------------------------------------
* allows users to log in and register using OAuth services
**/
everyauth.debug = true;
// Configure local password auth
var usersById = {},
nextUserId = 0,
usersByFacebookId = {},
usersByTwitId = {},
usersByLogin = {
'[email protected]': addUser({ email: '[email protected]', password: 'azure' })
};
everyauth.
everymodule.
findUserById(function (id, callback) {
callback(null, usersById[id]);
});
/**
* FACEBOOK AUTHENTICATION
* -------------------------------------------------------------------------------------------------
* uncomment this section if you want to enable facebook authentication. To use this, you will need
* to get a facebook application Id and Secret, and add those to settings.json. See:
* http://developers.facebook.com/
**/
//everyauth.
// facebook.
// appId(nconf.get('facebook:applicationId')).
// appSecret(nconf.get('facebook:applicationSecret')).
// findOrCreateUser(
// function (session, accessToken, accessTokenExtra, fbUserMetadata) {
// return usersByFacebookId[fbUserMetadata.claimedIdentifier] ||
// (usersByFacebookId[fbUserMetadata.claimedIdentifier] =
// addUser('facebook', fbUserMetadata));
// }).
// redirectPath('/');
/**
* TWITTER AUTHENTICATION
* -------------------------------------------------------------------------------------------------
* uncomment this section if you want to enable twitter authentication. To use this, you will need
* to get a twitter key and secret, and add those to settings.json. See:
* https://dev.twitter.com/
**/
//everyauth
// .twitter
// .consumerKey(nconf.get('twitter:consumerKey'))
// .consumerSecret(nconf.get('twitter:consumerSecret'))
// .findOrCreateUser(function (sess, accessToken, accessSecret, twitUser) {
// return usersByTwitId[twitUser.id] || (usersByTwitId[twitUser.id] = addUser('twitter', twitUser));
// })
// .redirectPath('/');
/**
* USERNAME & PASSWORD AUTHENTICATION
* -------------------------------------------------------------------------------------------------
* this section provides basic in-memory username and password authentication
**/
everyauth
.password
.loginWith('email')
.getLoginPath('/login')
.postLoginPath('/login')
.loginView('account/login')
.loginLocals(function (req, res, done) {
setTimeout(function () {
done(null, {
title: 'login. '
});
}, 200);
})
.authenticate(function (login, password) {
var errors = [];
if (!login) errors.push('Missing login');
if (!password) errors.push('Missing password');
if (errors.length) return errors;
var user = usersByLogin[login];
if (!user) return ['Login failed'];
if (user.password !== password) return ['Login failed'];
return user;
})
.getRegisterPath('/register')
.postRegisterPath('/register')
.registerView('account/register')
.registerLocals(function (req, res, done) {
setTimeout(function () {
done(null, {
title: 'Register. ',
recaptcha_form: (new Recaptcha(nconf.get('recaptcha:publicKey'), nconf.get('recaptcha:privateKey'))).toHTML()
});
}, 200);
})
.extractExtraRegistrationParams(function (req) {
return {
confirmPassword: req.body.confirmPassword,
data: {
remoteip: req.connection.remoteAddress,
challenge: req.body.recaptcha_challenge_field,
response: req.body.recaptcha_response_field
}
}
})
.validateRegistration(function (newUserAttrs, errors) {
var login = newUserAttrs.login;
var confirmPassword = newUserAttrs.confirmPassword;
if (!confirmPassword) errors.push('Missing password confirmation')
if (newUserAttrs.password != confirmPassword) errors.push('Passwords must match');
if (usersByLogin[login]) errors.push('Login already taken');
// validate the recaptcha
var recaptcha = new Recaptcha(nconf.get('recaptcha:publicKey'), nconf.get('recaptcha:privateKey'), newUserAttrs.data);
recaptcha.verify(function (success, error_code) {
if (!success) {
errors.push('Invalid recaptcha - please try again');
}
});
return errors;
})
.registerUser(function (newUserAttrs) {
var login = newUserAttrs[this.loginKey()];
return usersByLogin[login] = addUser(newUserAttrs);
})
.loginSuccessRedirect('/')
.registerSuccessRedirect('/');
// add a user to the in memory store of users. If you were looking to use a persistent store, this
// would be the place to start
function addUser(source, sourceUser) {
var user;
if (arguments.length === 1) {
user = sourceUser = source;
user.id = ++nextUserId;
return usersById[nextUserId] = user;
} else { // non-password-based
user = usersById[++nextUserId] = { id: nextUserId };
user[source] = sourceUser;
}
return user;
}
var app = express();
app.configure(function () {
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('azure zomg'));
// app.use(express.session());
app.use(session({
secret: 'secret key',
resave: true,
saveUninitialized: true,
cookie: { httpOnly: false },
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.use(flash());
app.use(everyauth.middleware(app));
app.use(app.router);
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));
});
app.locals.moment = moment;
app.configure('development', function () {
app.use(express.errorHandler());
});
/**
* ROUTING
* -------------------------------------------------------------------------------------------------
* include a route file for each major area of functionality in the site
**/
require('./routes/home')(app);
require('./routes/account')(app);
require('./routes/spotify')(app);
require('./routes/voting')(app);
require('./routes/admin')(app);
var server = http.createServer(app);
/**
* CHAT / SOCKET.IO
* -------------------------------------------------------------------------------------------------
* this shows a basic example of using socket.io to orchestrate chat
**/
// socket.io configuration
// var buffer = [];
// var io = require('socket.io').listen(server);
// io.configure(function () {
// io.set("transports", ["xhr-polling"]);
// io.set("polling duration", 100);
// });
// io.sockets.on('connection', function (socket) {
// socket.emit('messages', { buffer: buffer });
// socket.on('setname', function (name) {
// socket.set('name', name, function () {
// socket.broadcast.emit('announcement', { announcement: name + ' connected' });
// });
// });
// socket.on('message', function (message) {
// socket.get('name', function (err, name) {
// var msg = { message: [name, message] };
// buffer.push(msg);
// if (buffer.length > 15) buffer.shift();
// socket.broadcast.emit('message', msg);
// })
// });
// socket.on('disconnect', function () {
// socket.get('name', function (err, name) {
// socket.broadcast.emit('announcement', { announcement: name + ' disconnected' });
// })
// })
// });
/**
* RUN
* -------------------------------------------------------------------------------------------------
* this starts up the server on the given port
**/
server.listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
require('./crons/volume');
require('./crons/track');
require('./crons/token');
});