Refactor API key validation logic
Added API page documentation
This commit is contained in:
@ -1,39 +1,45 @@
|
||||
const { checkAPikey } = require('../functions/database.js');
|
||||
const { checkAPikey } = require("../functions/database.js");
|
||||
async function apikeyCheck(req, res, next) {
|
||||
//const authHeader = req.headers.authorization
|
||||
try{
|
||||
let apikey = req.headers.authorization
|
||||
if(!apikey){
|
||||
throw new Error('No API key was supplied. Invalid request')
|
||||
}
|
||||
else{
|
||||
//split the string by the -
|
||||
let splitAPIkey = apikey.split('-');
|
||||
let rowid = splitAPIkey[0];
|
||||
|
||||
//rejoin withouth the rowid
|
||||
let SuppliedKey = splitAPIkey.slice(1).join('-');
|
||||
if (checkAPikey(SuppliedKey , rowid))
|
||||
{
|
||||
//get permission
|
||||
let permission = await checkAPikey(SuppliedKey , rowid);
|
||||
console.log(permission);
|
||||
if (req.method === 'GET' && permission === 'canRead'){
|
||||
return next()
|
||||
}
|
||||
//['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)
|
||||
if (["GET" , "POST" , "PUT" , "DELETE"].includes(req.method) && permission === 'canWrite'){
|
||||
console.log('write')
|
||||
return next()
|
||||
}
|
||||
throw new Error('Your API key does not have the correct permissions to access this resource')
|
||||
|
||||
}
|
||||
}
|
||||
}catch(error){
|
||||
next(error);
|
||||
}
|
||||
//const authHeader = req.headers.authorization
|
||||
try {
|
||||
let apikey = req.headers.authorization;
|
||||
if (!apikey) {
|
||||
res.status(401).json({
|
||||
message: "No API key was supplied. Invalid request",
|
||||
});
|
||||
//throw new Error("No API key was supplied. Invalid request");
|
||||
} else {
|
||||
//split the string by the -
|
||||
let splitAPIkey = apikey.split("-");
|
||||
let rowid = splitAPIkey[0];
|
||||
|
||||
//rejoin withouth the rowid
|
||||
let SuppliedKey = splitAPIkey.slice(1).join("-");
|
||||
if (checkAPikey(SuppliedKey, rowid)) {
|
||||
//get permission
|
||||
let permission = await checkAPikey(SuppliedKey, rowid);
|
||||
console.log(permission);
|
||||
if (req.method === "GET" && permission === "canRead") {
|
||||
return next();
|
||||
}
|
||||
//['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)
|
||||
if (
|
||||
["GET", "POST", "PUT", "DELETE"].includes(req.method) &&
|
||||
permission === "canWrite"
|
||||
) {
|
||||
console.log("write");
|
||||
return next();
|
||||
}
|
||||
//throw status 403
|
||||
res.status(403).json({
|
||||
message:
|
||||
"Your API key does not have the correct permissions to access this resource",
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { apikeyCheck };
|
||||
@ -56,4 +62,4 @@ If it's correct API key and has canWrite perms
|
||||
I allow it to access put and post
|
||||
|
||||
|
||||
*/
|
||||
*/
|
||||
|
Reference in New Issue
Block a user