2020-05-07 11:53:34 +02:00
|
|
|
const jwt = require("jsonwebtoken")
|
2020-05-14 16:12:30 +02:00
|
|
|
const STATUS_CODES = require("../utilities/statusCodes")
|
|
|
|
const env = require("../environment")
|
2020-05-27 18:23:01 +02:00
|
|
|
const accessLevelController = require("../api/controllers/accesslevel")
|
|
|
|
const {
|
|
|
|
ADMIN_LEVEL_ID,
|
|
|
|
POWERUSER_LEVEL_ID,
|
|
|
|
} = require("../utilities/accessLevels")
|
2020-04-23 15:37:08 +02:00
|
|
|
|
|
|
|
module.exports = async (ctx, next) => {
|
2020-05-18 12:53:04 +02:00
|
|
|
if (ctx.path === "/_builder") {
|
2020-05-14 16:12:30 +02:00
|
|
|
await next()
|
2020-05-07 15:04:32 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-06-03 18:05:36 +02:00
|
|
|
const appToken = ctx.cookies.get("budibase:token")
|
|
|
|
const builderToken = ctx.cookies.get("builder:token")
|
|
|
|
const isBuilderAgent = ctx.headers["user-agent"] === "Budibase Builder"
|
|
|
|
|
|
|
|
// all admin api access should auth with buildertoken and 'Budibase Builder user agent
|
|
|
|
const shouldAuthAsBuilder = isBuilderAgent && builderToken
|
|
|
|
|
|
|
|
if (shouldAuthAsBuilder) {
|
|
|
|
if (builderToken === env.ADMIN_SECRET) {
|
|
|
|
ctx.isAuthenticated = true
|
|
|
|
ctx.isBuilder = true
|
|
|
|
} else {
|
|
|
|
ctx.isAuthenticated = false
|
|
|
|
ctx.isBuilder = false
|
|
|
|
}
|
|
|
|
|
2020-05-18 07:40:29 +02:00
|
|
|
await next()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-06-03 18:05:36 +02:00
|
|
|
if (!appToken) {
|
2020-05-04 18:13:57 +02:00
|
|
|
ctx.isAuthenticated = false
|
2020-05-07 11:53:34 +02:00
|
|
|
await next()
|
|
|
|
return
|
|
|
|
}
|
2020-04-23 15:37:08 +02:00
|
|
|
|
|
|
|
try {
|
2020-06-03 18:05:36 +02:00
|
|
|
const jwtPayload = jwt.verify(appToken, ctx.config.jwtSecret)
|
2020-05-27 18:23:01 +02:00
|
|
|
|
|
|
|
ctx.user = {
|
|
|
|
...jwtPayload,
|
|
|
|
accessLevel: await getAccessLevel(
|
|
|
|
jwtPayload.instanceId,
|
|
|
|
jwtPayload.accessLevelId
|
|
|
|
),
|
|
|
|
}
|
2020-05-07 11:53:34 +02:00
|
|
|
ctx.isAuthenticated = true
|
2020-04-23 15:37:08 +02:00
|
|
|
} catch (err) {
|
2020-05-07 15:04:32 +02:00
|
|
|
ctx.throw(err.status || STATUS_CODES.FORBIDDEN, err.text)
|
2020-04-23 15:37:08 +02:00
|
|
|
}
|
|
|
|
|
2020-05-07 11:53:34 +02:00
|
|
|
await next()
|
|
|
|
}
|
2020-05-27 18:23:01 +02:00
|
|
|
|
|
|
|
const getAccessLevel = async (instanceId, accessLevelId) => {
|
|
|
|
if (
|
|
|
|
accessLevelId === POWERUSER_LEVEL_ID ||
|
|
|
|
accessLevelId === ADMIN_LEVEL_ID
|
|
|
|
) {
|
|
|
|
return {
|
|
|
|
_id: accessLevelId,
|
|
|
|
name: accessLevelId,
|
|
|
|
permissions: [],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const findAccessContext = {
|
|
|
|
params: {
|
|
|
|
levelId: accessLevelId,
|
|
|
|
instanceId,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
await accessLevelController.find(findAccessContext)
|
|
|
|
return findAccessContext.body
|
|
|
|
}
|