-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.js
55 lines (45 loc) · 1.25 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
import express from "express";
import dotenv from "dotenv";
import cookieParser from "cookie-parser";
import testRoute from "./routes/test-route.js";
import authRouter from "./routes/auth-route.js";
const app = express();
import { connect } from "./db/connect.js";
import {
getCreateSessionCookie,
getDeleteSessionCookie,
validateSessionToken,
} from "./lib/auth.js";
dotenv.config();
connect();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cookieParser());
// auth middleware
app.use(async (req, res, next) => {
const token = req.cookies.session;
if (token === null) {
res.locals.user = null;
res.locals.session = null;
return next();
}
const { session, user } = await validateSessionToken(token);
if (session === null) {
res.appendHeader("Set-Cookie", getDeleteSessionCookie());
res.locals.session = null;
res.locals.user = null;
return next();
}
res.appendHeader(
"Set-Cookie",
getCreateSessionCookie(token, session.expires_at)
);
res.locals.session = session;
res.locals.user = user;
return next();
});
app.use("/auth", authRouter);
app.use("/test", testRoute);
app.listen(8080 || process.env.PORT, () =>
console.log("SERVER STARTED " + process.env.PORT)
);