1
0
Fork 0
mirror of synced 2024-06-29 19:41:03 +12:00
budibase/packages/auth/src/middleware/authenticated.js

44 lines
1.1 KiB
JavaScript
Raw Normal View History

2021-04-11 22:35:55 +12:00
const { Cookies } = require("../constants")
2021-04-22 22:45:22 +12:00
const database = require("../db")
const { getCookie, clearCookie } = require("../utils")
2021-04-22 22:45:22 +12:00
const { StaticDatabases } = require("../db/utils")
2021-04-11 22:35:55 +12:00
2021-04-29 01:28:25 +12:00
function makeRegex() {
}
module.exports = (noAuthPatterns = []) => {
const regex = new RegExp(noAuthPatterns.join("|"))
return async (ctx, next) => {
// the path is not authenticated
if (regex.test(ctx.request.url)) {
return next()
2021-04-11 22:35:55 +12:00
}
try {
// check the actual user is authenticated first
const authCookie = getCookie(ctx, Cookies.Auth)
if (authCookie) {
try {
const db = database.getDB(StaticDatabases.GLOBAL.name)
const user = await db.get(authCookie.userId)
delete user.password
ctx.isAuthenticated = true
ctx.user = user
} catch (err) {
// remove the cookie as the use does not exist anymore
clearCookie(ctx, Cookies.Auth)
}
}
// be explicit
if (ctx.isAuthenticated !== true) {
ctx.isAuthenticated = false
}
2021-04-11 22:35:55 +12:00
return next()
} catch (err) {
ctx.throw(err.status || 403, err)
}
2021-04-11 22:35:55 +12:00
}
}