-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
executable file
·282 lines (238 loc) · 9.95 KB
/
app.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
/*
Copyright 2017 IBM Corp.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const express = require("express");
const session = require("express-session");
const passport = require("passport");
const nconf = require("nconf");
const appID = require("bluemix-appid");
const helmet = require("helmet");
const express_enforces_ssl = require("express-enforces-ssl");
const cfEnv = require("cfenv");
const cookieParser = require("cookie-parser");
const WebAppStrategy = appID.WebAppStrategy;
const userAttributeManager = appID.UserAttributeManager;
const UnauthorizedException = appID.UnauthorizedException;
const app = express();
const GUEST_USER_HINT = "A guest user started using the app. App ID created a new anonymous profile, where the user’s selections can be stored.";
const RETURNING_USER_HINT = "An identified user returned to the app with the same identity. The app accesses his identified profile and the previous selections that he made.";
const NEW_USER_HINT = "An identified user logged in for the first time. Now when he logs in with the same credentials from any device or web client, the app will show his same profile and selections.";
const LOGIN_URL = "/ibm/bluemix/appid/login";
const CALLBACK_URL = "/ibm/bluemix/appid/callback";
const port = process.env.PORT || 3000;
const isLocal = cfEnv.getAppEnv().isLocal;
const config = getLocalConfig();
var Cloudant = require('@cloudant/cloudant');
var me = 'b341fed5-7e78-4231-80bf-ecfaa4e5f1e8-bluemix'; // Set this to your own account
var password = 'c26987d6f936abdb6c08b2ef4aa7a1136dd910e89c07484ee5fa57c92d46a257';
// Initialize the library with my account.
var cloudant = Cloudant({account:me, password:password});
cloudant.db.list(function(err, allDbs) {
console.log('All my databases: %s', allDbs.join(', '))
});
configureSecurity();
// Setup express application to use express-session middleware
// Must be configured with proper session storage for production
// environments. See https://github.com/expressjs/session for
// additional documentation
app.use(session({
secret: "123456",
resave: true,
saveUninitialized: true,
proxy: true,
cookie: {
httpOnly: true,
secure: !isLocal
}
}));
app.set('view engine', 'ejs');
// Configure express application to use passportjs
app.use(passport.initialize());
app.use(passport.session());
let webAppStrategy = new WebAppStrategy(config);
passport.use(webAppStrategy);
// Initialize the user attribute Manager
userAttributeManager.init(config);
// Configure passportjs with user serialization/deserialization. This is required
// for authenticated session persistence accross HTTP requests. See passportjs docs
// for additional information http://passportjs.org/docs
passport.serializeUser(function(user, cb) {
cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
cb(null, obj);
});
// Explicit login endpoint. Will always redirect browser to login widget due to {forceLogin: true}.
// If forceLogin is set to false redirect to login widget will not occur of already authenticated users.
app.get(LOGIN_URL, passport.authenticate(WebAppStrategy.STRATEGY_NAME, {
forceLogin: true
}));
// Callback to finish the authorization process. Will retrieve access and identity tokens/
// from AppID service and redirect to either (in below order)
// 1. the original URL of the request that triggered authentication, as persisted in HTTP session under WebAppStrategy.ORIGINAL_URL key.
// 2. successRedirect as specified in passport.authenticate(name, {successRedirect: "...."}) invocation
// 3. application root ("/")
app.get(CALLBACK_URL, passport.authenticate(WebAppStrategy.STRATEGY_NAME, {allowAnonymousLogin: true}));
function storeRefreshTokenInCookie(req, res, next) {
if (req.session[WebAppStrategy.AUTH_CONTEXT] && req.session[WebAppStrategy.AUTH_CONTEXT].refreshToken) {
const refreshToken = req.session[WebAppStrategy.AUTH_CONTEXT].refreshToken;
/* An example of storing user's refresh-token in a cookie with expiration of a month */
res.cookie('refreshToken', refreshToken, {maxAge: 1000 * 60 * 60 * 24 * 30 /* 30 days */});
}
next();
}
function isLoggedIn(req) {
return req.session[WebAppStrategy.AUTH_CONTEXT];
}
// Protected area. If current user is not authenticated - redirect to the login widget will be returned.
// In case user is authenticated - a page with current user information will be returned.
app.get("/protected", function tryToRefreshTokensIfNotLoggedIn(req, res, next) {
if (isLoggedIn(req)) {
return next();
}
webAppStrategy.refreshTokens(req, req.cookies.refreshToken).finally(function() {
next();
});
}, passport.authenticate(WebAppStrategy.STRATEGY_NAME), storeRefreshTokenInCookie, function (req, res, next) {
var accessToken = req.session[WebAppStrategy.AUTH_CONTEXT].accessToken;
var isGuest = req.user.amr[0] === "appid_anon";
var foodSelection;
var firstLogin;
// get the attributes for the current user:
userAttributeManager.getAllAttributes(accessToken).then(function (attributes) {
var toggledItem = req.query.foodItem;
foodSelection = attributes.foodSelection ? JSON.parse(attributes.foodSelection) : [];
firstLogin = !isGuest && !attributes.points;
if (!toggledItem) {
return;
}
var selectedItemIndex = foodSelection.indexOf(toggledItem);
if (selectedItemIndex >= 0) {
foodSelection.splice(selectedItemIndex, 1);
} else {
foodSelection.push(toggledItem);
}
// update the user's selection
return userAttributeManager.setAttribute(accessToken, "foodSelection", JSON.stringify(foodSelection));
}).then(function () {
givePointsAndRenderPage(req, res, foodSelection, isGuest, firstLogin);
}).catch(function (e) {
next(e);
});
});
// Protected area. If current user is not authenticated - an anonymous login process will trigger.
// In case user is authenticated - a page with current user information will be returned.
app.get("/anon_login", passport.authenticate(WebAppStrategy.STRATEGY_NAME, {allowAnonymousLogin: true, successRedirect : '/protected', forceLogin: true}));
// Protected area. If current user is not authenticated - redirect to the login widget will be returned.
// In case user is authenticated - a page with current user information will be returned.
app.get("/login", passport.authenticate(WebAppStrategy.STRATEGY_NAME, {successRedirect : '/front', forceLogin: true}));
app.get("/logout", function(req, res, next) {
WebAppStrategy.logout(req);
// If you chose to store your refresh-token, don't forgot to clear it also in logout:
res.clearCookie("refreshToken");
res.redirect("/");
});
app.get("/front",function(req,res) {
console.log('request handler for front was called');
res.writeHead(200, {"Content-Type": "text/html"});
res.write("random numbers that should come in the form of json");
res.end();
});
app.get("/token", function(req, res){
//return the token data
res.render('token',{tokens: JSON.stringify(req.session[WebAppStrategy.AUTH_CONTEXT])});
});
app.use(express.static("public", {index: null}));
app.use('/', function(req, res, next) {
if (!isLoggedIn(req)) {
webAppStrategy.refreshTokens(req, req.cookies.refreshToken).then(function() {
res.redirect('/protected');
}).catch(function() {
next();
})
} else {
res.redirect('/protected');
}
}, function(req,res,next) {
res.sendFile(__dirname + '/public/index.html');
});
app.use(function(err, req, res, next) {
if (err instanceof UnauthorizedException) {
WebAppStrategy.logout(req);
res.redirect('/');
} else {
next(err);
}
});
app.listen(port, function(){
console.log("Listening on http://localhost:" + port);
});
function givePointsAndRenderPage(req, res, foodSelection, isGuest, firstLogin) {
//return the protected page with user info
var hintText;
if (isGuest) {
hintText = GUEST_USER_HINT;
} else {
if (firstLogin) {
hintText = NEW_USER_HINT;
} else {
hintText = RETURNING_USER_HINT;
}
}
var email = req.user.email;
if(req.user.email !== undefined && req.user.email.indexOf('@') != -1)
email = req.user.email.substr(0,req.user.email.indexOf('@'));
var renderOptions = {
name: req.user.name || email || "Guest",
picture: req.user.picture || "/images/anonymous.svg",
foodSelection: JSON.stringify(foodSelection),
topHintText: isGuest ? "Login to get a gift >" : "You got 150 points go get a pizza",
topImageVisible : isGuest ? "hidden" : "visible",
topHintClickAction : isGuest ? ' window.location.href = "/login";' : ";",
hintText : hintText,
isGuest: isGuest
};
if (firstLogin) {
userAttributeManager.setAttribute(req.session[WebAppStrategy.AUTH_CONTEXT].accessToken, "points", "150").then(function (attributes) {
res.render('protected', renderOptions);
});
} else {
res.render('protected', renderOptions);
}
}
function getLocalConfig() {
if (!isLocal) {
return {};
}
let config = {};
const localConfig = nconf.env().file(`${__dirname}/config.json`).get();
const requiredParams = ['clientId', 'secret', 'tenantId', 'oauthServerUrl', 'profilesUrl'];
requiredParams.forEach(function (requiredParam) {
if (!localConfig[requiredParam]) {
console.error('When running locally, make sure to create a file *config.json* in the root directory. See config.template.json for an example of a configuration file.');
console.error(`Required parameter is missing: ${requiredParam}`);
process.exit(1);
}
config[requiredParam] = localConfig[requiredParam];
});
config['redirectUri'] = `http://localhost:${port}${CALLBACK_URL}`;
return config;
}
function configureSecurity() {
app.use(helmet());
app.use(cookieParser());
app.use(helmet.noCache());
app.enable("trust proxy");
if (!isLocal) {
app.use(express_enforces_ssl());
}
}