PHP code example of wappcode / gql-pdss-auth

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

    

wappcode / gql-pdss-auth example snippets



return [
    'database' => [
        'connection' => [
            'driver' => 'pdo_mysql',
            'user' => 'usuario',
            'password' => 'password',
            'host' => 'localhost',
            'port' => 3306,
            'dbname' => 'app',
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci'
        ],
        "entity_paths" => [
           "GPDAuth\Entities"=> realpath(__DIR__ . "/../vendor/wappcode/gql-pdss-auth/GPDAuth/src/Entities"),
            "GPDAuthJWT\Entities"=> realpath(__DIR__ . "/../vendor/wappcode/gql-pdss-auth/GPDAuthJWT/src/Entities"),
        ]
    ]
];


use GPDAuth\GPDAuthModule;

// Configuración básica (recomendada para GraphQL)
$app->addModules([
    new GPDAuthModule(
        exitUnauthenticated: false,  // Para GraphQL, permite validación granular por resolver
        publicRoutes: ['/login', '/register']  // Rutas que no requieren autenticación
    ),
    // Otros módulos...
    AppModule::class,
]);


// Para aplicaciones REST API tradicionales
new GPDAuthModule(
    exitUnauthenticated: true,   // Responde 401 si no está autenticado
    publicRoutes: ['/login', '/register', '/forgot-password']
);

// Para aplicaciones GraphQL (recomendado)
new GPDAuthModule(
    exitUnauthenticated: false,  // Permite validación a nivel de resolver
    publicRoutes: ['/login']
);


use GPDAuth\Contracts\AuthServiceInterface;

// En un resolver o controlador
$authService = $context->getServiceManager()->get(AuthServiceInterface::class);

