budibase/packages/server/src/middleware/authenticated.js

61 lines
1.5 KiB
JavaScript
Raw Normal View History

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")
2020-11-19 21:19:18 +01:00
const {
getAccessLevel,
BUILTIN_LEVELS,
} = require("../utilities/security/accessLevels")
const { AuthTypes } = require("../constants")
const { getAppId, getCookieName, setCookie, isClient } = require("../utilities")
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
}
// do everything we can to make sure the appId is held correctly
// we hold it in state as a
let appId = getAppId(ctx)
const cookieAppId = ctx.cookies.get(getCookieName("currentapp"))
if (appId && cookieAppId !== appId) {
setCookie(ctx, "currentapp", appId)
} else if (cookieAppId) {
appId = cookieAppId
}
let token
if (isClient(ctx)) {
ctx.auth.authenticated = AuthTypes.APP
token = ctx.cookies.get(getCookieName(appId))
} else {
ctx.auth.authenticated = AuthTypes.BUILDER
token = ctx.cookies.get(getCookieName())
}
if (!token) {
ctx.auth.authenticated = false
ctx.appId = appId
ctx.user = {
appId,
accessLevel: BUILTIN_LEVELS.PUBLIC,
}
2020-05-07 11:53:34 +02:00
await next()
return
}
try {
const jwtPayload = jwt.verify(token, ctx.config.jwtSecret)
ctx.appId = appId
ctx.auth.apiKey = jwtPayload.apiKey
2020-05-27 18:23:01 +02:00
ctx.user = {
...jwtPayload,
appId: appId,
accessLevel: await getAccessLevel(appId, jwtPayload.accessLevelId),
2020-05-27 18:23:01 +02:00
}
} catch (err) {
2020-05-07 15:04:32 +02:00
ctx.throw(err.status || STATUS_CODES.FORBIDDEN, err.text)
}
2020-05-07 11:53:34 +02:00
await next()
}