PHP code example of liuchang103 / hyperf-sanctum

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

    

liuchang103 / hyperf-sanctum example snippets


php bin/hyperf.php vendor:publish liuchang103/hyperf-sanctum

php bin/hyperf.php migrate

class Authentication extends \HyperfSanctum\Middleware
{
    // 未登陆成功
    protected function failedLogin()
    {
        return $this->response->json([
            'code' => -1,
            'message' => 'failedLogin'
        ]);
    }
}

Router::get( '/user', 'App\Controller\IndexController@user', ['middleware' => [App\Middleware\Authentication::class]]);

// or 注解

/**
 * @Middleware(\App\Middleware\Authentication::class)
 */
public function user()

class User extends Model
{
    use \HyperfSanctum\Tokens;

    // input 为用户输入, origin 为原数据
    public function tokenLoginVerify($input, $origin)
    {
        return md5($input) == $origin;
    }
}

$name = $user->tokenName();

/**
 * @Can("delete")
 */
public function delete()

/**
 * @Middleware(\App\Middleware\Authentication::class)
 * @Can("admin")
 * @CanWhite("boss")
 */
class AdminController
{
    public function index()

    /**
     * @Can({"create", "manage"})
     */
    public function create()

    /**
     * @Can("tongji")
     * @CanWhite("guest")
     */
    public function tongji()
}

/**
 * @Middleware(\App\Middleware\Authentication::class)
 * @Can({"admin:index", "admin:create", "admin:tongji"})
 * @CanWhite({"admin", "manage"})
 * @CanCard({"boss", "landlady"})
 */
class AdminController
{
    public function index()

    /**
     * @Can("create")
     */
    public function create()

    /**
     * @Can("tongji")
     * @CanCard("guest")
     */
    public function tongji()
}

class Authentication extends \HyperfSanctum\Middleware
{
    // 未登陆成功
    protected function failedLogin()
    {
        return $this->response->json([
            'code' => -1,
            'message' => 'failedLogin',
        ]);
    }
    
    // 未通过权限验证
    protected function unauthenticated()
    {
        return $this->response->json([
            'code' => -2,
            'message' => 'Unauthenticated',
        ]);
    }
}