1 |
import { NextFunction, Response } from "express"; |
2 |
import Request from "../Request"; |
3 |
import jwt, { JwtPayload } from 'jsonwebtoken'; |
4 |
import User from "../../models/User"; |
5 |
|
6 |
export default async function Auth(request: Request, response: Response, next: NextFunction) { |
7 |
if (!request.user) { |
8 |
const { authorization } = request.headers; |
9 |
|
10 |
if (!authorization) { |
11 |
next(); |
12 |
return; |
13 |
} |
14 |
|
15 |
const [type, token] = authorization.split(/ +/); |
16 |
|
17 |
if (type !== "Bearer") { |
18 |
return response.status(401).send({ error: "Only Bearer tokens are supported" }); |
19 |
} |
20 |
|
21 |
if (!token) { |
22 |
return response.status(401).send({ error: "No Bearer token provided" }); |
23 |
} |
24 |
|
25 |
try { |
26 |
const { _id, discord_id, username } = jwt.verify(token, process.env.JWT_SECRET!) as JwtPayload; |
27 |
|
28 |
if (!_id || !discord_id || !username) { |
29 |
throw new Error(); |
30 |
} |
31 |
|
32 |
const user = await User.findOne({ _id, discord_id, username }); |
33 |
|
34 |
if (!user) { |
35 |
throw new Error(); |
36 |
} |
37 |
|
38 |
request.user = user; |
39 |
} |
40 |
catch (e) { |
41 |
console.log(e); |
42 |
return response.status(401).send({ error: "Invalid token provided" }); |
43 |
} |
44 |
} |
45 |
|
46 |
next(); |
47 |
} |