npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

lib-access

v1.0.3

Published

Librería para **gestionar autenticación y acceso en aplicaciones React**, encapsulando la complejidad de integración con Keycloak y manejo de estado de usuario.

Readme

📦 Lib Access

Librería para gestionar autenticación y acceso en aplicaciones React, encapsulando la complejidad de integración con Keycloak y manejo de estado de usuario.


🚀 ¿Qué hace esta librería?

  • Centraliza el login con Keycloak
  • Maneja el estado global del usuario
  • Proporciona hooks para acceder fácilmente a:
    • Usuario autenticado
    • Logout
    • Información de acceso
  • Simplifica la integración en cualquier app React

📦 Instalación

Instala las dependencias necesarias en tu proyecto:

npm install [email protected] @react-keycloak/[email protected]
npm install zustand

Luego instala la librería:

npm install lib-access

🧪 Desarrollo de la librería

Para pruebas locales:

npm run dev

Para generar el build:

npm run build

⚙️ Configuración básica

Debes tener configurado Keycloak:

// config/keycloak.config.js
import Keycloak from 'keycloak-js';

export const keycloak = new Keycloak({
  url: 'https://tu-keycloak-url',
  realm: 'tu-realm',
  clientId: 'tu-client-id',
});

export const initOptions = {
  onLoad: 'login-required',
  checkLoginIframe: false,
};

🧩 Uso de la librería

1. Envolver la aplicación

import { AuthProvider, AccessProvider } from 'lib-access';
import { keycloak, initOptions } from './config/keycloak.config';

const AppRouter = () => {
  return (
    <AuthProvider keycloak={keycloak} initOptions={initOptions}>
      <AccessProvider url="https://localhost:44392/api/v2">
        <App />
      </AccessProvider>
    </AuthProvider>
  );
};

export default AppRouter;

2. Uso con React Router (ejemplo completo)

<AuthProvider keycloak={keycloak} initOptions={initOptions}>
  <HashRouter>
    <ThemeProvider theme="light">
      <AccessProvider url="https://localhost:44392/api/v2">
        <Suspense fallback={<Loader />}>
          <Routes>
            <Route path="/" element={<Layout />}>
              <Route index element={<MenuPage />} />
              <Route path="componentes" element={<ComponentesPage />} />
              <Route path="interfaces" element={<InterfacesPage />} />
              <Route path="armado/crear" element={<ArmadoPage />} />
              <Route path="catalogo/:id" element={<CatalogoPage />} />
              <Route path="settings" element={<SettingsPage />} />
              <Route path="armado/lista" element={<CombosPage />} />
            </Route>
          </Routes>
        </Suspense>
      </AccessProvider>
    </ThemeProvider>
  </HashRouter>
</AuthProvider>

🔐 Acceso al estado de autenticación

import { useAuth } from 'lib-access';

function App() {
  const store = useAuth();

  const logout = store(s => s.logout);
  const user = store(s => s.user);

  return (
    <>
      <h1>Bienvenido {user?.Nombre}</h1>
      <button onClick={logout}>Cerrar sesión</button>
    </>
  );
}

export default App;

👤 Estructura del usuario

export default class UserDto {
  Correo: string;
  Nombre: string;
  Nivel: number;
  Codigo: number;
  Roles: any[];
  Groups: any[];
  Departamento: string;
  Sucursal: string;
  IsChecked: boolean;

  constructor(obj: UserDtoProps = {}) {
    this.Correo       = obj?.Correo ?? "";
    this.Nombre       = obj?.Nombre ?? "";
    this.Nivel        = obj?.Nivel ?? 0;
    this.Codigo       = Number(obj?.Codigo) || 0;
    this.Roles        = obj?.Roles ?? [];
    this.Groups       = obj?.Groups ?? [];
    this.Departamento = obj?.Departamento ?? "";
    this.Sucursal     = obj?.Sucursal ?? "";
    this.IsChecked    = obj?.IsChecked ?? false;
  }
}

🧠 Flujo de uso

  1. AuthProvider

    • Inicializa Keycloak
    • Maneja login automático
  2. AccessProvider

    • Configura acceso a API
    • Gestiona contexto de acceso
  3. useAuth

    • Permite acceder al usuario y acciones (logout, etc.)

💡 Recomendaciones

  • Agregar ejemplos de consumo de API protegida
  • Documentar roles y permisos
  • Implementar protección de rutas (PrivateRoute)