timedoor/laravel-role-js

将Laravel中的角色和权限导入到JavaScript中。

v0.1.2 2023-07-17 03:30 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

从Laravel导入角色和权限数据到JavaScript。

安装

您可以通过composer安装此包

composer require timedoor/laravel-role-js

不要忘记安装jeremykenedy/laravel-roles包以使用默认设置。

您可以使用以下命令发布配置文件

php artisan vendor:publish --tag="laravel-role-js-config"

这是发布配置文件的内容

return [
    'generator' => timedoor\RoleJs\Generator\JeremyKenedyRoleGenerator::class,
];

初始化

首先,发布包含角色和权限逻辑的JavaScript文件。这些文件将被发布到resources/js/roles路径。

php artisan role-js:publish

如果您想更改发布路径,请在命令中指定路径。

php artisan role-js:publish your/publish/path/roles

其次,运行命令以生成包含角色和权限数据的JavaScript文件。它将在发布路径中生成data.ts文件。

php artisan role-js:generate

您也可以在命令中指定发布路径。

php artisan role-js:generate your/publish/path/roles

用法

您可以在JavaScript代码中使用生成的文件。

import { HasRolePermission, useRoles } from 'resources/js/roles';

// Example user data with one role
const admin: HasRolePermission = {
    roles: 'admin',
};

const { hasRole, hasPermission } = useRoles(admin);

// Check if user has the given role
if (hasRole('admin')) {
    // Do something
}

// check if user has one of the given roles
if (hasRole(['admin', 'editor'])) {
    // Do something
}

// check if user has a permission
if (hasPermission('edit.users')) {
    // Do something
}

// check if user has one of the given permissions
if (hasPermission(['view.users', 'edit.users'])) {
    // Do something
}

// check if user has all of the given permissions
if (hasPermission(['view.users', 'edit.users'], true)) {
    // Do something
}

自定义生成器

您可以通过实现timedoor\RoleJs\Generator\GeneratorInterface接口来创建自己的生成器。

<?php

namespace App\RoleJs;

use timedoor\RoleJs\Generator\GeneratorInterface;

class CustomRoleGenerator implements GeneratorInterface
{
    /**
     * @return \Illuminate\Support\Collection<int, string>
     */
    public function getRoles()
    {
        return collect(['admin', 'editor']);
    }

    /**
     * @return \Illuminate\Support\Collection<int, string>
     */
    public function getPermissions()
    {
        return collect(['view.users', 'edit.users']);
    }

    /**
     * @return \Illuminate\Support\Collection<string, string[]>
     */
    public function getRolePermissions()
    {
        return collect([
            'admin' => ['view.users', 'edit.users'],
            'editor' => ['view.users'],
        ]);
    }
}

然后,更改配置文件中的生成器类。

return [
    'generator' => App\RoleJs\CustomRoleGenerator::class,
];

测试

composer test

变更日志

有关最近更改的更多信息,请参阅变更日志

贡献

有关详细信息,请参阅贡献指南

安全漏洞

有关如何报告安全漏洞,请参阅我们的安全策略

鸣谢

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件