PHP code example of edwinhuish / think-auth

1. Go to this page and download the library: Download edwinhuish/think-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/ */

    

edwinhuish / think-auth example snippets




namespace app\model;

use Edwinhuish\ThinkAuth\Contracts\RoleContract;
use Edwinhuish\ThinkAuth\Traits\RoleTrait;
use think\Model;

class Role extends Model implements RoleContract
{
    use RoleTrait;

    protected $name = 'auth_roles';
}



namespace app\model;

use Edwinhuish\ThinkAuth\Contracts\PermissionContract;
use Edwinhuish\ThinkAuth\Traits\PermissionTrait;
use think\Model;

class Permission extends Model implements PermissionContract
{
    use PermissionTrait;

    protected $name = 'auth_permissions';
}



namespace app\model;

use Edwinhuish\ThinkAuth\Contracts\UserContract;
use Edwinhuish\ThinkAuth\Traits\UserTrait;
use think\Model;

class User extends Model implements UserContract
{
    use UserTrait;

    protected $name = 'users';
}


$owner = new Role();
$owner->name         = 'owner';
$owner->description  = '网站所有者'; // 可选
$owner->save();

$administrator = new Role();
$administrator->name        = 'administrator';
$administrator->description = '管理员'; // 可选
$administrator->save();

$hurray = User::findByName('hurray');

/* 为用户分配角色 */
$hurray->attachRole($administrator); // model
$hurray->attachRole('administrator'); // name
$hurray->attachRole($administrator->id); // id


$administrator = Role::findByName('administrator');

$owner = Role::findByName('owner');

$createPost = new Permission();
$createPost->name         = 'post/create';
$createPost->description  = '创建一篇文章'; // 可选
$createPost->save();

$editPost = new Permission();
$editPost->name         = 'post/edit';
$editPost->description  = '编辑一篇文章'; // optional
$editPost->save();

/* 为 administrator 添加权限 */
$administrator->attachPermission($createPost); // model
$administrator->attachPermission('post/create'); // name
$administrator->attachPermission($createPost->id); // id

/* 为 owner 添加多个权限 */
$owner->attachPermissions([$createPost, $editPost]); // model
$owner->attachPermissions(['post/create', 'post/edit']); // name
$owner->attachPermissions([$createPost->id, $editPost->id]); // model

$hurray = User::findByName('hurray');
$hurray->can('post/edit');   // false
$hurray->can('post/create'); // true

$hurray->refreshPermissionsCache();

#route/app.php

# 拥有 post/edit 规则的用户 可以访问此路由
Route::rule('/testPermission', function(){
  return 'edit';
}, 'GET')->allowCrossDomain()->middleware('auth.permission', 'post/edit');

#route/app.php

# 拥有 administrator 角色的用户 可以访问此路由
Route::rule('/testRole', function(){
  return 'administrator';
}, 'GET')->allowCrossDomain()->middleware('auth.role', 'administrator');

bash
composer dump-autoload