All files / src/security/helpers parseForClause.ts

26% Statements 13/50
100% Branches 0/0
0% Functions 0/2
26% Lines 13/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 501x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                           1x 1x                
 
 
import { getMainConfig } from '../../helpers/getGreenDotConfigs'
import { ForClauseWithAll, ForClauseParsedWithAll, ForClauseParsed } from '../../types/core.types'
 
import { asArray } from 'topkat-utils'
 
 
 
/** Merge default permissions and replace ALL by all permissions */
export async function parseForClause<T extends ForClauseParsedWithAll | ForClauseWithAll<any>>(
  forClause: T
): Promise<ForClauseParsed[]> {

  const { allRoles } = getMainConfig()

  const forClauseArr = asArray(forClause) as T extends any[] ? T : T[]

  const output = []

  for (const pRaw of forClauseArr) {

    const p = typeof pRaw === 'string' ? { role: pRaw } : pRaw

    if (p.role === 'public') {
      output.push(p as ForClauseParsed)
    } else {
      const defaultPerms = await getDefaultPerms(p.role, p)

      for (const k in defaultPerms) {
        if (defaultPerms[k] === 'any') delete defaultPerms[k]
      }
      output.push(defaultPerms)
    }
  }

  if (output.some(p => p.role === 'public')) return [{ role: 'public' }]
  else if (output.some(p => (p.role as any) === 'ALL')) return allRoles.map(role => ({ role }))
  else return output
}
 
 
async function getDefaultPerms(role: string, toMerge = {}) {
  const mainConfig = getMainConfig()
  return {
    ...(mainConfig.defaultPermRestrictionForAll || {}),
    ...(mainConfig.defaultPermRestrictionForRole?.[role] || {}),
    ...toMerge,
  } as ForClauseParsed
}