-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.js
More file actions
198 lines (178 loc) · 5.6 KB
/
Copy pathapp.js
File metadata and controls
198 lines (178 loc) · 5.6 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
/**
* Module dependencies.
*/
var express = require('express')
, http = require('http')
, path = require('path')
, request = require('request')
, crypto = require('crypto')
, Sequelize = require('sequelize');
var sequelize = new Sequelize('sample_app', 'username', 'password', {
host: 'localhost',
dialect: 'sqlite',
pool: {
max: 5,
min: 0,
idle: 10000
},
storage: './sample_app.sqlite'
});
var User = sequelize.define('user', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
email: {
type: Sequelize.STRING
},
clefID: {
type: Sequelize.INTEGER
},
loggedOutAt: {
type: Sequelize.DATE
},
});
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 4000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
});
app.configure('development', function() {
app.use(express.errorHandler());
});
var APP_ID = '4f4baa300eae6a7532cc60d06b49e0b9',
APP_SECRET = 'd0d0ba5ef23dc134305125627c45677c';
// Pass your credentials to the ClefAPI constructor
var clef = require('clef').initialize({appID: APP_ID, appSecret: APP_SECRET});
/**
* This middleware function is used to check whether the user has logged out
* with Clef already, and if so, destroys their session in the browser,
* logging them out.
*
* For more info, see http://docs.getclef.com/v1.0/docs/checking-timestamped-logins
*/
app.use(function(req, res, next) {
if (req.session.user == undefined) { return next(); }
User.find({ where: { id: req.session.user.id } }).then(function(user) {
if (!user || user.loggedOutAt == null || user.loggedOutAt < req.session.user.loggedInAt) {
next();
} else {
req.session.destroy();
res.redirect('/');
}
})
});
var generateRandomStateParameter = function(session) {
var state = crypto.randomBytes(32).toString('base64');
// Make the base64 encoded string URL safe by replacing '+' and '/' with '-' and '_'
state = state.replace(/\+/g, '-').replace(/\//g, '_');
session.state = state;
return state;
};
var stateParameterIsValid = function(session, state) {
stateIsValid = session.state && session.state.length > 0 && state == session.state;
delete session.state;
return stateIsValid;
};
/**
* Shows user information, or shows the Clef login button.
*/
app.get('/', function(req, res) {
var userID = req.session.user && req.session.user.id;
User.find({ where: { id: userID } }).then(function(user) {
res.render('index', { user: user, state: generateRandomStateParameter(req.session) });
});
});
/**
* Does an OAuth handshake with Clef to get user information.
*
* This route is redirected to automatically by the browser when a user
* logs in with Clef.
*
* For more info, see http://docs.getclef.com/v1.0/docs/authenticating-users
*/
app.get('/login', function(req, res) {
// If the state parameter doesn't match what we passed into the Clef button,
// then this request could have been generated by a 3rd party, so we should
// abort it.
//
// For more protection about the state parameter and CSRF, check out
// http://docs.getclef.com/v1.0/docs/verifying-state-parameter
var state = req.query.state;
if (!stateParameterIsValid(req.session, state)) {
return res.status(403).send("Oops, the state parameter didn't match what was passed in to the Clef button.");
}
var code = req.query.code;
clef.getLoginInformation({code: code}, function(err, userInformation) {
if (err) {
// Handle the error
switch(err.type) {
case 'InvalidAppIDError':
console.log('Invalid app ID');
break;
case 'InvalidAppSecretError':
console.log('Invalid app secret');
break;
case 'InvalidOAuthCodeError':
console.log('Invalid OAuth code');
break;
case 'InvalidOAuthTokenError':
console.log('Invalid OAuth token exchange');
break;
default:
console.log('API error');
console.log(err);
}
} else {
var clefID = userInformation['id'];
var email = userInformation['email'];
// Fetch a user given the `id` returned by Clef. If the user doesn't
// exist, it is created with the email address and `id` returned by Clef.
User.findOrCreate({where: {clefID: clefID}, defaults: {email: email}})
.spread(function(user, created) {
req.session.user = {
id: user.id,
loggedInAt: Date.now()
}
res.redirect('/');
});
}
});
});
/**
* Handles logout hook requests sent by Clef when a user logs out on their phone.
*
* This method looks up a user by their `clefID` and updates the database to
* indicate that they've logged out.
*
* For more info, see http://docs.getclef.com/v1.0/docs/database-logout
*/
app.post('/logout', function(req, res) {
var token = req.body.logout_token;
clef.getLogoutInformation({logoutToken: token}, function(err, clefID){
if (err) {
console.log(err);
} else {
User.find({where: {clefID: clefID}}).then(function(user){
user.updateAttributes({
loggedOutAt: Date.now()
}).then(function() {
res.send('bye');
});
});
}
});
});
sequelize.sync().then(function () {
http.createServer(app).listen(app.get('port'), function() {
console.log("Express server listening on port " + app.get('port'));
});
})