Last active
December 14, 2024 17:42
-
-
Save CasperEngl/d65c90fffa92e0b8439b3a50e4524096 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import type { RequireOneOrNone } from "type-fest" | |
| import { isArray } from "lodash-es" | |
| import type { UserModel } from "@/db/users/types" | |
| import type { ResourceModelMap } from "./interfaces" | |
| import type { PermissionResource, PermissionScope } from "./types" | |
| import { getPermissions, validatePermissions } from "./utils" | |
| type PermissionOptions<T extends PermissionResource> = RequireOneOrNone<{ | |
| resource: ResourceModelMap[T] | |
| resources: ResourceModelMap[T][] | |
| }, "resource" | "resources"> | |
| /** | |
| * Checks if the user has the required permission for the given resource. | |
| * | |
| * @param {UserModel} user - The user to check the permission for. | |
| * @param {PermissionResource} resourceName - The name of the resource. | |
| * @param {PermissionScope} permissionOrPermissions - The permission to check. | |
| * @param {object} [options] - The options to check the permission for. | |
| * @param [options.resource] - The related resource to check the permission for. | |
| * @param [options.resources] - The related resources to check the permission for. | |
| * @returns A boolean indicating whether the user has the required permission. | |
| */ | |
| export function checkUserPermissions<T extends PermissionResource>( | |
| user: UserModel, | |
| resourceName: T, | |
| permissionOrPermissions: PermissionScope | PermissionScope[], | |
| options: PermissionOptions<T> = {}, | |
| ) { | |
| const requestedPermissions = isArray(permissionOrPermissions) ? permissionOrPermissions : [permissionOrPermissions] | |
| const givenPermissions = getPermissions(user, resourceName, options.resource) | |
| return validatePermissions(givenPermissions, requestedPermissions) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment