forked from IzaanD98/plaidPal-BE
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
256 lines (217 loc) · 8.14 KB
/
Copy pathserver.js
File metadata and controls
256 lines (217 loc) · 8.14 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
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
const express = require("express");
const cors = require("cors");
const User = require("./db/model/UserModel");
const {handleAllErrors} = require('./controllers/error_handling_controllers');
const {
createLinkToken,
tokenExchange,
getPlaidAccounts,
getTransactions,
getPlaidCategories,
// getSingleTransaction,
getSingleTransactionAndNote,
} = require("./controllers/controller");
const db = require("./db/db");
const passport = require("passport");
const session = require("express-session");
const dotenv = require("dotenv");
const { OAuth2Client } = require("google-auth-library"); // npm install this on pp-be
const jwt = require("jsonwebtoken"); // this needs installing too
dotenv.config({ path: "./config.env" });
require("./config/passport")(passport);
db();
const {
createUser,
getAllUsers,
getUserById,
deleteUserById,
deleteAcount,
postNoteByTransactionId,
} = require("./controllers/controller");
const app = express();
app.use(cors());
// app.use(
// cors({
// origin: ["http://localhost:3000"],
// methods: "GET,POST,PUT,DELETE,OPTIONS",
// })
// ); // Hmmmmmm :D Deployed, this will be different.
// res.setHeader('Access-Control-Allow-Origin', '*');
app.use((req, res, next) => {
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, DELETE, OPTIONS"
);
res.setHeader("Access-Control-Allow-Credentials", true);
next();
});
app.use(express.json());
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: false,
})
);
// app.use(passport.initialize());
// app.use(passport.session());
// app.get(
// "/auth/google",
// passport.authenticate("google", {
// scope: ["profile", "email"],
// })
// );
// app.get(
// "/auth/google/callback",
// passport.authenticate("google", { failureRedirect: "/" }),
// (req, res) => {
// res.redirect("http://localhost:3000/dashboard");
// }
// );
app.get("/api/users", getAllUsers);
app.get("/api/users/:googleId", getUserById);
app.delete("/api/users/:googleId", deleteUserById);
app.post("/api/users", createUser);
app.post("/api/create_link_token", createLinkToken);
app.post("/api/exchange_public_token", tokenExchange);
app.post("/api/plaid/accounts", getPlaidAccounts);
app.post("/api/plaid/transactions", getTransactions);
app.get("/api/plaid/categories", getPlaidCategories);
app.post("/api/notes/:transaction_id", postNoteByTransactionId);
app.post("/api/transactions/:transaction_id", getSingleTransactionAndNote);
app.delete("/api/accounts/:account_id", deleteAcount);
const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
const client = new OAuth2Client(GOOGLE_CLIENT_ID);
async function verifyGoogleToken(token) {
try {
const ticket = await client.verifyIdToken({
idToken: token,
audience: GOOGLE_CLIENT_ID,
});
return { payload: ticket.getPayload() };
} catch (error) {
return { error: "Invalid user detected. Please try again" };
}
}
/** to here */
app.post("/api/signup", async (req, res) => {
console.log(req.body);
console.log(req.body.credential);
try {
// if (true) {
if (req.body.credential !== null) {
const verificationResponse = await verifyGoogleToken(req.body.credential);
// const verificationResponse = await verifyGoogleToken("eyJhbGciOiJSUzI1NiIsIm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1LsYmv8KCDXapQEycXX1N4ly2qwx8frP__cTJCBuHidLr9QH1diREX3emnSHe0ah1eopbg7nmQ10eFo9UNG7kGOcXCbitEnc4ImVkrtBkRFA");
console.log(verificationResponse);
if (verificationResponse.error) {
console.log(
"we got error on verifygoogletoken" + verificationResponse.error
);
return res.status(400).json({ message: verificationResponse.error });
}
const results = await User.find({
googleId: verificationResponse?.payload.sub,
});
if (results.length > 0) {
return res
.status(409)
.send({ message: "PlaidPal Error: User already exists" });
}
const profile = verificationResponse?.payload;
profile.googleId = verificationResponse?.payload.sub;
profile.displayName = verificationResponse?.payload.name;
await User.create(profile);
res
.status(201)
.send({
message: "Signup was successful",
user: {
googleId: profile?.sub,
displayName: profile?.name,
firstName: profile?.given_name,
lastName: profile?.family_name,
picture: profile?.picture,
email: profile?.email,
token: jwt.sign({ email: profile?.email }, "mySecret", {
expiresIn: "1d",
}),
},
})
.catch((error) => {
console.log(error);
console.log("plaidPal error 1st catch:");
return res
.status(500)
.send({ message: "An error occurred. Registration failed. 1" });
});
}
} catch (error) {
console.log("plaidPal error 2nd catch:");
console.log(error);
return res
.status(500)
.send({ message: "An error occurred. Registration failed. 2" });
}
});
/** Another route to add, and another function to add to the controller googleAuth.....
* prepend /api to the route eg. /api/login
*/
app.post("/api/login", async (req, res) => {
console.log(req.body);
console.log(req.body.credential);
try {
if (req.body.credential !== null) {
console.log(req.body);
console.log(req.body.credential);
const verificationResponse = await verifyGoogleToken(req.body.credential);
console.log("verificationResponse");
console.log(verificationResponse);
if (verificationResponse.error) {
return res.status(400).json({
message: verificationResponse.error,
});
}
const profile = verificationResponse?.payload;
profile.googleId = verificationResponse?.payload.sub;
// const existsInDB = DB.find((person) => person?.email === profile?.email); // perhaps findUserByID/Email/something? in the user model :)
// let existsInDB = "";
// User.find({email:profile?.email}).then((result)=>{
// existsInDB = result;
// });
let existsInDB = await User.find({ email: profile?.email });
console.log(existsInDB);
if (!existsInDB) {
return res.status(400).json({
message: "You are not registered. Please sign up",
});
}
res.status(201).json({
message: "Login was successful", // the user object will be the one returned from the DB and not hard coded
user: {
firstName: profile?.given_name,
lastName: profile?.family_name,
picture: profile?.picture,
email: profile?.email,
googleId: profile?.sub,
token: jwt.sign(
{ email: profile?.email },
process.env.GOOGLE_CLIENT_SECRET,
{
expiresIn: "1d",
}
),
},
});
}
} catch (error) {
res.status(500).json({
message: error?.message || error,
});
}
});
app.use(handleAllErrors);
module.exports = app;