PHP code example of wiseadmin / wise-auth

1. Go to this page and download the library: Download wiseadmin/wise-auth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

wiseadmin / wise-auth example snippets



namespace app\admin\model;

use think\Model;
use wise\auth\trait\HasRoles;
use wise\auth\contract\UserContract;

class Admin extends Model implements UserContract
{
    use HasRoles;
}

'super_admin_ids' => [1],

// route/admin.php
Route::group('admin', function () {
    Route::get('dashboard', 'admin.Index/index');
    Route::get('users', 'admin.Admins/index');
})->middleware(\wise\auth\middleware\RbacMiddleware::class);


namespace app\admin\controller;

use app\common\controller\BaseController;
use wise\auth\facade\Rbac;

class UserController extends BaseController
{
    public function delete($id)
    {
        $adminId = session('admin_id');

        if (!Rbac::check($adminId, 'admin', 'admin.user.delete')) {
            return json(['code' => 403, 'msg' => '没有删除权限']);
        }

        // 执行删除逻辑...
    }
}

'user_models' => [
    'admin'  => \app\admin\model\Admin::class,
    'member' => \app\api\model\Member::class,
],


namespace app\admin\model;

use think\Model;
use wise\auth\trait\HasRoles;

class Admin extends Model
{
    use HasRoles;

    // 可选:覆盖默认的 user_type(默认取类名小写)
    public function getAuthUserType(): string
    {
        return 'admin';
    }
}

$admin = Admin::find(1);

// 单个权限
if ($admin->can('admin.user.edit')) {
    // ...
}

// OR 检查(任一满足即可)
if ($admin->hasPermission(['admin.user.edit', 'admin.user.delete'])) {
    // ...
}

// AND 检查(全部满足才行)
if ($admin->hasPermission(['admin.user.edit', 'admin.user.delete'], true)) {
    // ...
}

use wise\auth\facade\Rbac;

// 单个权限检查
Rbac::check($userId, 'admin', 'admin.user.list');

// OR 检查
Rbac::checkAny($userId, 'admin', ['admin.user.edit', 'admin.user.delete']);

// AND 检查
Rbac::checkAll($userId, 'admin', ['admin.user.edit', 'admin.user.delete']);

// 超管判断
Rbac::isSuperAdmin($userId, 'admin');

// 获取用户所有权限
$permissions = Rbac::getUserPermissions($userId, 'admin');

// 路由匹配权限
$permissions = Rbac::matchRouteToPermissions('/admin/admins/index', 'GET');

use wise\auth\model\Role;

$role = Role::create([
    'name'        => '编辑员',
    'slug'        => 'editor',
    'description' => '内容编辑角色',
    'parent_id'   => 0,       // 父角色 ID,0 表示顶级
    'is_inherit'  => 1,       // 是否继承父角色权限
    'sort'        => 10,
    'status'      => 1,
]);

$role = Role::find(1);

// 赋予单个权限
$role->grantPermission(1);

// 赋予多个权限
$role->grantPermission([1, 2, 3]);

// 撤销权限
$role->revokePermission(2);

// 同步权限(先清空再设置)
$role->syncPermissions([1, 3, 5]);

use wise\auth\facade\Rbac;

$roleTree = Rbac::getRoleTree();

[
    [
        'id'       => 1,
        'name'     => '超级管理员',
        'slug'     => 'super_admin',
        'parent_id' => 0,
        'children' => [
            [
                'id'       => 2,
                'name'     => '管理员',
                'slug'     => 'admin',
                'parent_id' => 1,
                'children' => [...],
            ],
        ],
    ],
]

use wise\auth\model\Role;

// 在保存前检查
if (config('wise-auth.cycle_check_enabled', true)) {
    if (Role::hasCycle($newParentId, $currentRoleId)) {
        throw new \Exception('检测到角色循环继承!');
    }
}

// route/admin.php
Route::group('admin', function () {
    Route::get('dashboard', 'admin.Index/index');
    Route::resource('users', 'admin.Admins');
    Route::resource('roles', 'admin.Roles');
})->middleware(\wise\auth\middleware\RbacMiddleware::class);

// 手动指定需要的权限(使用完整类名)
Route::get('dangerous', 'admin.Tools/clean')
    ->middleware(\wise\auth\middleware\RbacMiddleware::class . ':admin.tools.clean');

return [
    // 中间件别名
    'alias' => [
        'wise.auth' => \wise\auth\middleware\RbacMiddleware::class,
    ],
    // 全局中间件(可选)
    // 'global' => [],
];

'user_resolver' => function () {
    $token = request()->header('Authorization');
    if ($token) {
        // JWT 解析,获取用户 ID
        $userId = JwtService::parse($token)->uid;
        return \app\admin\model\Admin::find($userId);
    }
    return null;
},

'default_mode'      => 'whitelist',
'whitelist_routes'  => [
    '/admin/login',
    '/admin/logout',
    '/admin/auth/*',   // 支持通配符
    '/api/public/*',
],

'default_mode'      => 'blacklist',
'blacklist_routes'  => [
    '/admin/finance/*',
],

