v1.0.0 #28

Merged
bizcochito merged 147 commits from develop into main 2024-01-14 19:49:34 +00:00
3 changed files with 73 additions and 0 deletions
Showing only changes of commit d8bb908b03 - Show all commits

View File

@ -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"
}
}

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