aboutsummaryrefslogtreecommitdiff
path: root/src/middleware/auth.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/middleware/auth.ts')
-rw-r--r--src/middleware/auth.ts34
1 files changed, 34 insertions, 0 deletions
diff --git a/src/middleware/auth.ts b/src/middleware/auth.ts
new file mode 100644
index 0000000..ee10218
--- /dev/null
+++ b/src/middleware/auth.ts
@@ -0,0 +1,34 @@
+import { Request, Response, NextFunction } from "express";
+import jwt from "jsonwebtoken";
+
+const authenticate = () => (req: Request, res: Response, next: NextFunction) => {
+ const authHeader = req.headers.authorization;
+ const token = authHeader && authHeader.split(" ")[1];
+
+ if (!token) res.status(401).json({ error: "Unauthorized" });
+
+ // @ts-ignore
+ jwt.verify(token as string, process.env.ACCESS_TOKEN_SECRET, (err, claims) => {
+ if (err) {
+ // @ts-ignore
+ switch (err.message) {
+ case "jwt expired":
+ res.status(401).json({ error: "Token Expired" });
+ break;
+ case "invalid signature":
+ res.status(401).json({ error: "Invalid Credentials" });
+ break;
+ default:
+ res.status(500).json({ error: "Internal Server Error" });
+ console.error(err)
+ break;
+ }
+ } else {
+ // @ts-ignore
+ req.userId = claims.userId;
+ next();
+ }
+ });
+}
+
+export default authenticate; \ No newline at end of file