-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
97 lines (80 loc) · 2.4 KB
/
index.ts
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
import express from "express";
import passport from "passport";
import { UserService } from "./services/user";
import jwt from "jsonwebtoken";
import postRouter from "./routes/posts";
import voteRouter from "./routes/votes";
import categoryRouter from "./routes/categories";
import tagRouter from "./routes/tags";
import AnonymousStrategy from "passport-anonymous";
import cors from "cors";
const app = express();
const port = 3500;
const userService = new UserService();
app.use(express.json());
app.use(cors({
origin: "http://localhost:3000",
}))
passport.use('signup', userService.registerStrategy());
passport.use('login', userService.loginStrategy());
passport.use(userService.jwtStrategy());
passport.use(new AnonymousStrategy.Strategy());
const auth = passport.authenticate(["jwt", "anonymous"], { session: false });
app.use('/api/v1/posts', auth, postRouter);
app.use('/api/v1/categories', auth, categoryRouter);
app.use('/api/v1/tags', auth, tagRouter);
app.use('/api/v1/votes', auth, voteRouter);
app.post(
"/api/v1/register",
passport.authenticate('signup', { session: false }),
async (req, res) => {
res.status(201);
res.json(req.user);
},
);
app.post(
'/api/v1/login',
async (req, res, next) => {
passport.authenticate(
'login',
async (err, user) => {
try {
if (err || !user) {
const error = new Error('An error occurred.');
return next(error);
}
req.login(
user,
{ session: false },
async (error) => {
if (error) return next(error);
const body = { id: user.id, username: user.username, admin: user.admin };
const token = jwt.sign({ user: { id: user.id } }, 'TOP_SECRET');
return res.json({ token, user: body });
}
);
} catch (error) {
return next(error);
}
}
)(req, res, next);
}
);
app.get("/api/v1/me", auth, (req, res) => {
if (req.user) {
res.json(req.user);
} else {
res.status(401);
res.send("You must be logged in to be able to see your user data.");
}
})
app.get("/assets/:file", (req, res) => {
res.sendFile(`${__dirname}/public/assets/${req.params.file}`);
});
app.get("/*", (_, res) => {
res.sendFile(__dirname + "/public/index.html");
});
const server = app.listen(port, () => {
console.log("Server is running.");
});
export default server;