Files
speckle-server/packages/server/modules/shared/index.js
T
Gergő Jedlicska c6cd4c311d feat(serverinvites): create domain module in server invites (#2401)
* chore(serverinvites): repository refactor for multiregion

* chore(serverinvites): remove migrated functions from old repository

* chore(serverinvites): refactor serverInviteForToken resolver for multiregion

* chore(serverinvites): invite processing service refactor for multiregion

* chore(serverinvites): subscription refactor for multiregion

* chore(serverinvites): move buildEmailContents to dedicated file

* chore(serverinvites): deleteAllStreamInvites function multiregion refactor

* chore(serverinvites): refactor deleteServerOnlyInvites multiregion repository

* chore(serverinvites): complete repository refactor for multiregion

* feat(serverinvites): create domain module in server invites

* fix(serverinvites): no relative imports

* feat(serverinvites): extract individual types from repository

* feat(serverinvites): move interfaces to operations

* fix(serverinvites): update imports referencing old interfaces file

* fix(serverinvites): type mismatch for insert invite and delete old

* chore(serverinvites): refactor to single repo function

* test(serverinvites): fix tests

* fix(serverinvites): use domain types in all places

* feat(serverinvites): WIP unity

* feat(serverinvites): move to new facory names and types

* feat(serverinvites): fix tests

* fix(serverinvites): use factory name

---------

Co-authored-by: Alessandro Magionami <alessandro.magionami@gmail.com>
2024-06-25 13:24:37 +02:00

137 lines
4.0 KiB
JavaScript

'use strict'
const knex = require(`@/db/knex`)
const { ForbiddenError, ApolloError } = require('apollo-server-express')
const {
pubsub,
StreamSubscriptions,
CommitSubscriptions,
BranchSubscriptions
} = require('@/modules/shared/utils/subscriptions')
const { Roles } = require('@speckle/shared')
const { adminOverrideEnabled } = require('@/modules/shared/helpers/envHelper')
const { ServerAcl: ServerAclSchema } = require('@/modules/core/dbSchema')
const { getRoles } = require('@/modules/shared/roles')
const {
roleResourceTypeToTokenResourceType,
isResourceAllowed
} = require('@/modules/core/helpers/token')
const ServerAcl = () => ServerAclSchema.knex()
/**
* Validates the scope against a list of scopes of the current session.
* @param {string[]|undefined} scopes
* @param {string} scope
* @return {void}
*/
async function validateScopes(scopes, scope) {
const errMsg = `Your auth token does not have the required scope${
scope?.length ? ': ' + scope + '.' : '.'
}`
if (!scopes) throw new ForbiddenError(errMsg, { scope })
if (scopes.indexOf(scope) === -1 && scopes.indexOf('*') === -1)
throw new ForbiddenError(errMsg, { scope })
}
/**
* Checks the userId against the resource's acl.
* @param {string | null | undefined} userId
* @param {string} resourceId
* @param {string} requiredRole
* @param {import('@/modules/serverinvites/services/operations').TokenResourceIdentifier[] | undefined | null} [userResourceAccessLimits]
*/
async function authorizeResolver(
userId,
resourceId,
requiredRole,
userResourceAccessLimits
) {
userId = userId || null
const roles = await getRoles()
// TODO: Cache these results with a TTL of 1 mins or so, it's pointless to query the db every time we get a ping.
const role = roles.find((r) => r.name === requiredRole)
if (!role) throw new ApolloError('Unknown role: ' + requiredRole)
const resourceRuleType = roleResourceTypeToTokenResourceType(role.resourceTarget)
const isResourceLimited =
resourceRuleType &&
!isResourceAllowed({
resourceId,
resourceType: resourceRuleType,
resourceAccessRules: userResourceAccessLimits
})
if (isResourceLimited) {
throw new ForbiddenError('You are not authorized to access this resource.')
}
if (adminOverrideEnabled()) {
const serverRoles = await ServerAcl().select('role').where({ userId })
if (serverRoles.map((r) => r.role).includes(Roles.Server.Admin)) return requiredRole
}
try {
const { isPublic } = await knex(role.resourceTarget)
.select('isPublic')
.where({ id: resourceId })
.first()
if (isPublic && role.weight < 200) return true
} catch {
throw new ApolloError(
`Resource of type ${role.resourceTarget} with ${resourceId} not found`
)
}
const userAclEntry = userId
? await knex(role.aclTableName).select('*').where({ resourceId, userId }).first()
: null
if (!userAclEntry) {
throw new ForbiddenError('You are not authorized to access this resource.')
}
userAclEntry.role = roles.find((r) => r.name === userAclEntry.role)
if (userAclEntry.role.weight >= role.weight) return userAclEntry.role.name
throw new ForbiddenError('You are not authorized.')
}
const Scopes = () => knex('scopes')
async function registerOrUpdateScope(scope) {
await knex.raw(
`${Scopes()
.insert(scope)
.toString()} on conflict (name) do update set public = ?, description = ? `,
[scope.public, scope.description]
)
return
}
const UserRoles = () => knex('user_roles')
async function registerOrUpdateRole(role) {
await knex.raw(
`${UserRoles()
.insert(role)
.toString()} on conflict (name) do update set weight = ?, description = ?, "resourceTarget" = ? `,
[role.weight, role.description, role.resourceTarget]
)
return
}
module.exports = {
registerOrUpdateScope,
registerOrUpdateRole,
// validateServerRole,
validateScopes,
authorizeResolver,
pubsub,
getRoles,
StreamPubsubEvents: StreamSubscriptions,
CommitPubsubEvents: CommitSubscriptions,
BranchPubsubEvents: BranchSubscriptions
}