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

31 lines
851 B
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 } = require("../utils")
2021-04-22 22:45:22 +12:00
const { StaticDatabases } = require("../db/utils")
2021-04-11 22:35:55 +12:00
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) {
2021-04-22 22:45:22 +12:00
const db = database.getDB(StaticDatabases.GLOBAL.name)
const user = await db.get(authCookie.userId)
delete user.password
ctx.isAuthenticated = true
2021-04-22 22:45:22 +12:00
ctx.user = user
}
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
}
}