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

91 lines
2.3 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")
2020-05-28 04:23:01 +12:00
const accessLevelController = require("../api/controllers/accesslevel")
const { BUILTIN_LEVEL_ID_ARRAY } = require("../utilities/security/accessLevels")
const env = require("../environment")
const { AuthTypes } = require("../constants")
const { getAppId, getCookieName, setCookie } = 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"))
if (appId && cookieAppId !== appId) {
setCookie(ctx, "currentapp", appId)
} else if (cookieAppId) {
appId = cookieAppId
}
const appToken = ctx.cookies.get(getCookieName(appId))
const builderToken = ctx.cookies.get(getCookieName())
let token
// if running locally in the builder itself
if (!env.CLOUD && !appToken) {
token = builderToken
ctx.auth.authenticated = AuthTypes.BUILDER
} else {
token = appToken
ctx.auth.authenticated = AuthTypes.APP
}
if (!token) {
ctx.auth.authenticated = false
ctx.appId = appId
ctx.user = {
appId,
}
2020-05-07 21:53:34 +12:00
await next()
return
}
try {
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,
accessLevel: await getAccessLevel(appId, jwtPayload.accessLevelId),
2020-05-28 04:23:01 +12:00
}
} catch (err) {
2020-05-08 01:04:32 +12:00
ctx.throw(err.status || STATUS_CODES.FORBIDDEN, err.text)
}
2020-05-07 21:53:34 +12:00
await next()
}
2020-05-28 04:23:01 +12:00
2020-06-30 05:57:17 +12:00
/**
2020-07-08 08:29:20 +12:00
* Return the full access level object either from constants
2020-06-30 05:57:17 +12:00
* or the database based on the access level ID passed.
2020-07-08 08:29:20 +12:00
*
* @param {*} appId - appId of the user
2020-07-08 08:29:20 +12:00
* @param {*} accessLevelId - the id of the users access level
2020-06-30 05:57:17 +12:00
*/
const getAccessLevel = async (appId, accessLevelId) => {
if (BUILTIN_LEVEL_ID_ARRAY.indexOf(accessLevelId) !== -1) {
2020-05-28 04:23:01 +12:00
return {
_id: accessLevelId,
name: accessLevelId,
permissions: [],
}
}
const findAccessContext = {
params: {
levelId: accessLevelId,
2020-06-19 07:41:37 +12:00
},
user: {
appId,
2020-05-28 04:23:01 +12:00
},
}
await accessLevelController.find(findAccessContext)
return findAccessContext.body
}