added basic auth controler

This commit is contained in:
Alie 2023-12-27 18:19:46 +01:00
parent 730b8368cd
commit d8bb908b03
3 changed files with 73 additions and 0 deletions

View File

@ -22,9 +22,11 @@
"dependencies": { "dependencies": {
"@types/express": "^4.17.21", "@types/express": "^4.17.21",
"@types/express-list-endpoints": "^6.0.3", "@types/express-list-endpoints": "^6.0.3",
"@types/jsonwebtoken": "^9.0.5",
"@types/mongoose": "^5.11.97", "@types/mongoose": "^5.11.97",
"express": "^4.18.2", "express": "^4.18.2",
"express-list-endpoints": "^6.0.0", "express-list-endpoints": "^6.0.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.0.3" "mongoose": "^8.0.3"
} }
} }

View File

@ -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();

19
src/models/AppModel.ts Normal file
View File

@ -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);