PHP code example of nasustop / hapi-auth

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

    

nasustop / hapi-auth example snippets


php bin/hyperf.php vendor:publish nasustop/hapi-auth



declare(strict_types=1);
/**
 * This file is part of Hapi.
 *
 * @link     https://www.nasus.top
 * @document https://wiki.nasus.top
 * @contact  [email protected]
 * @license  https://github.com/nasustop/hapi/blob/master/LICENSE
 */
namespace SystemBundle\Auth;

use Hyperf\HttpMessage\Exception\BadRequestHttpException;
use Hyperf\HttpMessage\Exception\UnauthorizedHttpException;
use Hyperf\Snowflake\IdGeneratorInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Nasustop\HapiAuth\UserProvider;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\SimpleCache\InvalidArgumentException;
use SystemBundle\Service\SystemUserService;

class AuthUserProvider extends UserProvider
{
    public function getInfo(array $payload): array
    {
        if (empty($payload['id'])) {
            throw new UnauthorizedHttpException('登录失效,请重新登录');
        }
        $user = cache($this->getCacheDriver())->get((string) $payload['id']);
        if (empty($user)) {
            throw new UnauthorizedHttpException('登录失效,请重新登录');
        }
        $user['id'] = $payload['id'];
        return $user;
    }

    /**
     * @throws NotFoundExceptionInterface
     * @throws ContainerExceptionInterface
     * @throws InvalidArgumentException
     */
    public function login(array $inputData): array
    {
        $validatorFactory = $this->container->get(ValidatorFactoryInterface::class);
        $validator = $validatorFactory->make($inputData, [
            'username' => '           // generate snowflake id
            $generator = $this->container->get(id: IdGeneratorInterface::class);
            $cacheSnowflakeId = $generator->generate();
        }

        $exp = (int) config(sprintf('auth.%s.jwt.exp', $this->guard), 7200);
        cache($this->getCacheDriver())->set(key: (string) $cacheSnowflakeId, value: $userInfo, ttl: $exp);
        cache($this->getCacheDriver())->set(key: $cacheUserIdKey, value: $cacheSnowflakeId, ttl: $exp);

        return ['id' => $cacheSnowflakeId];
    }

    /**
     * @throws InvalidArgumentException
     */
    public function logout(array $payload): bool
    {
        if (! empty($payload['id'])) {
            $userInfo = cache($this->getCacheDriver())->get(key: (string) $payload['id']);
            if (! empty($userInfo['user_id'])) {
                $cacheUserIdKey = $this->getCacheUserIdKey(user_id: $userInfo['user_id']);
                cache($this->getCacheDriver())->delete(key: $cacheUserIdKey);
            }
            cache($this->getCacheDriver())->delete(key: (string) $payload['id']);
        }
        return true;
    }

    public function validateToken(array $payload): array
    {
        if (empty($payload['id'])) {
            return [];
        }
        $user = cache($this->getCacheDriver())->get(key: (string) $payload['id']);
        if (empty($user)) {
            return [];
        }
        $user['id'] = $payload['id'];
        return $user;
    }

    protected function getCacheDriver()
    {
        return config(sprintf('auth.%s.cache', $this->guard), 'default');
    }

    protected function getCacheUserIdKey(int $user_id): string
    {
        return sprintf('auth:user_id:%s', $user_id);
    }
}