1
0
Fork 0
mirror of synced 2024-10-01 01:28:51 +13:00
budibase/packages/server/src/middleware/authenticated.js

74 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-05-07 21:53:34 +12:00
const jwt = require("jsonwebtoken")
2020-05-15 02:12:30 +12:00
const STATUS_CODES = require("../utilities/statusCodes")
const { getRole, getBuiltinRoles } = require("../utilities/security/roles")
const { AuthTypes } = require("../constants")
const {
getAppId,
getCookieName,
clearCookie,
setCookie,
isClient,
} = require("../utilities")
module.exports = async (ctx, next) => {
2020-05-18 22:53:04 +12:00
if (ctx.path === "/_builder") {
2020-05-15 02:12:30 +12:00
await next()
2020-05-08 01:04:32 +12: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"))
const builtinRoles = getBuiltinRoles()
if (appId && cookieAppId !== appId) {
setCookie(ctx, appId, "currentapp")
} else if (cookieAppId) {
appId = cookieAppId
}
let token, authType
if (!isClient(ctx)) {
token = ctx.cookies.get(getCookieName())
authType = AuthTypes.BUILDER
2021-01-30 02:14:36 +13:00
}
2021-03-10 06:31:52 +13:00
2021-01-30 02:14:36 +13:00
if (!token && appId) {
token = ctx.cookies.get(getCookieName(appId))
authType = AuthTypes.APP
}
if (!token) {
ctx.auth.authenticated = false
ctx.appId = appId
ctx.user = {
appId,
role: builtinRoles.PUBLIC,
}
2020-05-07 21:53:34 +12:00
await next()
return
}
try {
ctx.auth.authenticated = authType
const jwtPayload = jwt.verify(token, ctx.config.jwtSecret)
ctx.appId = appId
ctx.auth.apiKey = jwtPayload.apiKey
2020-05-28 04:23:01 +12:00
ctx.user = {
...jwtPayload,
appId: appId,
role: await getRole(appId, jwtPayload.roleId),
2020-05-28 04:23:01 +12:00
}
} catch (err) {
2021-03-10 06:31:52 +13:00
console.log(err)
if (authType === AuthTypes.BUILDER) {
clearCookie(ctx)
ctx.status = 200
return
} else {
ctx.throw(err.status || STATUS_CODES.FORBIDDEN, err.text)
}
}
2020-05-07 21:53:34 +12:00
await next()
}