// Login
try {
    $authService->login('username', 'password');
    echo "Login exitoso";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

// Verificar si está autenticado
$user = $authService->getAuthenticatedUser();
if ($user) {
    echo "Usuario: " . $user->getUsername();
}

// Logout
$authService->logout();


// En un módulo GraphQL
use GPDAuth\Graphql\AuthResolverGuardFactory;
use GPDCore\Graphql\ResolverPipelineFactory;

class AppModule extends AbstractModule
{
    function getResolvers(): array
    {
        $echoResolve = fn($root, $args) => $args["message"];
        
        return [
            // Resolver público
            "Query::echo" => $echoResolve,
            
            // Resolver protegido que requiere autenticación
            'Query::echoProtected' => ResolverPipelineFactory::createPipeline($echoResolve, [
                AuthResolverGuardFactory::


use GPDAuth\Contracts\AuthServiceInterface;

$auth = $context->getServiceManager()->get(AuthServiceInterface::class);

// Autenticación
$auth->login(string $username, string $password): void;
$auth->logout(): void;
$user = $auth->getAuthenticatedUser(): ?AuthenticatedUserInterface;


// Resolver de login
public static function createLoginResolve(): callable
{
    return function ($root, array $args, AppContextInterface $context, $info) {
        $username = $args["username"] ?? '';
        $password = $args["password"] ?? '';
        
        /** @var AuthServiceInterface */
        $auth = $context->getServiceManager()->get(AuthServiceInterface::class);
        
        try {
            $auth->login($username, $password);
            $user = $auth->getAuthenticatedUser();
            
            return [
                'success' => true,
                'user' => $user->toArray(),
                'message' => 'Login exitoso'
            ];
        } catch (Throwable $e) {
            throw new GQLException('Credenciales inválidas', 'INVALID_CREDENTIALS');
        }
    };
}


// Verificación de roles
$user->hasRole(string $role): bool;
$user->hasAnyRole(array $roles): bool;
$user->hasAllRoles(array $roles): bool;

// Verificación de permisos
$user->hasPermission(string $resource, string $permission, ?string $scope = null): bool;
$user->hasAnyPermission(array $resources, array $permissions, ?array $scopes = null): bool;
$user->hasAllPermissions(array $resources, array $permissions, ?array $scopes = null): bool;


$user = $auth->getAuthenticatedUser();

// Verificar roles
if ($user->hasRole('admin')) {
    echo "Usuario es administrador";
}

if ($user->hasAnyRole(['editor', 'publisher'])) {
    echo "Usuario puede editar contenido";
}

// Verificar permisos específicos
if ($user->hasPermission('posts', 'CREATE')) {
    echo "Usuario puede crear posts";
}

// Permisos con scope
if ($user->hasPermission('posts', 'EDIT', 'OWNER')) {
    echo "Usuario puede editar sus propios posts";
}

if ($user->hasPermission('posts', 'EDIT', 'ALL')) {
    echo "Usuario puede editar cualquier post";
}

// Permisos múltiples
if ($user->hasAllPermissions(['posts', 'comments'], ['CREATE', 'EDIT'], ['ALL'])) {
    echo "Usuario tiene control completo sobre posts y comentarios";
}


use GPDAuth\Graphql\AuthResolverGuardFactory;

// Requiere autenticación (cualquier usuario logueado)
AuthResolverGuardFactory::tory::GuardFactory::verGuardFactory::    ['CREATE', 'EDIT', 'DELETE'], 
    ['ALL']
);


class AppModule extends AbstractModule
{
    function getResolvers(): array
    {
        return [
            // Público
            'Query::login' => FieldLogin::createResolve(),
            
            // Solo usuarios autenticados
            'Query::profile' => ResolverPipelineFactory::createPipeline(
                $profileResolver,
                [AuthResolverGuardFactory::                $publishResolver,
                [AuthResolverGuardFactory::


// Configuración en GPDAuthModule
new GPDAuthModule(
    exitUnauthenticated: true,   // true: responde 401 si no autenticado
                                // false: continúa y permite validación granular
    publicRoutes: ['/login', '/register', '/forgot-password']
);


// El middleware inyecta el usuario autenticado en el request
$request = $context->getContextAttribute(ServerRequestInterface::class);
$user = $request->getAttribute(AuthenticatedUserInterface::class);

if ($user instanceof AuthenticatedUserInterface) {
    echo "Usuario autenticado: " . $user->getUsername();
}


use GPDAuthJWT\GPDAuthJWTModule;

// Configurar junto con el módulo base
$app->addModules([
    new GPDAuthModule(exitUnauthenticated: false),
    new GPDAuthJWTModule(),
    AppModule::class,
]);


use GPDAuth\Contracts\AuthenticatedUserInterface;
use Psr\Http\Message\ServerRequestInterface;

$request = $context->getContextAttribute(ServerRequestInterface::class);

$user = $request->getAttribute(AuthenticatedUserInterface::class);
$jwtPayload = $request->getAttribute('jwt_payload');

if ($user instanceof AuthenticatedUserInterface) {
    echo $user->getUsername();
}

if (is_array($jwtPayload)) {
    echo $jwtPayload['iss'] ?? '';
}


use GPDAuthJWT\Contracts\JWTAuthenticatorInterface;
use GPDAuthJWT\DTO\AuthenticationResult;

interface JWTAuthenticatorInterface
{
    public function authenticate(string $jwt): AuthenticationResult;
}


use GPDAuth\Contracts\AuthenticatedUserInterface;

final class AuthenticationResult
{
    public function getAuthenticatedUser(): AuthenticatedUserInterface;
    public function getPayload(): array;
    public function getHeader(): array;
}


// Endpoint para obtener tokens JWT
// POST /oauth/token
$response = [
    'grant_type' => 'client_credentials',
    'client_id' => 'your_client_id',  
    'client_secret' => 'your_client_secret',
    'scope' => 'read write'
];

interface AuthServiceInterface
{
    public function login(string $username, string $password);
    public function logout(): void;
    public function getAuthenticatedUser(): ?AuthenticatedUserInterface;
}

interface AuthenticatedUserInterface
{
    // Información del usuario
    public function getId(): string;
    public function getUsername(): string;
    public function getFullName(): string;
    public function getEmail(): ?string;
    public function toArray(): array;
    
    // Roles
    public function hasRole(string $role): bool;
    public function hasAnyRole(array $roles): bool;
    public function hasAllRoles(array $roles): bool;
    
    // Permisos
    public function hasPermission(string $resource, string $permission, ?string $scope = null): bool;
    public function hasAnyPermission(array $resources, array $permission, ?array $scopes = null): bool;
    public function hasAllPermissions(array $resources, array $permission, ?array $scopes = null): bool;
}

interface JWTAuthenticatorInterface
{
    public function authenticate(string $jwt): AuthenticationResult;
}

final class AuthenticationResult
{
    public function getAuthenticatedUser(): AuthenticatedUserInterface;
    public function getPayload(): array;
    public function getHeader(): array;
}


// GPDAuth\Enums\AuthenticatedUserType
enum AuthenticatedUserType: string
{
    case API_CLIENT = 'api_client';
    case LOCAL_USER = 'local_user';
    case EXTERN_USER = 'extern_user';
}

// GPDAuthJWT\Enums\ApiConsumerStatus
enum ApiConsumerStatus: string
{
    case ACTIVE = 'active';
    case REVOKED = 'revoked';
    case SUSPENDED = 'suspended';
}

enum PermissionAccess: string
{
    case ALLOW = 'allow';
    case DENY = 'deny';
}

enum PermissionValue: string
{
    case ALL = 'all';
    case VIEW = 'view';
    case CREATE = 'create';
    case UPDATE = 'update';
    case DELETE = 'delete';
    case UPLOAD = 'upload';
    case DOWNLOAD = 'download';
}

enum AuthenticationType: string
{
    case SESSION = 'session';
    case ACCESS_TOKEN = 'access_token';
    case REFRESH_TOKEN = 'refresh_token';
    case NONE = 'none';
}

enum HashAlgorithm: string
{
    case Argon2id = 'argon2id';
    case Bcrypt = 'bcrypt';
    case Sha256 = 'sha256';
    case Sha1 = 'sha1';
    case Md5 = 'md5';
}

enum JwtAlgorithm: string
{
    case HS256 = 'HS256';
    case HS384 = 'HS384';
    case HS512 = 'HS512';
    case RS256 = 'RS256';
    case RS384 = 'RS384';
    case RS512 = 'RS512';
    case ES256 = 'ES256';
    case ES384 = 'ES384';
    case ES256K = 'ES256K';
}


$proxyEcho = fn($resolver) => function ($root, $args, AppContextInterface $context, $info) use ($resolver) {
    /** @var AuthServiceInterface */
    $authService = $context->getServiceManager()->get(AuthServiceInterface::class);
    $user = $authService->getAuthenticatedUser();
    
    if (!$user) {
        return $resolver($root, $args, $context, $info);
    }
    
    $msg = $resolver($root, $args, $context, $info);
    return sprintf("%s -> Usuario: %s", $msg, $user->getUsername());
};

return [
    'Query::echoWithUser' => ResolverPipelineFactory::createPipeline($echoResolve, [
        ResolverPipelineFactory::createWrapper($proxyEcho),
        AuthResolverGuardFactory::


use GPDAuth\Library\NoSignedException;
use GPDAuth\Library\NoAuthorizedException;

try {
    $user = static::getAuthenticatedUser($context);
    if (!$user) {
        throw new NoSignedException();
    }
    
    if (!$user->hasRole('admin')) {
        throw new NoAuthorizedException("Acceso denegado", "FORBIDDEN", 403);
    }
    
    // Lógica del resolver...
    
} catch (NoSignedException $e) {
    throw new GQLException('Debe iniciar sesión', 'UNAUTHENTICATED', 401);
} catch (NoAuthorizedException $e) {
    throw new GQLException('Permisos insuficientes', 'FORBIDDEN', 403);
}

$entityPaths = [
    __DIR__ . "/../vendor/wappcode/gql-pdss-auth/GPDAuth/src/Entities"
];


use GPDAuth\Services\AuthSessionService;
use GPDAuth\Services\UserRepository;

$userRepository = new UserRepository($entityManager);
$authService = new AuthSessionService($userRepository);

// Uso del servicio
$authService->login('username', 'password');
$user = $authService->getAuthenticatedUser();