-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
77 lines (67 loc) · 1.96 KB
/
server.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
const next = require("next");
const express = require("express");
const axios = require("axios");
const cookieParser = require("cookie-parser");
const dev = process.env.NODE_ENV !== "production";
const port = process.env.PORT || 3000;
const app = next({ dev });
const handle = app.getRequestHandler();
const AUTH_USER_TYPE = "authenticated";
const COOKIE_SECRET = "asldkfjals23ljk";
const COOKIE_OPTIONS = {
httpOnly: true,
secure: !dev,
signed: true
};
const authenticate = async (email, password) => {
const { data } = await axios.get(
"https://jsonplaceholder.typicode.com/users"
);
return data.find(user => {
if (user.email === email && user.website === password) {
return user;
}
});
};
app.prepare().then(() => {
const server = express();
server.use(express.json());
server.use(cookieParser(COOKIE_SECRET));
server.post("/api/login", async (req, res) => {
const { email, password } = req.body;
const user = await authenticate(email, password);
if (!user) {
return res.status(403).send("Invalid email or password");
}
const userData = {
name: user.name,
email: user.email,
type: AUTH_USER_TYPE
};
res.cookie("token", userData, COOKIE_OPTIONS);
res.json(userData);
});
server.post("/api/logout", (req, res) => {
res.clearCookie("token", COOKIE_OPTIONS);
res.sendStatus(204);
});
server.get("/api/profile", async (req, res) => {
const { signedCookies = {} } = req;
const { token } = signedCookies;
if (token && token.email) {
const { data } = await axios.get(
"https://jsonplaceholder.typicode.com/users"
);
const userProfile = data.find(user => user.email === token.email);
return res.json({ user: userProfile });
}
res.sendStatus(404);
});
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`Listening on PORT ${port}`);
});
});