diff --git a/.env.example b/.env.example index bf36a73..0ee5859 100644 --- a/.env.example +++ b/.env.example @@ -4,4 +4,7 @@ DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=test DB_USERNAME=root -DB_PASSWORD= \ No newline at end of file +DB_PASSWORD= + +JWT_SECRET=test +JWT_ALGORITHM=HS256 \ No newline at end of file diff --git a/package.json b/package.json index e3078a1..3f2b152 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "license": "MIT", "dependencies": { "express": "^4.18.2", + "express-jwt": "^8.4.1", "morgan": "^1.10.0", "mysql2": "^3.6.2", "path": "^0.12.7", diff --git a/src/config/express.ts b/src/config/express.ts index 1d9b2d1..2bb8183 100644 --- a/src/config/express.ts +++ b/src/config/express.ts @@ -1,5 +1,6 @@ import express from 'express'; import logger from 'morgan' +import {expressjwt} from "express-jwt"; const app = express(); @@ -7,5 +8,26 @@ app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); + +// JWT +app.use( + expressjwt({ + secret: Buffer.from(process.env.JWT_SECRET, "base64"), + algorithms: ["HS256"], + issuer: "testing", + }) +); + +app.use((err: express.ErrorRequestHandler, req: express.Request, res: express.Response, next: express.NextFunction) => { + if (err.name === "UnauthorizedError") { + res.status(401).send({ + "message": "Invalid token" + }); + } else { + next(err); + } +}); + + export default app;