forked from rdegges/svcc-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
79 lines (69 loc) · 1.89 KB
/
utils.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
var bodyParser = require('body-parser');
var csrf = require('csurf');
var express = require('express');
var mongoose = require('mongoose');
var session = require('client-sessions');
var middleware = require('./middleware');
/**
* Given a user object:
*
* - Store the user object as a req.user
* - Make the user object available to templates as #{user}
* - Set a session cookie with the user object
*
* @param {Object} req - The http request object.
* @param {Object} res - The http response object.
* @param {Object} user - A user object.
*/
module.exports.createUserSession = function(req, res, user) {
var cleanUser = {
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
data: user.data || {},
};
req.session.user = cleanUser;
req.user = cleanUser;
res.locals.user = cleanUser;
};
/**
* Create and initialize an Express application that is 'fully loaded' and
* ready for usage!
*
* This will also handle setting up all dependencies (like database
* connections).
*
* @returns {Object} - An Express app object.
*/
module.exports.createApp = function() {
mongoose.connect('mongodb://localhost/svcc');
var app = express();
// settings
app.set('view engine', 'jade');
// middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
cookieName: 'session',
secret: 'keyboard cat',
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000,
}));
app.use(csrf());
app.use(middleware.simpleAuth);
// routes
app.use(require('./routes/auth'));
app.use(require('./routes/main'));
return app;
};
/**
* Ensure a user is logged in before allowing them to continue their request.
*
* If a user isn't logged in, they'll be redirected back to the login page.
*/
module.exports.requireLogin = function(req, res, next) {
if (!req.user) {
res.redirect('/login');
} else {
next();
}
};