This repository has been archived by the owner on Sep 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
200 lines (174 loc) · 6.1 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
const createError = require("http-errors");
const express = require("express");
const helmet = require("helmet");
const path = require("path");
const passport = require("passport");
const OAuth2Strategy = require("passport-oauth2");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const debug = require("debug")("strava-app:app");
const api = require("./routes/api");
const webhook = require("./routes/webhook");
const { saveEmailToDb } = require("./routes/email_api");
const { deleteAccount } = require("./routes/delete");
const { loadDb, deserializeUserQuery, newUserQuery } = require("./util/db");
const { mergeActivies } = require("./routes/merge");
const app = express();
const environment = app.get("env");
const version_env = process.env.VERSION_ENV;
loadDb();
// version number from GitHub actions
let version = "dev";
if (version_env) {
if (version_env.startsWith("refs/heads/main"))
version = version_env.match(/(?!-)([\w\d]){7}/)[0];
else version = version_env.substring(10, version_env.indexOf("-"));
}
console.log(
"strava-app, env: " +
environment +
", version: " +
version +
", analytics: " +
process.env.ANALYTICS_URL
);
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
// helmet setup
app.use(helmet());
app.use(
helmet.contentSecurityPolicy({
directives: {
"script-src": [
"'self'",
"cdnjs.cloudflare.com",
`${process.env.ANALYTICS_CSP}`,
],
"style-src": ["'self'", "cdnjs.cloudflare.com"],
"connect-src": ["'self'", `${process.env.ANALYTICS_CSP}`],
"img-src": ["'self'", `${process.env.ANALYTICS_CSP}`],
},
}),
helmet.crossOriginEmbedderPolicy({ policy: "credentialless" })
);
app.use(express.json());
// app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")));
let sessionSetup = {
secret: process.env.SECRET,
resave: false,
saveUninitialized: true,
cookie: { secure: false, maxAge: 3600000 * 24 * 90 },
store: MongoStore.create({
mongoUrl: `mongodb://${process.env.MONGO_USER}:${process.env.MONGO_PASS}@${process.env.MONGO_HOSTNAME}:27017/${process.env.MONGO_DB}?authSource=admin`,
}),
};
if (environment == "production") {
app.set("trust proxy", 1); // trust first proxy
sessionSetup.cookie.secure = true; // serve secure cookies
}
app.use(session(sessionSetup));
// Passport Setup
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
deserializeUserQuery(obj.id, done);
});
passport.use(
new OAuth2Strategy(
{
clientID: process.env.STRAVA_CLIENT_ID,
clientSecret: process.env.STRAVA_CLIENT_SECRET,
callbackURL: process.env.CALLBACKURL,
authorizationURL: "https://www.strava.com/oauth/authorize",
tokenURL: "https://www.strava.com/oauth/token",
},
function (accessToken, refreshToken, params, profile, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
newUserQuery(params, done, accessToken, refreshToken);
});
}
)
);
app.get("/api/activities", ensureAuthenticatedApi, api.view);
app.post("/api/email", ensureAuthenticatedApi, saveEmailToDb);
app.delete("/api/delete", ensureAuthenticatedApi, deleteAccount);
app.post("/api/merge", ensureAuthenticatedApi, mergeActivies);
app.get("/", function (req, res) {
res.render("index", {
user: req.user,
version,
analyticsUrl: process.env.ANALYTICS_URL,
analyticsImgUrl: process.env.ANALYTICS_IMG_URL,
});
});
app.get("/account", ensureAuthenticated, function (req, res) {
res.render("account", {
user: req.user,
version,
analyticsUrl: process.env.ANALYTICS_URL,
analyticsImgUrl: process.env.ANALYTICS_IMG_URL,
});
});
// GET /auth/strava
// Use passport.authenticate() as route middleware to authenticate the
// request. The first step in Strava authentication will involve
// redirecting the user to strava.com. After authorization, Strava
// will redirect the user back to this application at /auth/strava/callback
app.get(
"/auth/strava",
passport.authenticate("oauth2", {
scope: ["activity:read_all,activity:read,activity:write"],
})
);
// GET /auth/strava/callback
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
app.get(
"/auth/strava/callback",
passport.authenticate("oauth2", { failureRedirect: "/" }),
function (req, res) {
// On first login, show the welcome message
if (req.user.login_count <= 1) return res.redirect("/account?new");
res.redirect("/account");
}
);
app.get("/logout", function (req, res, next) {
req.logout(function (err) {
if (err) return next(err);
res.redirect("/");
});
});
// webhooks
app.post("/webhook", webhook.post);
app.get("/webhook", webhook.get);
// Simple route middleware to ensure user is authenticatec
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) return next();
res.redirect("/");
}
function ensureAuthenticatedApi(req, res, next) {
if (req.isAuthenticated()) return next();
res.status(403).send();
}
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = environment === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error");
});
module.exports = app;