finish etyd + checktoken tweaks

This commit is contained in:
Enstrayed
2025-05-09 16:59:54 -07:00
parent 4be52c7f26
commit d3f0b29094
5 changed files with 68 additions and 126 deletions

View File

@@ -19,25 +19,36 @@ async function checkToken(token,scope) {
}
/**
* New function to check if a token exists in the sessions table (authentication) and if it has the desired scope (authorization)
* @param {string} token Token as received by client
* Checks for tokens provided in request and validates them against the sessions table including the desired scope
* @param {object} request Express request object
* @param {string} scope Desired scope for action
* @typedef {Object} Object containing the result and the username of the token owner
* @typedef {object} Object containing the result and the username of the token owner
* @property {boolean} result Boolean result of if the check passed
* @property {string} owner Username of the token owner
* @property {number} ownerId Database ID of the token owner
*/
async function checkTokenNew(token,scope) {
return await db`select s.*, u.username from sessions s join users u on s.owner = u.id where s.token = ${token}`.then(response => {
if (response.length === 0) {
return { result: false, owner: response[0]?.username, ownerId: response[0]?.owner}
} else if (response[0]?.scopes.split(",").includes(scope)) {
return { result: true, owner: response[0]?.username, ownerId: response[0]?.owner}
} else {
return { result: false, owner: response[0]?.username, ownerId: response[0]?.owner}
}
})
async function checkTokenNew(request, scope) {
if (!request.cookies["APIToken"] && !request.get("Authorization")) {
return { result: false, owner: "", ownerId: "" }
} else {
return await db`select s.*, u.username from sessions s join users u on s.owner = u.id where s.token = ${request.get("Authorization") ?? request.cookies["APIToken"]}`.then(response => {
if (response.length === 0) {
return { result: false, owner: response[0]?.username, ownerId: response[0]?.owner }
} else if (response[0]?.scopes.split(",").includes(scope)) {
return { result: true, owner: response[0]?.username, ownerId: response[0]?.owner }
} else {
return { result: false, owner: response[0]?.username, ownerId: response[0]?.owner }
}
}).catch(dbErr => {
return { result: false, owner: "", ownerId: "" }
})
}
}
export {checkToken, checkTokenNew}