All files / src/access createAccessWrapper.ts

89.47% Statements 17/19
85.71% Branches 12/14
100% Functions 3/3
93.33% Lines 14/15

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 50 51 52 53 54 55 56 57 58 59              3x           337x 76x     38x   1x               1x     1x       1x       37x   36x               36x     26x 8x       18x    
import type { Access } from 'payload'
import type { GatekeeperOptions } from '../types'
 
/**
 * Creates a wrapper for access control functions that checks permissions first,
 * then delegates to the original access control if it exists
 */
export const createAccessWrapper = (
  collectionSlug: string,
  operation: 'create' | 'read' | 'update' | 'delete',
  originalAccess?: Access,
  options?: GatekeeperOptions
): Access => {
  return async (args) => {
    const { checkPermission } = await import('../utils/checkPermission')
 
    // Public user handling for read operations
    if (!args.req.user && operation === 'read') {
      // Pass through to checkPermission which handles public role
      const hasPermission = await checkPermission(
        args.req.payload,
        null,
        `${collectionSlug}.${operation}`,
        undefined,
        options
      )
      
      Iif (!hasPermission) return false
      
      // Check original access if exists
      Iif (originalAccess) {
        return await originalAccess(args)
      }
      
      return true
    }
 
    // No user for non-read operations = denied
    if (!args.req.user) return false
    
    const hasPermission = await checkPermission(
      args.req.payload,
      args.req.user.role,
      `${collectionSlug}.${operation}`,
      args.req.user.id,
      options
    )
    
    if (!hasPermission) return false
 
    // Then check original access control if it exists
    if (originalAccess) {
      return await originalAccess(args)
    }
 
    // Default: permission check was sufficient
    return true
  }
}