PHP code example of hnraytek / flame-auth

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

    

hnraytek / flame-auth example snippets


'auth' => [
    'enable' => false,          // 是否开启全局鉴权
    'strategy' => 'allow',      // allow: 只检查 NeedAuth | block: 只允许 NoAuth

    'token_name' => 'user',     // 请求头中的 token key,header[token_name]
    'key' => 'your-secret-key', // 加密密钥(请修改!)
    'algo' => 'ripemd160',      // 加密算法
    'table' => '',              // 数据表名(如自行更改请保证数据结构正确,默认留空)
    'expire' => 604800,         // 默认 Token 过期时间(秒)
],

use FlameModule\Attribute\NeedAuth;
use FlameModule\Auth\Attribute\NoAuth;

class UserController
{
    #[NoAuth]
    public function login()
    {
        // 无需鉴权的登录接口,strategy 为 block 生效 
    }

    #[NeedAuth]
    public function profile()
    {
        // 需要鉴权的用户信息接口,strategy 为 allow 才生效
    }
}

use FlameModule\Auth\Attribute\NoAuth;use FlameModule\Auth\Controller\AuthApiController;

class ApiController extends AuthApiController
{
    protected string $tokenType = 'user'; // (必填)token 类型,支持多种类型(如 `user`、`admin`、`member` 等)

    #[NoAuth]
    public function login()
    {
        // 验证用户...
        $this->setUserId($userId); // 设置用户ID并生成 token
        
        $this->success([
            'token' => $this->getToken(),
            'refresh_token' => $this->getRefreshToken(),
        ]);
    }
    
    public function userInfo()
    {
        $userId = $this->getUserId(); // 获取当前登录用户ID
        // ...
    }
    
    public function logout()
    {
        $this->clearToken(); // 清除 token
        $this->success(['message' => 'Logout success']);
    }
}

use FlameModule\Auth\Token;

$tokenService = app(Token::class);

// 生成 token
$token = Token::generateToken();

// 设置 token
$tokenService->set($token, 'user', $userId, 7 * 24 * 3600);

// 获取 token 数据
$data = $tokenService->get($token);

// 验证 token
$isValid = $tokenService->check($token, 'user', $userId);

// 删除 token
$tokenService->delete($token);

// 清理用户所有 token
$tokenService->clear($userId, 'user');

use FlameModule\Auth\Exception\TokenExpirationException;

if ($e instanceof TokenExpirationException) {
    return json([
        'code' => 401,
        'message' => 'Token has expired or is invalid',
    ], 401);
}