// 抛出异常(适合框架级处理)
'unauthorized_action' => 'exception',

// 重定向(适合传统 Web 应用)
'unauthorized_action' => 'redirect',
'unauthorized_redirect' => '/admin/login',

// 返回 JSON(适合 API 接口,默认)
'unauthorized_action' => 'json',
// 响应格式:{"code":403,"msg":"Permission denied: ...","data":[],"timestamp":...}

// 自定义处理
'unauthorized_action' => 'custom',
'unauthorized_handler' => function (\think\Request $request) {
    return json(['code' => 403, 'msg' => '您没有访问权限'])->code(403);
},

'super_admin_ids' => [1, 2],

'super_role' => 'super_admin',

// 在业务中使用
$admin = Admin::find(1);
if ($admin->isSuperAdmin()) {
    // 超管逻辑
}

// editor 自动继承 admin 的权限
$editor = Role::create([
    'name'      => '编辑员',
    'slug'      => 'editor',
    'parent_id' => $adminRoleId,   // 父角色 ID
    'is_inherit' => 1,             // 开启继承
]);

'constraints' => [
    'mutual_exclusion' => [
        ['admin', 'auditor'],     // admin 和 auditor 互斥
        ['finance', 'cashier'],   // finance 和 cashier 互斥
    ],
],

'constraints' => [
    'cardinality' => [
        'super_admin' => 3,       // super_admin 最多 3 人
        'finance'     => 5,       // finance 最多 5 人
    ],
],

'constraints' => [
    'prerequisite' => [
        'super_admin' => ['admin'],   // 分配 super_admin 前必须先有 admin
    ],
],

// config/wise-auth.php
'constraint_checker' => \app\common\auth\CustomConstraintChecker::class,


namespace app\common\auth;

use wise\auth\contract\ConstraintCheckerInterface;

class CustomConstraintChecker implements ConstraintCheckerInterface
{
    public function checkBeforeAssignRole($userId, string $userType, $roleId, array $context = []): bool
    {
        // 自定义逻辑:例如检查用户部门是否匹配
        return true;
    }

    public function checkBeforeGrantPermission($roleId, $permissionId, array $context = []): bool
    {
        return true;
    }

    public function checkBeforeSaveRole(array $data, $roleId = null): bool
    {
        return true;
    }
}

'data_policy' => function (string $permission, $user, array $context = []): \Closure {
    // 返回一个闭包用于修改查询条件
    return function ($query) use ($user) {
        // 例如:只看自己部门的数据
        $query->where('dept_id', $user->dept_id);
    };
},

'permission_sources' => ['database', 'config'],
'permissions' => [
    [
        'ident'       => 'admin.dashboard',
        'name'        => '仪表盘',
        'type'        => 'route',
        'route'       => '/admin/index/index',
        'method'      => '*',
        'description' => '查看后台仪表盘',
    ],
    [
        'ident'       => 'admin.user.list',
        'name'        => '管理员列表',
        'type'        => 'route',
        'route'       => '/admin/admins/index',
        'method'      => 'GET',
    ],
    [
        'ident'  => 'admin.user.delete',
        'name'   => '删除管理员',
        'type'   => 'custom',
        'parent' => 'admin.user.list',  // 父权限 ident
    ],
],

/**
 * 管理员列表
 *
 * @permission ident="admin.user.list", name="管理员列表", type="route", route="/admin/admins/index", method="GET"
 * @return \think\Response
 */
public function index()
{
    // ...
}

/**
 * 删除管理员
 *
 * @permission ident="admin.user.delete", name="删除管理员", type="custom"
 */
public function delete($id)
{
    // ...
}

'permission_sources' => ['annotation'],
'annotation_dirs'    => [
    app_path('admin/controller'),
    app_path('api/controller'),
],
'annotation_tag'     => '@permission',

use think\facade\Event;
use wise\auth\event\RoleChanged;

// 在角色修改后触发
Event::trigger(new RoleChanged('update', $role->id, $role->toArray()));

// app/event.php
return [
    'listen' => [
        'RbacRoleAssigned' => [
            \app\admin\listener\OperationLog::class,
        ],
    ],
];

'subscribe' => [
    \app\admin\subscribe\UserAuthListener::class,
],

// 始终在保存角色前检查
if (Role::hasCycle($request->parent_id, $roleId)) {
    return $this->error('不允许的角色继承关系,检测到循环引用');
}

// 配置多种用户类型
'user_models' => [
    'admin'  => \app\admin\model\Admin::class,
    'member' => \app\api\model\Member::class,
],

// 使用时指定 user_type
Rbac::check($adminId, 'admin', 'admin.dashboard');
Rbac::check($memberId, 'member', 'member.profile.edit');
bash
php think wise:auth:publish
bash
php think migrate:run
bash
php think wise:auth:publish

# 强制覆盖已有配置
php think wise:auth:publish --force
bash
# 清除所有缓存
php think wise:auth:clear

# 清除指定用户缓存
php think wise:auth:clear --user=1 --type=admin