Merge branch 'feature/security-update' of github.com:Budibase/budibase into feature/self-hosting

This commit is contained in:
mike12345567 2020-12-03 15:01:41 +00:00
commit 3bcbb5f27c
35 changed files with 551 additions and 541 deletions

View File

@ -111,7 +111,7 @@ Cypress.Commands.add("addRow", values => {
})
})
Cypress.Commands.add("createUser", (username, password, accessLevel) => {
Cypress.Commands.add("createUser", (username, password, role) => {
// Create User
cy.contains("Users").click()
@ -126,7 +126,7 @@ Cypress.Commands.add("createUser", (username, password, accessLevel) => {
.type(username)
cy.get("select")
.first()
.select(accessLevel)
.select(role)
// Save
cy.get(".buttons")

View File

@ -18,7 +18,7 @@ export class Screen extends BaseStructure {
},
routing: {
route: "",
accessLevelId: "",
roleId: "",
},
name: "screen-id",
}

View File

@ -56,9 +56,7 @@
password: string().required(
"Please enter a password for your first user."
),
accessLevelId: string().required(
"You need to select an access level for your user."
),
roleId: string().required("You need to select a role for your user."),
},
]
@ -79,9 +77,7 @@
if (hasKey) {
validationSchemas.shift()
validationSchemas = validationSchemas
steps.shift()
steps = steps
}
// Handles form navigation
@ -167,7 +163,7 @@
name: $createAppStore.values.username,
username: $createAppStore.values.username,
password: $createAppStore.values.password,
accessLevelId: $createAppStore.values.accessLevelId,
roleId: $createAppStore.values.roleId,
}
const userResp = await api.post(`/api/users`, user)
const json = await userResp.json()

View File

@ -21,7 +21,7 @@
placeholder="Password"
type="password"
error={blurred.password && validationErrors.password} />
<Select label="Access Level" secondary name="accessLevelId">
<Select label="Role" secondary name="roleId">
<option value="ADMIN">Admin</option>
<option value="POWER_USER">Power User</option>
</Select>

View File

@ -70,7 +70,7 @@
draftScreen.props._instanceName = name
draftScreen.props._component = baseComponent
// TODO: need to fix this up correctly
draftScreen.routing = { route, accessLevelId: "ADMIN" }
draftScreen.routing = { route, roleId: "ADMIN" }
await store.actions.screens.create(draftScreen)
if (createLink) {

View File

@ -3,7 +3,7 @@ export const TableNames = {
}
// fields on the user table that cannot be edited
export const UNEDITABLE_USER_FIELDS = ["username", "password", "accessLevelId"]
export const UNEDITABLE_USER_FIELDS = ["username", "password", "roleId"]
export const DEFAULT_PAGES_OBJECT = {
main: {

View File

@ -52,9 +52,9 @@
{
"type": "node",
"request": "launch",
"name": "Jest - Access Levels",
"name": "Jest - Roles",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": ["accesslevel.spec", "--runInBand"],
"args": ["role.spec", "--runInBand"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true,

View File

@ -1,52 +0,0 @@
const CouchDB = require("../../db")
const {
BUILTIN_LEVELS,
AccessLevel,
getAccessLevel,
} = require("../../utilities/security/accessLevels")
const {
generateAccessLevelID,
getAccessLevelParams,
} = require("../../db/utils")
exports.fetch = async function(ctx) {
const db = new CouchDB(ctx.user.appId)
const body = await db.allDocs(
getAccessLevelParams(null, {
include_docs: true,
})
)
const customAccessLevels = body.rows.map(row => row.doc)
const staticAccessLevels = [BUILTIN_LEVELS.ADMIN, BUILTIN_LEVELS.POWER]
ctx.body = [...staticAccessLevels, ...customAccessLevels]
}
exports.find = async function(ctx) {
ctx.body = await getAccessLevel(ctx.user.appId, ctx.params.levelId)
}
exports.save = async function(ctx) {
const db = new CouchDB(ctx.user.appId)
let id = ctx.request.body._id || generateAccessLevelID()
const level = new AccessLevel(
id,
ctx.request.body.name,
ctx.request.body.inherits
)
if (ctx.request.body._rev) {
level._rev = ctx.request.body._rev
}
const result = await db.put(level)
level._rev = result.rev
ctx.body = level
ctx.message = `Access Level '${level.name}' created successfully.`
}
exports.destroy = async function(ctx) {
const db = new CouchDB(ctx.user.appId)
await db.remove(ctx.params.levelId, ctx.params.rev)
ctx.message = `Access Level ${ctx.params.id} deleted successfully`
ctx.status = 200
}

View File

@ -19,7 +19,7 @@ const {
generatePageID,
generateScreenID,
} = require("../../db/utils")
const { BUILTIN_LEVEL_IDS } = require("../../utilities/security/accessLevels")
const { BUILTIN_ROLE_IDS } = require("../../utilities/security/roles")
const {
downloadExtractComponentLibraries,
} = require("../../utilities/createAppPackage")
@ -94,12 +94,12 @@ exports.fetchAppDefinition = async function(ctx) {
const db = new CouchDB(ctx.params.appId)
// TODO: need to get rid of pages here, they shouldn't be needed anymore
const { mainPage, unauthPage } = await getMainAndUnauthPage(db)
const userAccessLevelId =
!ctx.user.accessLevel || !ctx.user.accessLevel._id
? BUILTIN_LEVEL_IDS.PUBLIC
: ctx.user.accessLevel._id
const userRoleId =
!ctx.user.role || !ctx.user.role._id
? BUILTIN_ROLE_IDS.PUBLIC
: ctx.user.role._id
const correctPage =
userAccessLevelId === BUILTIN_LEVEL_IDS.PUBLIC ? unauthPage : mainPage
userRoleId === BUILTIN_ROLE_IDS.PUBLIC ? unauthPage : mainPage
const screens = (
await db.allDocs(
getScreenParams(correctPage._id, {
@ -107,7 +107,7 @@ exports.fetchAppDefinition = async function(ctx) {
})
)
).rows.map(row => row.doc)
// TODO: need to handle access control here, limit screens to user access level
// TODO: need to handle access control here, limit screens to user role
ctx.body = {
page: correctPage,
screens: screens,

View File

@ -32,9 +32,8 @@ exports.authenticate = async ctx => {
if (await bcrypt.compare(password, dbUser.password)) {
const payload = {
userId: dbUser._id,
accessLevelId: dbUser.accessLevelId,
roleId: dbUser.roleId,
version: app.version,
permissions: dbUser.permissions || [],
}
// if in cloud add the user api key
if (env.CLOUD) {

View File

@ -0,0 +1,6 @@
const { BUILTIN_PERMISSIONS } = require("../../utilities/security/permissions")
exports.fetch = async function(ctx) {
// TODO: need to build out custom permissions
ctx.body = Object.values(BUILTIN_PERMISSIONS)
}

View File

@ -0,0 +1,55 @@
const CouchDB = require("../../db")
const {
BUILTIN_ROLES,
Role,
getRole,
} = require("../../utilities/security/roles")
const { generateRoleID, getRoleParams } = require("../../db/utils")
exports.fetch = async function(ctx) {
const db = new CouchDB(ctx.user.appId)
const body = await db.allDocs(
getRoleParams(null, {
include_docs: true,
})
)
const customRoles = body.rows.map(row => row.doc)
// exclude internal roles like builder
const staticRoles = [
BUILTIN_ROLES.ADMIN,
BUILTIN_ROLES.POWER,
BUILTIN_ROLES.BASIC,
BUILTIN_ROLES.PUBLIC,
]
ctx.body = [...staticRoles, ...customRoles]
}
exports.find = async function(ctx) {
ctx.body = await getRole(ctx.user.appId, ctx.params.roleId)
}
exports.save = async function(ctx) {
const db = new CouchDB(ctx.user.appId)
let { _id, name, inherits, permissionId } = ctx.request.body
if (!_id) {
_id = generateRoleID()
}
const role = new Role(_id, name)
.addPermission(permissionId)
.addInheritance(inherits)
if (ctx.request.body._rev) {
role._rev = ctx.request.body._rev
}
const result = await db.put(role)
role._rev = result.rev
ctx.body = role
ctx.message = `Role '${role.name}' created successfully.`
}
exports.destroy = async function(ctx) {
const db = new CouchDB(ctx.user.appId)
await db.remove(ctx.params.roleId, ctx.params.rev)
ctx.message = `Role ${ctx.params.id} deleted successfully`
ctx.status = 200
}

View File

@ -1,8 +1,8 @@
const { getRoutingInfo } = require("../../utilities/routing")
const {
getUserAccessLevelHierarchy,
BUILTIN_LEVEL_IDS,
} = require("../../utilities/security/accessLevels")
getUserRoleHierarchy,
BUILTIN_ROLE_IDS,
} = require("../../utilities/security/roles")
const URL_SEPARATOR = "/"
@ -33,15 +33,15 @@ Routing.prototype.getScreensProp = function(fullpath) {
return this.json[topLevel].subpaths[fullpath].screens
}
Routing.prototype.addScreenId = function(fullpath, accessLevel, screenId) {
this.getScreensProp(fullpath)[accessLevel] = screenId
Routing.prototype.addScreenId = function(fullpath, roleId, screenId) {
this.getScreensProp(fullpath)[roleId] = screenId
}
/**
* Gets the full routing structure by querying the routing view and processing the result into the tree.
* @param {string} appId The application to produce the routing structure for.
* @returns {Promise<object>} The routing structure, this is the full structure designed for use in the builder,
* if the client routing is required then the updateRoutingStructureForUserLevel should be used.
* if the client routing is required then the updateRoutingStructureForUserRole should be used.
*/
async function getRoutingStructure(appId) {
const screenRoutes = await getRoutingInfo(appId)
@ -49,8 +49,8 @@ async function getRoutingStructure(appId) {
for (let screenRoute of screenRoutes) {
let fullpath = screenRoute.routing.route
const accessLevel = screenRoute.routing.accessLevelId
routing.addScreenId(fullpath, accessLevel, screenRoute.id)
const roleId = screenRoute.routing.roleId
routing.addScreenId(fullpath, roleId, screenRoute.id)
}
return { routes: routing.json }
@ -62,29 +62,26 @@ exports.fetch = async ctx => {
exports.clientFetch = async ctx => {
const routing = await getRoutingStructure(ctx.appId)
let accessLevelId = ctx.user.accessLevel._id
let roleId = ctx.user.role._id
// builder is a special case, always return the full routing structure
if (accessLevelId === BUILTIN_LEVEL_IDS.BUILDER) {
accessLevelId = BUILTIN_LEVEL_IDS.ADMIN
if (roleId === BUILTIN_ROLE_IDS.BUILDER) {
roleId = BUILTIN_ROLE_IDS.ADMIN
}
const accessLevelIds = await getUserAccessLevelHierarchy(
ctx.appId,
accessLevelId
)
const roleIds = await getUserRoleHierarchy(ctx.appId, roleId)
for (let topLevel of Object.values(routing.routes)) {
for (let subpathKey of Object.keys(topLevel.subpaths)) {
let found = false
const subpath = topLevel.subpaths[subpathKey]
const accessLevelOptions = Object.keys(subpath.screens)
if (accessLevelOptions.length === 1 && !accessLevelOptions[0]) {
subpath.screenId = subpath.screens[accessLevelOptions[0]]
subpath.accessLevelId = BUILTIN_LEVEL_IDS.BASIC
const roleOptions = Object.keys(subpath.screens)
if (roleOptions.length === 1 && !roleOptions[0]) {
subpath.screenId = subpath.screens[roleOptions[0]]
subpath.roleId = BUILTIN_ROLE_IDS.BASIC
found = true
} else {
for (let levelId of accessLevelIds) {
if (accessLevelOptions.indexOf(levelId) !== -1) {
subpath.screenId = subpath.screens[levelId]
subpath.accessLevelId = levelId
for (let roleId of roleIds) {
if (roleOptions.indexOf(roleId) !== -1) {
subpath.screenId = subpath.screens[roleId]
subpath.roleId = roleId
found = true
break
}

View File

@ -1,6 +1,6 @@
const CouchDB = require("../../db")
const { getScreenParams, generateScreenID } = require("../../db/utils")
const { AccessController } = require("../../utilities/security/accessLevels")
const { AccessController } = require("../../utilities/security/roles")
exports.fetch = async ctx => {
const appId = ctx.user.appId
@ -16,7 +16,7 @@ exports.fetch = async ctx => {
ctx.body = await new AccessController(appId).checkScreensAccess(
screens,
ctx.user.accessLevel._id
ctx.user.role._id
)
}
@ -32,7 +32,7 @@ exports.find = async ctx => {
ctx.body = await new AccessController(appId).checkScreensAccess(
screens,
ctx.user.accessLevel._id
ctx.user.role._id
)
}

View File

@ -1,12 +1,7 @@
const CouchDB = require("../../db")
const bcrypt = require("../../utilities/bcrypt")
const { generateUserID, getUserParams, ViewNames } = require("../../db/utils")
const {
BUILTIN_LEVEL_ID_ARRAY,
} = require("../../utilities/security/accessLevels")
const {
BUILTIN_PERMISSION_NAMES,
} = require("../../utilities/security/permissions")
const { getRole } = require("../../utilities/security/roles")
exports.fetch = async function(ctx) {
const database = new CouchDB(ctx.user.appId)
@ -20,21 +15,15 @@ exports.fetch = async function(ctx) {
exports.create = async function(ctx) {
const db = new CouchDB(ctx.user.appId)
const {
username,
password,
name,
accessLevelId,
permissions,
} = ctx.request.body
const { username, password, name, roleId } = ctx.request.body
if (!username || !password) {
ctx.throw(400, "Username and Password Required.")
}
const accessLevel = await checkAccessLevel(db, accessLevelId)
const role = await getRole(ctx.user.appId, roleId)
if (!accessLevel) ctx.throw(400, "Invalid Access Level")
if (!role) ctx.throw(400, "Invalid Role")
const user = {
_id: generateUserID(username),
@ -42,8 +31,7 @@ exports.create = async function(ctx) {
password: await bcrypt.hash(password),
name: name || username,
type: "user",
accessLevelId,
permissions: permissions || [BUILTIN_PERMISSION_NAMES.POWER],
roleId,
tableId: ViewNames.USERS,
}
@ -96,15 +84,3 @@ exports.find = async function(ctx) {
_rev: user._rev,
}
}
const checkAccessLevel = async (db, accessLevelId) => {
if (!accessLevelId) return
if (BUILTIN_LEVEL_ID_ARRAY.indexOf(accessLevelId) !== -1) {
return {
_id: accessLevelId,
name: accessLevelId,
permissions: [],
}
}
return await db.get(accessLevelId)
}

View File

@ -1,18 +0,0 @@
const Router = require("@koa/router")
const controller = require("../controllers/accesslevel")
const authorized = require("../../middleware/authorized")
const { BUILDER } = require("../../utilities/security/permissions")
const router = Router()
router
.post("/api/accesslevels", authorized(BUILDER), controller.save)
.get("/api/accesslevels", authorized(BUILDER), controller.fetch)
.get("/api/accesslevels/:levelId", authorized(BUILDER), controller.find)
.delete(
"/api/accesslevels/:levelId/:rev",
authorized(BUILDER),
controller.destroy
)
module.exports = router

View File

@ -10,12 +10,13 @@ const staticRoutes = require("./static")
const componentRoutes = require("./component")
const automationRoutes = require("./automation")
const webhookRoutes = require("./webhook")
const accesslevelRoutes = require("./accesslevel")
const roleRoutes = require("./role")
const deployRoutes = require("./deploy")
const apiKeysRoutes = require("./apikeys")
const templatesRoutes = require("./templates")
const analyticsRoutes = require("./analytics")
const routingRoutes = require("./routing")
const permissionRoutes = require("./permission")
exports.mainRoutes = [
deployRoutes,
@ -26,12 +27,13 @@ exports.mainRoutes = [
automationRoutes,
viewRoutes,
componentRoutes,
accesslevelRoutes,
roleRoutes,
apiKeysRoutes,
templatesRoutes,
analyticsRoutes,
webhookRoutes,
routingRoutes,
permissionRoutes,
// these need to be handled last as they still use /api/:tableId
// this could be breaking as koa may recognise other routes as this
tableRoutes,

View File

@ -0,0 +1,10 @@
const Router = require("@koa/router")
const controller = require("../controllers/permission")
const authorized = require("../../middleware/authorized")
const { BUILDER } = require("../../utilities/security/permissions")
const router = Router()
router.get("/api/permissions", authorized(BUILDER), controller.fetch)
module.exports = router

View File

@ -0,0 +1,30 @@
const Router = require("@koa/router")
const controller = require("../controllers/role")
const authorized = require("../../middleware/authorized")
const { BUILDER } = require("../../utilities/security/permissions")
const Joi = require("joi")
const joiValidator = require("../../middleware/joi-validator")
const {
BUILTIN_PERMISSION_IDS,
} = require("../../utilities/security/permissions")
const router = Router()
function generateValidator() {
// prettier-ignore
return joiValidator.body(Joi.object({
_id: Joi.string().optional(),
_rev: Joi.string().optional(),
name: Joi.string().required(),
permissionId: Joi.string().valid(...Object.values(BUILTIN_PERMISSION_IDS)).required(),
inherits: Joi.string().optional(),
}).unknown(true))
}
router
.post("/api/roles", authorized(BUILDER), generateValidator(), controller.save)
.get("/api/roles", authorized(BUILDER), controller.fetch)
.get("/api/roles/:roleId", authorized(BUILDER), controller.find)
.delete("/api/roles/:roleId/:rev", authorized(BUILDER), controller.destroy)
module.exports = router

View File

@ -5,9 +5,10 @@ const controller = require("../controllers/routing")
const router = Router()
// gets the full structure, not just the correct screen ID for your access level
router
// gets correct structure for user role
.get("/api/routing/client", controller.clientFetch)
// gets the full structure, not just the correct screen ID for user role
.get("/api/routing", authorized(BUILDER), controller.fetch)
module.exports = router

View File

@ -14,7 +14,7 @@ function generateSaveValidation() {
name: Joi.string().required(),
routing: Joi.object({
route: Joi.string().required(),
accessLevelId: Joi.string().required().allow(""),
roleId: Joi.string().required().allow(""),
}).required().unknown(true),
props: Joi.object({
_id: Joi.string().required(),

View File

@ -1,110 +0,0 @@
const {
createApplication,
createTable,
createView,
supertest,
defaultHeaders
} = require("./couchTestUtils")
const {
BUILTIN_LEVEL_IDS,
} = require("../../../utilities/security/accessLevels")
const accessLevelBody = { name: "user", inherits: BUILTIN_LEVEL_IDS.BASIC }
describe("/accesslevels", () => {
let server
let request
let appId
let table
let view
beforeAll(async () => {
({ request, server } = await supertest())
});
afterAll(() => {
server.close()
})
beforeEach(async () => {
let app = await createApplication(request)
appId = app.instance._id
table = await createTable(request, appId)
view = await createView(request, appId, table._id)
})
describe("create", () => {
it("returns a success message when level is successfully created", async () => {
const res = await request
.post(`/api/accesslevels`)
.send(accessLevelBody)
.set(defaultHeaders(appId))
.expect('Content-Type', /json/)
.expect(200)
expect(res.res.statusMessage).toEqual("Access Level 'user' created successfully.")
expect(res.body._id).toBeDefined()
expect(res.body._rev).toBeDefined()
})
});
describe("fetch", () => {
it("should list custom levels, plus 2 default levels", async () => {
const createRes = await request
.post(`/api/accesslevels`)
.send(accessLevelBody)
.set(defaultHeaders(appId))
.expect('Content-Type', /json/)
.expect(200)
const customLevel = createRes.body
const res = await request
.get(`/api/accesslevels`)
.set(defaultHeaders(appId))
.expect('Content-Type', /json/)
.expect(200)
expect(res.body.length).toBe(3)
const adminLevel = res.body.find(r => r._id === BUILTIN_LEVEL_IDS.ADMIN)
expect(adminLevel.inherits).toEqual(BUILTIN_LEVEL_IDS.POWER)
expect(adminLevel).toBeDefined()
const powerUserLevel = res.body.find(r => r._id === BUILTIN_LEVEL_IDS.POWER)
expect(powerUserLevel.inherits).toEqual(BUILTIN_LEVEL_IDS.BASIC)
expect(powerUserLevel).toBeDefined()
const customLevelFetched = res.body.find(r => r._id === customLevel._id)
expect(customLevelFetched.inherits).toEqual(BUILTIN_LEVEL_IDS.BASIC)
expect(customLevelFetched).toBeDefined()
})
});
describe("destroy", () => {
it("should delete custom access level", async () => {
const createRes = await request
.post(`/api/accesslevels`)
.send({ name: "user" })
.set(defaultHeaders(appId))
.expect('Content-Type', /json/)
.expect(200)
const customLevel = createRes.body
await request
.delete(`/api/accesslevels/${customLevel._id}/${customLevel._rev}`)
.set(defaultHeaders(appId))
.expect(200)
await request
.get(`/api/accesslevels/${customLevel._id}`)
.set(defaultHeaders(appId))
.expect(404)
})
})
});

View File

@ -1,11 +1,6 @@
const CouchDB = require("../../../db")
const supertest = require("supertest")
const {
BUILTIN_LEVEL_IDS,
} = require("../../../utilities/security/accessLevels")
const {
BUILTIN_PERMISSION_NAMES,
} = require("../../../utilities/security/permissions")
const { BUILTIN_ROLE_IDS } = require("../../../utilities/security/roles")
const packageJson = require("../../../../package")
const jwt = require("jsonwebtoken")
const env = require("../../../environment")
@ -26,7 +21,7 @@ exports.supertest = async () => {
exports.defaultHeaders = appId => {
const builderUser = {
userId: "BUILDER",
accessLevelId: BUILTIN_LEVEL_IDS.BUILDER,
roleId: BUILTIN_ROLE_IDS.BUILDER,
}
const builderToken = jwt.sign(builderUser, env.JWT_SECRET)
@ -128,54 +123,12 @@ exports.createUser = async (
name: "Bill",
username,
password,
accessLevelId: BUILTIN_LEVEL_IDS.POWER,
roleId: BUILTIN_ROLE_IDS.POWER,
})
return res.body
}
const createUserWithOnePermission = async (request, appId, permName) => {
let permissions = [permName]
return await createUserWithPermissions(
request,
appId,
permissions,
"onePermOnlyUser"
)
}
const createUserWithAdminPermissions = async (request, appId) => {
let permissions = [BUILTIN_PERMISSION_NAMES.ADMIN]
return await createUserWithPermissions(
request,
appId,
permissions,
"adminUser"
)
}
const createUserWithAllPermissionExceptOne = async (
request,
appId,
permName
) => {
let permissions = [permName]
return await createUserWithPermissions(
request,
appId,
permissions,
"allPermsExceptOneUser"
)
}
const createUserWithPermissions = async (
request,
appId,
permissions,
username
) => {
const createUserWithRole = async (request, appId, roleId, username) => {
const password = `password_${username}`
await request
.post(`/api/users`)
@ -184,13 +137,12 @@ const createUserWithPermissions = async (
name: username,
username,
password,
accessLevelId: BUILTIN_LEVEL_IDS.POWER,
permissions,
roleId,
})
const anonUser = {
userId: "ANON",
accessLevelId: BUILTIN_LEVEL_IDS.PUBLIC,
roleId: BUILTIN_ROLE_IDS.PUBLIC,
appId: appId,
version: packageJson.version,
}
@ -218,23 +170,29 @@ exports.testPermissionsForEndpoint = async ({
url,
body,
appId,
permName1,
permName2,
passRole,
failRole,
}) => {
const headers = await createUserWithOnePermission(request, appId, permName1)
await createRequest(request, method, url, body)
.set(headers)
.expect(200)
const noPermsHeaders = await createUserWithAllPermissionExceptOne(
const passHeader = await createUserWithRole(
request,
appId,
permName2
passRole,
"passUser"
)
await createRequest(request, method, url, body)
.set(noPermsHeaders)
.set(passHeader)
.expect(200)
const failHeader = await createUserWithRole(
request,
appId,
failRole,
"failUser"
)
await createRequest(request, method, url, body)
.set(failHeader)
.expect(403)
}
@ -245,7 +203,12 @@ exports.builderEndpointShouldBlockNormalUsers = async ({
body,
appId,
}) => {
const headers = await createUserWithAdminPermissions(request, appId)
const headers = await createUserWithRole(
request,
appId,
BUILTIN_ROLE_IDS.BASIC,
"basicUser"
)
await createRequest(request, method, url, body)
.set(headers)

View File

@ -0,0 +1,114 @@
const {
createApplication,
createTable,
createView,
supertest,
defaultHeaders
} = require("./couchTestUtils")
const {
BUILTIN_ROLE_IDS,
} = require("../../../utilities/security/roles")
const { BUILTIN_PERMISSION_IDS } = require("../../../utilities/security/permissions")
const roleBody = { name: "NewRole", inherits: BUILTIN_ROLE_IDS.BASIC, permissionId: BUILTIN_PERMISSION_IDS.READ_ONLY }
describe("/roles", () => {
let server
let request
let appId
let table
let view
beforeAll(async () => {
({ request, server } = await supertest())
});
afterAll(() => {
server.close()
})
beforeEach(async () => {
let app = await createApplication(request)
appId = app.instance._id
table = await createTable(request, appId)
view = await createView(request, appId, table._id)
})
describe("create", () => {
it("returns a success message when role is successfully created", async () => {
const res = await request
.post(`/api/roles`)
.send(roleBody)
.set(defaultHeaders(appId))
.expect('Content-Type', /json/)
.expect(200)
expect(res.res.statusMessage).toEqual("Role 'NewRole' created successfully.")
expect(res.body._id).toBeDefined()
expect(res.body._rev).toBeDefined()
})
});
describe("fetch", () => {
it("should list custom roles, plus 2 default roles", async () => {
const createRes = await request
.post(`/api/roles`)
.send(roleBody)
.set(defaultHeaders(appId))
.expect('Content-Type', /json/)
.expect(200)
const customRole = createRes.body
const res = await request
.get(`/api/roles`)
.set(defaultHeaders(appId))
.expect('Content-Type', /json/)
.expect(200)
expect(res.body.length).toBe(3)
const adminRole = res.body.find(r => r._id === BUILTIN_ROLE_IDS.ADMIN)
expect(adminRole).toBeDefined()
expect(adminRole.inherits).toEqual(BUILTIN_ROLE_IDS.POWER)
expect(adminRole.permissionId).toEqual(BUILTIN_PERMISSION_IDS.ADMIN)
const powerUserRole = res.body.find(r => r._id === BUILTIN_ROLE_IDS.POWER)
expect(powerUserRole).toBeDefined()
expect(powerUserRole.inherits).toEqual(BUILTIN_ROLE_IDS.BASIC)
expect(powerUserRole.permissionId).toEqual(BUILTIN_PERMISSION_IDS.POWER)
const customRoleFetched = res.body.find(r => r._id === customRole._id)
expect(customRoleFetched).toBeDefined()
expect(customRoleFetched.inherits).toEqual(BUILTIN_ROLE_IDS.BASIC)
expect(customRoleFetched.permissionId).toEqual(BUILTIN_PERMISSION_IDS.READ_ONLY)
})
});
describe("destroy", () => {
it("should delete custom roles", async () => {
const createRes = await request
.post(`/api/roles`)
.send({ name: "user", permissionId: BUILTIN_PERMISSION_IDS.READ_ONLY })
.set(defaultHeaders(appId))
.expect('Content-Type', /json/)
.expect(200)
const customRole = createRes.body
await request
.delete(`/api/roles/${customRole._id}/${customRole._rev}`)
.set(defaultHeaders(appId))
.expect(200)
await request
.get(`/api/roles/${customRole._id}`)
.set(defaultHeaders(appId))
.expect(404)
})
})
});

View File

@ -6,11 +6,15 @@ const {
testPermissionsForEndpoint,
} = require("./couchTestUtils")
const {
BUILTIN_PERMISSION_NAMES,
} = require("../../../utilities/security/permissions")
const {
BUILTIN_LEVEL_IDS,
} = require("../../../utilities/security/accessLevels")
BUILTIN_ROLE_IDS,
} = require("../../../utilities/security/roles")
const { cloneDeep } = require("lodash/fp")
const baseBody = {
name: "brandNewUser",
password: "yeeooo",
roleId: BUILTIN_ROLE_IDS.POWER
}
describe("/users", () => {
let request
@ -20,12 +24,12 @@ describe("/users", () => {
beforeAll(async () => {
({ request, server } = await supertest(server))
});
})
beforeEach(async () => {
app = await createApplication(request)
appId = app.instance._id
});
})
afterAll(() => {
server.close()
@ -54,38 +58,40 @@ describe("/users", () => {
method: "GET",
url: `/api/users`,
appId: appId,
permName1: BUILTIN_PERMISSION_NAMES.POWER,
permName2: BUILTIN_PERMISSION_NAMES.WRITE,
passRole: BUILTIN_ROLE_IDS.ADMIN,
failRole: BUILTIN_ROLE_IDS.PUBLIC,
})
})
})
describe("create", () => {
it("returns a success message when a user is successfully created", async () => {
const body = cloneDeep(baseBody)
body.username = "bill"
const res = await request
.post(`/api/users`)
.set(defaultHeaders(appId))
.send({ name: "Bill", username: "bill", password: "bills_password", accessLevelId: BUILTIN_LEVEL_IDS.POWER })
.send(body)
.expect(200)
.expect('Content-Type', /json/)
expect(res.res.statusMessage).toEqual("User created successfully.");
expect(res.res.statusMessage).toEqual("User created successfully.")
expect(res.body._id).toBeUndefined()
})
it("should apply authorization to endpoint", async () => {
const body = cloneDeep(baseBody)
body.username = "brandNewUser"
await testPermissionsForEndpoint({
request,
method: "POST",
body: { name: "brandNewUser", username: "brandNewUser", password: "yeeooo", accessLevelId: BUILTIN_LEVEL_IDS.POWER },
body,
url: `/api/users`,
appId: appId,
permName1: BUILTIN_PERMISSION_NAMES.ADMIN,
permName2: BUILTIN_PERMISSION_NAMES.POWER,
passRole: BUILTIN_ROLE_IDS.ADMIN,
failRole: BUILTIN_ROLE_IDS.PUBLIC,
})
})
});
})
})

View File

@ -1,4 +1,4 @@
const accessLevels = require("../../utilities/security/accessLevels")
const roles = require("../../utilities/security/roles")
const userController = require("../../api/controllers/user")
const env = require("../../environment")
const usage = require("../../utilities/usageQuota")
@ -11,7 +11,7 @@ module.exports.definition = {
type: "ACTION",
stepId: "CREATE_USER",
inputs: {
accessLevelId: accessLevels.BUILTIN_LEVEL_IDS.POWER,
roleId: roles.BUILTIN_ROLE_IDS.POWER,
},
schema: {
inputs: {
@ -25,14 +25,14 @@ module.exports.definition = {
customType: "password",
title: "Password",
},
accessLevelId: {
roleId: {
type: "string",
title: "Access Level",
enum: accessLevels.BUILTIN_LEVEL_ID_ARRAY,
pretty: accessLevels.BUILTIN_LEVEL_NAME_ARRAY,
title: "Role",
enum: roles.BUILTIN_ROLE_ID_ARRAY,
pretty: roles.BUILTIN_ROLE_NAME_ARRAY,
},
},
required: ["username", "password", "accessLevelId"],
required: ["username", "password", "roleId"],
},
outputs: {
properties: {
@ -59,13 +59,13 @@ module.exports.definition = {
}
module.exports.run = async function({ inputs, appId, apiKey }) {
const { username, password, accessLevelId } = inputs
const { username, password, roleId } = inputs
const ctx = {
user: {
appId: appId,
},
request: {
body: { username, password, accessLevelId },
body: { username, password, roleId },
},
}

View File

@ -1,4 +1,4 @@
const { BUILTIN_LEVEL_IDS } = require("../utilities/security/accessLevels")
const { BUILTIN_ROLE_IDS } = require("../utilities/security/roles")
const AuthTypes = {
APP: "app",
@ -24,14 +24,14 @@ const USERS_TABLE_SCHEMA = {
fieldName: "username",
name: "username",
},
accessLevelId: {
fieldName: "accessLevelId",
name: "accessLevelId",
roleId: {
fieldName: "roleId",
name: "roleId",
type: "options",
constraints: {
type: "string",
presence: false,
inclusion: Object.keys(BUILTIN_LEVEL_IDS),
inclusion: Object.keys(BUILTIN_ROLE_IDS),
},
},
},

View File

@ -1,4 +1,4 @@
const { BUILTIN_LEVEL_IDS } = require("../utilities/security/accessLevels")
const { BUILTIN_ROLE_IDS } = require("../utilities/security/roles")
exports.HOME_SCREEN = {
description: "",
@ -97,7 +97,7 @@ exports.HOME_SCREEN = {
},
routing: {
route: "/",
accessLevelId: BUILTIN_LEVEL_IDS.BASIC,
roleId: BUILTIN_ROLE_IDS.BASIC,
},
name: "d834fea2-1b3e-4320-ab34-f9009f5ecc59",
}

View File

@ -10,7 +10,7 @@ const DocumentTypes = {
AUTOMATION: "au",
LINK: "li",
APP: "app",
ACCESS_LEVEL: "ac",
ROLE: "role",
WEBHOOK: "wh",
INSTANCE: "inst",
PAGE: "page",
@ -169,18 +169,18 @@ exports.getAppParams = (appId = null, otherProps = {}) => {
}
/**
* Generates a new access level ID.
* @returns {string} The new access level ID which the access level doc can be stored under.
* Generates a new role ID.
* @returns {string} The new role ID which the role doc can be stored under.
*/
exports.generateAccessLevelID = () => {
return `${DocumentTypes.ACCESS_LEVEL}${SEPARATOR}${newid()}`
exports.generateRoleID = () => {
return `${DocumentTypes.ROLE}${SEPARATOR}${newid()}`
}
/**
* Gets parameters for retrieving an access level, this is a utility function for the getDocParams function.
* Gets parameters for retrieving a role, this is a utility function for the getDocParams function.
*/
exports.getAccessLevelParams = (accessLevelId = null, otherProps = {}) => {
return getDocParams(DocumentTypes.ACCESS_LEVEL, accessLevelId, otherProps)
exports.getRoleParams = (roleId = null, otherProps = {}) => {
return getDocParams(DocumentTypes.ROLE, roleId, otherProps)
}
/**

View File

@ -1,9 +1,6 @@
const jwt = require("jsonwebtoken")
const STATUS_CODES = require("../utilities/statusCodes")
const {
getAccessLevel,
BUILTIN_LEVELS,
} = require("../utilities/security/accessLevels")
const { getRole, BUILTIN_ROLES } = require("../utilities/security/roles")
const { AuthTypes } = require("../constants")
const { getAppId, getCookieName, setCookie, isClient } = require("../utilities")
@ -35,7 +32,7 @@ module.exports = async (ctx, next) => {
ctx.appId = appId
ctx.user = {
appId,
accessLevel: BUILTIN_LEVELS.PUBLIC,
role: BUILTIN_ROLES.PUBLIC,
}
await next()
return
@ -49,7 +46,7 @@ module.exports = async (ctx, next) => {
ctx.user = {
...jwtPayload,
appId: appId,
accessLevel: await getAccessLevel(appId, jwtPayload.accessLevelId),
role: await getRole(appId, jwtPayload.roleId),
}
} catch (err) {
ctx.throw(err.status || STATUS_CODES.FORBIDDEN, err.text)

View File

@ -1,4 +1,7 @@
const { BUILTIN_LEVEL_IDS } = require("../utilities/security/accessLevels")
const {
BUILTIN_ROLE_IDS,
getUserPermissionIds,
} = require("../utilities/security/roles")
const {
PermissionTypes,
doesHavePermission,
@ -7,7 +10,7 @@ const env = require("../environment")
const { apiKeyTable } = require("../db/dynamoClient")
const { AuthTypes } = require("../constants")
const ADMIN_ACCESS = [BUILTIN_LEVEL_IDS.ADMIN, BUILTIN_LEVEL_IDS.BUILDER]
const ADMIN_ROLES = [BUILTIN_ROLE_IDS.ADMIN, BUILTIN_ROLE_IDS.BUILDER]
const LOCAL_PASS = new RegExp(["webhooks/trigger", "webhooks/schema"].join("|"))
@ -47,9 +50,9 @@ module.exports = (permType, permLevel = null) => async (ctx, next) => {
ctx.throw(403, "User not found")
}
const accessLevel = ctx.user.accessLevel
const permissions = ctx.user.permissions
if (ADMIN_ACCESS.indexOf(accessLevel._id) !== -1) {
const role = ctx.user.role
const permissions = await getUserPermissionIds(ctx.appId, role._id)
if (ADMIN_ROLES.indexOf(role._id) !== -1) {
return next()
}

View File

@ -1,5 +1,4 @@
const { BUILTIN_LEVEL_IDS } = require("../security/accessLevels")
const { BUILTIN_PERMISSION_NAMES } = require("../security/permissions")
const { BUILTIN_ROLE_IDS } = require("../security/roles")
const env = require("../../environment")
const CouchDB = require("../../db")
const jwt = require("jsonwebtoken")
@ -10,8 +9,7 @@ const APP_PREFIX = DocumentTypes.APP + SEPARATOR
module.exports = async (ctx, appId, version) => {
const builderUser = {
userId: "BUILDER",
accessLevelId: BUILTIN_LEVEL_IDS.BUILDER,
permissions: [BUILTIN_PERMISSION_NAMES.ADMIN],
roleId: BUILTIN_ROLE_IDS.BUILDER,
version,
}
if (env.BUDIBASE_API_KEY) {

View File

@ -1,150 +0,0 @@
const CouchDB = require("../../db")
const { cloneDeep } = require("lodash/fp")
const BUILTIN_IDS = {
ADMIN: "ADMIN",
POWER: "POWER_USER",
BASIC: "BASIC",
PUBLIC: "PUBLIC",
BUILDER: "BUILDER",
}
function AccessLevel(id, name, inherits) {
this._id = id
this.name = name
if (inherits) {
this.inherits = inherits
}
}
exports.BUILTIN_LEVELS = {
ADMIN: new AccessLevel(BUILTIN_IDS.ADMIN, "Admin", BUILTIN_IDS.POWER),
POWER: new AccessLevel(BUILTIN_IDS.POWER, "Power", BUILTIN_IDS.BASIC),
BASIC: new AccessLevel(BUILTIN_IDS.BASIC, "Basic", BUILTIN_IDS.PUBLIC),
PUBLIC: new AccessLevel(BUILTIN_IDS.PUBLIC, "Public"),
BUILDER: new AccessLevel(BUILTIN_IDS.BUILDER, "Builder"),
}
exports.BUILTIN_LEVEL_ID_ARRAY = Object.values(exports.BUILTIN_LEVELS).map(
level => level._id
)
exports.BUILTIN_LEVEL_NAME_ARRAY = Object.values(exports.BUILTIN_LEVELS).map(
level => level.name
)
function isBuiltin(accessLevel) {
return exports.BUILTIN_LEVEL_ID_ARRAY.indexOf(accessLevel) !== -1
}
/**
* Gets the access level object, this is mainly useful for two purposes, to check if the level exists and
* to check if the access level inherits any others.
* @param {string} appId The app in which to look for the access level.
* @param {string|null} accessLevelId The level ID to lookup.
* @returns {Promise<AccessLevel|object|null>} The access level object, which may contain an "inherits" property.
*/
exports.getAccessLevel = async (appId, accessLevelId) => {
if (!accessLevelId) {
return null
}
let accessLevel
if (isBuiltin(accessLevelId)) {
accessLevel = cloneDeep(
Object.values(exports.BUILTIN_LEVELS).find(
level => level._id === accessLevelId
)
)
} else {
const db = new CouchDB(appId)
accessLevel = await db.get(accessLevelId)
}
return accessLevel
}
/**
* Returns an ordered array of the user's inherited access level IDs, this can be used
* to determine if a user can access something that requires a specific access level.
* @param {string} appId The ID of the application from which access levels should be obtained.
* @param {string} userAccessLevelId The user's access level, this can be found in their access token.
* @returns {Promise<string[]>} returns an ordered array of the access levels, with the first being their
* highest level of access and the last being the lowest level.
*/
exports.getUserAccessLevelHierarchy = async (appId, userAccessLevelId) => {
// special case, if they don't have a level then they are a public user
if (!userAccessLevelId) {
return [BUILTIN_IDS.PUBLIC]
}
let accessLevelIds = [userAccessLevelId]
let userAccess = await exports.getAccessLevel(appId, userAccessLevelId)
// check if inherited makes it possible
while (
userAccess &&
userAccess.inherits &&
accessLevelIds.indexOf(userAccess.inherits) === -1
) {
accessLevelIds.push(userAccess.inherits)
// go to get the inherited incase it inherits anything
userAccess = await exports.getAccessLevel(appId, userAccess.inherits)
}
// add the user's actual level at the end (not at start as that stops iteration
return accessLevelIds
}
class AccessController {
constructor(appId) {
this.appId = appId
this.userHierarchies = {}
}
async hasAccess(tryingAccessLevelId, userAccessLevelId) {
// special cases, the screen has no access level, the access levels are the same or the user
// is currently in the builder
if (
tryingAccessLevelId == null ||
tryingAccessLevelId === "" ||
tryingAccessLevelId === userAccessLevelId ||
userAccessLevelId === BUILTIN_IDS.BUILDER
) {
return true
}
let accessLevelIds = this.userHierarchies[userAccessLevelId]
if (!accessLevelIds) {
accessLevelIds = await exports.getUserAccessLevelHierarchy(
this.appId,
userAccessLevelId
)
this.userHierarchies[userAccessLevelId] = userAccessLevelId
}
return accessLevelIds.indexOf(tryingAccessLevelId) !== -1
}
async checkScreensAccess(screens, userAccessLevelId) {
let accessibleScreens = []
// don't want to handle this with Promise.all as this would mean all custom access levels would be
// retrieved at same time, it is likely a custom levels will be re-used and therefore want
// to work in sync for performance save
for (let screen of screens) {
const accessible = await this.checkScreenAccess(screen, userAccessLevelId)
if (accessible) {
accessibleScreens.push(accessible)
}
}
return accessibleScreens
}
async checkScreenAccess(screen, userAccessLevelId) {
const accessLevelId =
screen && screen.routing ? screen.routing.accessLevelId : null
if (await this.hasAccess(accessLevelId, userAccessLevelId)) {
return screen
}
return null
}
}
exports.AccessController = AccessController
exports.BUILTIN_LEVEL_IDS = BUILTIN_IDS
exports.isBuiltin = isBuiltin
exports.AccessLevel = AccessLevel

View File

@ -45,7 +45,7 @@ function getAllowedLevels(userPermLevel) {
}
}
exports.BUILTIN_PERMISSION_NAMES = {
exports.BUILTIN_PERMISSION_IDS = {
READ_ONLY: "read_only",
WRITE: "write",
ADMIN: "admin",
@ -54,21 +54,24 @@ exports.BUILTIN_PERMISSION_NAMES = {
exports.BUILTIN_PERMISSIONS = {
READ_ONLY: {
name: exports.BUILTIN_PERMISSION_NAMES.READ_ONLY,
_id: exports.BUILTIN_PERMISSION_IDS.READ_ONLY,
name: "Read only",
permissions: [
new Permission(PermissionTypes.TABLE, PermissionLevels.READ),
new Permission(PermissionTypes.VIEW, PermissionLevels.READ),
],
},
WRITE: {
name: exports.BUILTIN_PERMISSION_NAMES.WRITE,
_id: exports.BUILTIN_PERMISSION_IDS.WRITE,
name: "Read/Write",
permissions: [
new Permission(PermissionTypes.TABLE, PermissionLevels.WRITE),
new Permission(PermissionTypes.VIEW, PermissionLevels.READ),
],
},
POWER: {
name: exports.BUILTIN_PERMISSION_NAMES.POWER,
_id: exports.BUILTIN_PERMISSION_IDS.POWER,
name: "Power",
permissions: [
new Permission(PermissionTypes.TABLE, PermissionLevels.WRITE),
new Permission(PermissionTypes.USER, PermissionLevels.READ),
@ -78,7 +81,8 @@ exports.BUILTIN_PERMISSIONS = {
],
},
ADMIN: {
name: exports.BUILTIN_PERMISSION_NAMES.ADMIN,
_id: exports.BUILTIN_PERMISSION_IDS.ADMIN,
name: "Admin",
permissions: [
new Permission(PermissionTypes.TABLE, PermissionLevels.ADMIN),
new Permission(PermissionTypes.USER, PermissionLevels.ADMIN),
@ -89,11 +93,11 @@ exports.BUILTIN_PERMISSIONS = {
},
}
exports.doesHavePermission = (permType, permLevel, userPermissionNames) => {
exports.doesHavePermission = (permType, permLevel, permissionIds) => {
const builtins = Object.values(exports.BUILTIN_PERMISSIONS)
let permissions = flatten(
builtins
.filter(builtin => userPermissionNames.indexOf(builtin.name) !== -1)
.filter(builtin => permissionIds.indexOf(builtin._id) !== -1)
.map(builtin => builtin.permissions)
)
for (let permission of permissions) {

View File

@ -0,0 +1,183 @@
const CouchDB = require("../../db")
const { cloneDeep } = require("lodash/fp")
const { BUILTIN_PERMISSION_IDS } = require("./permissions")
const BUILTIN_IDS = {
ADMIN: "ADMIN",
POWER: "POWER_USER",
BASIC: "BASIC",
PUBLIC: "PUBLIC",
BUILDER: "BUILDER",
}
function Role(id, name) {
this._id = id
this.name = name
}
Role.prototype.addPermission = function(permissionId) {
this.permissionId = permissionId
return this
}
Role.prototype.addInheritance = function(inherits) {
this.inherits = inherits
return this
}
exports.BUILTIN_ROLES = {
ADMIN: new Role(BUILTIN_IDS.ADMIN, "Admin")
.addPermission(BUILTIN_PERMISSION_IDS.ADMIN)
.addInheritance(BUILTIN_IDS.POWER),
POWER: new Role(BUILTIN_IDS.POWER, "Power")
.addPermission(BUILTIN_PERMISSION_IDS.POWER)
.addInheritance(BUILTIN_IDS.BASIC),
BASIC: new Role(BUILTIN_IDS.BASIC, "Basic")
.addPermission(BUILTIN_PERMISSION_IDS.WRITE)
.addInheritance(BUILTIN_IDS.PUBLIC),
PUBLIC: new Role(BUILTIN_IDS.PUBLIC, "Public").addPermission(
BUILTIN_PERMISSION_IDS.READ_ONLY
),
BUILDER: new Role(BUILTIN_IDS.BUILDER, "Builder").addPermission(
BUILTIN_PERMISSION_IDS.ADMIN
),
}
exports.BUILTIN_ROLE_ID_ARRAY = Object.values(exports.BUILTIN_ROLES).map(
level => level._id
)
exports.BUILTIN_ROLE_NAME_ARRAY = Object.values(exports.BUILTIN_ROLES).map(
level => level.name
)
function isBuiltin(role) {
return exports.BUILTIN_ROLE_ID_ARRAY.indexOf(role) !== -1
}
/**
* Gets the role object, this is mainly useful for two purposes, to check if the level exists and
* to check if the role inherits any others.
* @param {string} appId The app in which to look for the role.
* @param {string|null} roleId The level ID to lookup.
* @returns {Promise<Role|object|null>} The role object, which may contain an "inherits" property.
*/
exports.getRole = async (appId, roleId) => {
if (!roleId) {
return null
}
let role
if (isBuiltin(roleId)) {
role = cloneDeep(
Object.values(exports.BUILTIN_ROLES).find(role => role._id === roleId)
)
} else {
const db = new CouchDB(appId)
role = await db.get(roleId)
}
return role
}
/**
* Simple function to get all the roles based on the top level user role ID.
*/
async function getAllUserRoles(appId, userRoleId) {
if (!userRoleId) {
return [BUILTIN_IDS.PUBLIC]
}
let currentRole = await exports.getRole(appId, userRoleId)
let roles = currentRole ? [currentRole] : []
let roleIds = [userRoleId]
// get all the inherited roles
while (
currentRole &&
currentRole.inherits &&
roleIds.indexOf(currentRole.inherits) === -1
) {
roleIds.push(currentRole.inherits)
currentRole = await exports.getRole(appId, currentRole.inherits)
roles.push(currentRole)
}
return roles
}
/**
* Returns an ordered array of the user's inherited role IDs, this can be used
* to determine if a user can access something that requires a specific role.
* @param {string} appId The ID of the application from which roles should be obtained.
* @param {string} userRoleId The user's role ID, this can be found in their access token.
* @returns {Promise<string[]>} returns an ordered array of the roles, with the first being their
* highest level of access and the last being the lowest level.
*/
exports.getUserRoleHierarchy = async (appId, userRoleId) => {
// special case, if they don't have a role then they are a public user
return (await getAllUserRoles(appId, userRoleId)).map(role => role._id)
}
/**
* Get all of the user permissions which could be found across the role hierarchy
* @param appId The ID of the application from which roles should be obtained.
* @param userRoleId The user's role ID, this can be found in their access token.
* @returns {Promise<string[]>} A list of permission IDs these should all be unique.
*/
exports.getUserPermissionIds = async (appId, userRoleId) => {
return [
...new Set(
(await getAllUserRoles(appId, userRoleId)).map(role => role.permissionId)
),
]
}
class AccessController {
constructor(appId) {
this.appId = appId
this.userHierarchies = {}
}
async hasAccess(tryingRoleId, userRoleId) {
// special cases, the screen has no role, the roles are the same or the user
// is currently in the builder
if (
tryingRoleId == null ||
tryingRoleId === "" ||
tryingRoleId === userRoleId ||
tryingRoleId === BUILTIN_IDS.BUILDER
) {
return true
}
let roleIds = this.userHierarchies[userRoleId]
if (!roleIds) {
roleIds = await exports.getUserRoleHierarchy(this.appId, userRoleId)
this.userHierarchies[userRoleId] = userRoleId
}
return roleIds.indexOf(tryingRoleId) !== -1
}
async checkScreensAccess(screens, userRoleId) {
let accessibleScreens = []
// don't want to handle this with Promise.all as this would mean all custom roles would be
// retrieved at same time, it is likely a custom role will be re-used and therefore want
// to work in sync for performance save
for (let screen of screens) {
const accessible = await this.checkScreenAccess(screen, userRoleId)
if (accessible) {
accessibleScreens.push(accessible)
}
}
return accessibleScreens
}
async checkScreenAccess(screen, userRoleId) {
const roleId = screen && screen.routing ? screen.routing.roleId : null
if (await this.hasAccess(roleId, userRoleId)) {
return screen
}
return null
}
}
exports.AccessController = AccessController
exports.BUILTIN_ROLE_IDS = BUILTIN_IDS
exports.isBuiltin = isBuiltin
exports.Role = Role