From d8bb908b03c82348a12f689d48b95c7276defc1f Mon Sep 17 00:00:00 2001 From: Alie Date: Wed, 27 Dec 2023 18:19:46 +0100 Subject: [PATCH] added basic auth controler --- package.json | 2 ++ src/controllers/AuthControler.ts | 52 ++++++++++++++++++++++++++++++++ src/models/AppModel.ts | 19 ++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 src/controllers/AuthControler.ts create mode 100644 src/models/AppModel.ts diff --git a/package.json b/package.json index 299b1a8..7a8021d 100644 --- a/package.json +++ b/package.json @@ -22,9 +22,11 @@ "dependencies": { "@types/express": "^4.17.21", "@types/express-list-endpoints": "^6.0.3", + "@types/jsonwebtoken": "^9.0.5", "@types/mongoose": "^5.11.97", "express": "^4.18.2", "express-list-endpoints": "^6.0.0", + "jsonwebtoken": "^9.0.2", "mongoose": "^8.0.3" } } \ No newline at end of file diff --git a/src/controllers/AuthControler.ts b/src/controllers/AuthControler.ts new file mode 100644 index 0000000..5d0e43e --- /dev/null +++ b/src/controllers/AuthControler.ts @@ -0,0 +1,52 @@ +import jwt from "jsonwebtoken"; +import AppModel from "../models/AppModel"; +import { Request, Response, NextFunction } from "express"; + +const authTokenSecret = process.env.JWTSECRET || "badsecret"; + +class AuthControler { + async login(req: Request, res: Response) { + // Read app and secret from request body + const { app, secret } = req.body; + + // Filter app from the apps by app and secret + const authenticated = await AppModel.findOne(app, secret); + + if (authenticated) { + console.log("Authenticated app ", authenticated.app); + // Generate an access token + const accessToken = jwt.sign({ app: authenticated.app }, authTokenSecret); + + res.json({ + accessToken, + }); + } else { + res.status(403).send("Credentials incorrect"); + } + } + + authorize(req: Request, res: Response, next: NextFunction) { + const authHeader = req.headers.authorization; + if (authHeader) { + const token = authHeader.split(" ")[1]; + + jwt.verify(token, authTokenSecret, (err, user) => { + if (err) { + return res.status(403).json("Invalid token provided"); + } + + console.log( + "Authorization provided for ", + next.name, + " to user ", + user + ); + next(); + }); + } else { + res.status(401).json("No Authorization header provided"); + } + } +} + +export default new AuthControler(); diff --git a/src/models/AppModel.ts b/src/models/AppModel.ts new file mode 100644 index 0000000..9ef6535 --- /dev/null +++ b/src/models/AppModel.ts @@ -0,0 +1,19 @@ +import mongoose, { Document } from "mongoose"; + +export interface App extends Document { + app: String, + secret: String +} + +const AppSchema = new mongoose.Schema({ + app: { + type: String, + required: true, + }, + secret: { + type: String, + required: true, + }, +}); + +export default mongoose.model("apps", AppSchema);