Try checking admin access before getting capabilities

GitOrigin-RevId: 75ff99aa6b6e94c1b84a99d22d65b327f4d40126
This commit is contained in:
Andrew Rumble
2025-08-08 08:05:47 +00:00
committed by Copybot
parent df68be700d
commit 488c0ab6e6
2 changed files with 29 additions and 8 deletions
@@ -31,13 +31,14 @@ async function getAdminCapabilities(user) {
async function addHasAdminCapabilityToLocals(req, res, next) {
const user = SessionManager.getSessionUser(req.session)
if (!hasAdminAccess(user)) {
res.locals.hasAdminCapability = () => false
return next()
}
try {
const { adminCapabilities, adminCapabilitiesAvailable } =
await getAdminCapabilities(user)
res.locals.hasAdminCapability = capability => {
if (!hasAdminAccess(user)) {
return false
}
if (!adminCapabilitiesAvailable) {
// If admin capabilities are not available, then all admins have all capabilities
return true
@@ -45,10 +46,7 @@ async function addHasAdminCapabilityToLocals(req, res, next) {
return adminCapabilities.includes(capability)
}
} catch (error) {
if (user) {
// This is unexpected, it probably means that the session user does not exist.
logger.warn({ error, req, user }, 'Failed to get admin capabilities')
}
logger.warn({ error, req, user }, 'Failed to get admin capabilities')
// A module probably threw so adminCapabilitiesAvailable should be true if we are here so deny to be safe
res.locals.hasAdminCapability = () => false
}
@@ -69,7 +69,7 @@ describe('AdminAuthorizationHelper', function () {
this.next = sinon.stub()
this.user = {
isAdmin: false,
isAdmin: true,
}
this.req.logger = {
@@ -101,6 +101,29 @@ describe('AdminAuthorizationHelper', function () {
})
})
describe('when admin capabilities are not available', function () {
describe('user is null', function () {
beforeEach(async function () {
this.req = new MockRequest()
this.res = new MockResponse()
this.next = sinon.stub()
this.req.session = {
user: null,
}
await this.AdminAuthorizationHelper.addHasAdminCapabilityToLocals(
this.req,
this.res,
this.next
)
})
it('defines hasAdminCapability on res.locals', function () {
expect(this.res.locals).to.have.property('hasAdminCapability')
})
it('returns false when called with any capability', function () {
expect(this.res.locals.hasAdminCapability('capability1')).to.be.false
})
})
describe('user is not an admin', function () {
beforeEach(async function () {
this.req = new MockRequest()