v1.0.0 #28
|
@ -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"
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -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();
|
|
@ -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);
|
Loading…
Reference in New Issue