-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
236 lines (207 loc) · 6.78 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
"use strict";
require("dotenv").config();
const redis = require("redis");
const session = require("express-session");
const RedisStore = require("connect-redis")(session);
const passport = require("passport");
const flash = require("express-flash");
const methodOverride = require("method-override");
const path = require("path");
const { PythonShell } = require("python-shell");
const crypto = require("crypto");
// const CoinMarketCap = require("coinmarketcap-api");
/*************************************
* Create App
*************************************/
const express = require("express");
const app = express();
const helmet = require("helmet");
const isDevelopment =
!process.env.NODE_ENV || process.env.NODE_ENV === "development";
const isProduction = process.env.NODE_ENV === "production";
var nonce = crypto.randomBytes(16).toString("hex");
if (isProduction) {
app.use((req, res, next) => {
res.locals.nonce = crypto.randomBytes(16).toString("hex");
next();
});
app.set("trust proxy", 1);
app.use(
helmet({
// crossOriginResourcePolicy: false,
})
);
// app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" }));
// app.use(helmet({ crossOriginEmbedderPolicy: false }));
app.use(
helmet.contentSecurityPolicy({
directives: {
"default-src": [
"'self'",
"'unsafe-inline'",
"https://s3.tradingview.com",
"https://s.tradingview.com",
"https://platform.twitter.com",
],
/* ... */
"script-src": [
"'self'",
"'unsafe-inline'",
"https://s3.tradingview.com",
"https://s.tradingview.com",
"https://platform.twitter.com",
// (req, res) => `'nonce-${res.locals.nonce}'`,
],
},
})
);
}
/*************************************
* Initialize Session
*************************************/
const sessionConfig = {
store: new RedisStore({ client: redis.createClient() }),
secret: process.env.COOKIE_SECRET,
resave: false,
saveUninitialized: false,
name: "session",
cookie: {
sameSite: isProduction,
secure: isProduction,
httpOnly: true,
maxAge: 1000 * 60 * 60 * 8, // 8 hours
},
};
/*************************************
* Initialize Middleware
*************************************/
app.use(flash());
app.use(session(sessionConfig));
app.use(passport.initialize());
app.use(passport.session());
/*************************************
* Authentication Using Passport
*************************************/
const initializePassport = require("./passportConfig");
initializePassport(passport);
app.use(methodOverride("_method"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// Make Public folder accessible without defining explicit endpoints
app.use(
"/public",
express.static(path.join(__dirname, "Public"), {
index: false,
extensions: ["html"],
})
);
/*************************************
* Server Side Rendering
*************************************/
app.set("view engine", "ejs");
/*************************************
* Require Controllers
*************************************/
const userController = require("./Controllers/userController.js");
const tweetController = require("./Controllers/tweetController.js");
const brokenController = require("./Controllers/brokenController");
/*************************************
* Require Validators
*************************************/
const userValidator = require("./Validators/userValidator");
const {
notFoundHandler,
productionErrorHandler,
catchAsyncErrors,
} = require("./utils/errorHandlers");
const pythonScript = require("./Machine_Learning/computePrediction");
/*************************************
* Create Endpoints
*************************************/
var coinNames = { btc: "Bitcoin", eth: "Ethereum", doge: "Doge Coin" };
// Simple endpoint that purposely throws an asynchronous exception
app.get("/breakAsync", catchAsyncErrors(brokenController.breakAsync));
/**********************************************
* If logged in, go to dashboard.
* If not already logged in, go to login page.
* *******************************************/
app.get("/", userController.checkAuthenticated, async (req, res) => {
res.render("dashboard", {
loggedUsername: req.user.firstName,
});
});
app.get("/index", userController.checkAuthenticated, (req, res) => {
res.redirect("/");
});
app.get("/register", userController.checkNotAuthenticated, (req, res) => {
res.render("register.ejs");
});
/***********************************************************************
* Checks if not logged in,
* Validates user; checks if username and email not in database(unique),
* Creates the user.
***********************************************************************/
app.post(
"/register",
userController.checkNotAuthenticated,
userValidator.validateUserCreationBody,
catchAsyncErrors(userController.createNewUser)
);
app.get("/login", userController.checkNotAuthenticated, (req, res) => {
res.render("login");
});
app.get("/:coin/coinChart", userController.checkAuthenticated, (req, res) => {
// console.log("NONCE", res.locals.nonce);
res.render("coinChart", {
coin: req.params.coin,
coinName: coinNames[req.params.coin],
nonce: res.locals.nonce,
});
});
//update, pythonScript for searching tweet data and build boxes for tweets on website.
app.get(
"/:coin/coinChart/predict",
userController.checkAuthenticated,
userController.checkPrediction,
pythonScript.python,
tweetController.getTweetsOfCoin,
(req, res) => {
res.render("prediction", {
pred: res.locals.pred,
coin: req.params.coin,
tweets: res.locals.tweets,
});
}
);
app.get(
"/history",
userController.checkAuthenticated,
userController.getPredictionHistory,
(req, res) => {
res.render("predictHistory", { history: res.locals.history });
}
);
/**********************************************************************
* If /login endpoint is entered:
* If person 'logged in', goes to main page(aka dashboard).
* If person not logged in, goes to /login page.
**********************************************************************/
app.post(
"/login",
userController.checkNotAuthenticated,
passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/login",
failureFlash: true,
})
);
app.get("/logout", (req, res) => {
req.logOut();
req.flash("logOutSuccess", "Log Out Successful!");
res.redirect("/login");
});
app.use(notFoundHandler);
if (isProduction) {
app.use(productionErrorHandler);
}
module.exports = app;