本文へ移動
cccskills
無料GitHub で公開

State Management & Auth Contexts

Gestion de l'état global dans Next.js — contextes d'auth Sanctuaire/Expert, entitlements, et hooks React personnalisés.

インストール方法を見る

含まれるファイル(2)

  • SKILL.md5.9 KB
  • source.json647 B

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

State Management & Auth Contexts

Context

Lumira V2 utilise React Context API (pas Redux, pas Zustand) pour la gestion d'état global. Deux contextes d'authentification coexistent selon la zone de l'app.


Contextes disponibles

apps/web/context/
├── SanctuaireAuthContext.tsx  // JWT client (Sanctuaire)
├── SanctuaireContext.tsx      // Entitlements & capabilities
├── AuthContext.tsx            // Auth générale (legacy)
└── ExpertAuthContext.tsx      // JWT expert (Admin Desk)

SanctuaireAuthContext

Gère la session de l'utilisateur final (client).

Storage des tokens

// Clés localStorage
const SANCTUAIRE_TOKEN_KEY = 'sanctuaire_token';
const LUMIRA_TOKEN_KEY = 'lumira_token'; // alias legacy

// Lecture du token
const token = localStorage.getItem('sanctuaire_token') 
           || localStorage.getItem('lumira_token');

Hook d'utilisation

'use client';
import { useSanctuaireAuth } from '@/context/SanctuaireAuthContext';

function MyComponent() {
  const { user, isLoading, isAuthenticated, login, logout } = useSanctuaireAuth();

  if (isLoading) return <Spinner />;
  if (!isAuthenticated) return <Redirect to="/sanctuaire/login" />;

  return <div>Bienvenue {user.firstName}</div>;
}

Interface User

interface SanctuaireUser {
  id: string;
  email: string;
  firstName: string;
  lastName: string;
  role: 'CLIENT' | 'EXPERT' | 'ADMIN';
  profile?: UserProfile;
}

SanctuaireContext — Entitlements

Gère les capacités débloquées selon le niveau d'achat.

Hook principal

'use client';
import { useSanctuaire } from '@/context/SanctuaireContext';

function FeatureGate() {
  const {
    capabilities,        // string[] — liste des capabilities actives
    hasCapability,       // (cap: string) => boolean
    highestLevel,        // 0 | 1 | 2 | 3 | 4
    levelMetadata,       // { name, color, price }
    isLoading,
  } = useSanctuaire();

  // Vérification par capability
  if (!hasCapability('chat_unlimited')) {
    return <UpgradePrompt requiredLevel={3} />;
  }

  // Vérification par niveau
  if (highestLevel < 2) {
    return <LockedFeature minLevel={2} />;
  }

  return <Feature />;
}

Capabilities par niveau

CapabilityNiveau 1Niveau 2Niveau 3Niveau 4
reading_basic✅✅✅✅
insights_3✅✅✅✅
timeline❌✅✅✅
chat_limited❌✅✅✅
chat_unlimited❌❌✅✅
rituals❌❌✅✅
akashic_record❌❌❌✅
priority_support❌❌❌✅

ExpertAuthContext

Gère la session de l'expert/admin dans le tableau de bord.

// Storage key
localStorage.getItem('expert_token');

// Hook
import { useExpertAuth } from '@/context/ExpertAuthContext';

function AdminPage() {
  const { expert, isAdmin, logout } = useExpertAuth();
  // expert.role: 'EXPERT' | 'ADMIN'
}

Intercepteur Axios

L'API client injecte automatiquement le token dans les requêtes :

// apps/web/lib/api.ts
import axios from 'axios';

export const api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_URL,
  withCredentials: true,
});

api.interceptors.request.use((config) => {
  const token = localStorage.getItem('sanctuaire_token') 
             || localStorage.getItem('lumira_token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// Intercepteur de réponse pour gérer les 401
api.interceptors.response.use(
  (response) => response,
  async (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('sanctuaire_token');
      window.location.href = '/sanctuaire/login';
    }
    return Promise.reject(error);
  }
);

Fournisseur de contexte — Root Layout

// apps/web/app/layout.tsx
export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <SanctuaireAuthProvider>
          <SanctuaireProvider>         {/* Entitlements */}
            <ExpertAuthProvider>
              {children}
            </ExpertAuthProvider>
          </SanctuaireProvider>
        </SanctuaireAuthProvider>
      </body>
    </html>
  );
}

Hooks personnalisés utiles

// hooks/useEntitlement.ts
export function useEntitlement(capability: string) {
  const { hasCapability, highestLevel } = useSanctuaire();
  return { 
    isAllowed: hasCapability(capability),
    highestLevel 
  };
}

// hooks/useIsAuthenticated.ts
export function useIsAuthenticated() {
  const { isAuthenticated, isLoading } = useSanctuaireAuth();
  return { isAuthenticated, isLoading };
}

Pattern de protection de route

// components/guards/AuthGuard.tsx
'use client';

export function AuthGuard({ children, requiredLevel = 0 }) {
  const { isAuthenticated, isLoading } = useSanctuaireAuth();
  const { highestLevel } = useSanctuaire();

  if (isLoading) return <FullPageSpinner />;
  if (!isAuthenticated) redirect('/sanctuaire/login');
  if (highestLevel < requiredLevel) return <UpgradeModal level={requiredLevel} />;

  return children;
}

Best Practices

✅ DO❌ DON'T
Utiliser hasCapability() pour les gatesComparer directement les niveaux dans les composants
Protéger les layouts avec AuthGuardVérifier l'auth dans chaque composant feuille
Stocker sous sanctuaire_tokenCréer de nouvelles clés localStorage
Gérer le isLoading avant d'afficherFlash du contenu privé avant auth check
Centraliser la logique d'auth dans les contextesDupliquer la logique de refresh token

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

007

無料

Security audit, hardening, threat modeling (STRIDE/PASTA), Red/Blue Team, OWASP checks, code review, incident response, and infrastructure security for any project.

日本語の概要は準備中です。原文の説明を表示しています。

aibot88/sec_skill_store42026年5月27日 更新

Guides the creation of agile user stories and Gherkin feature files. Use when the user wants to create a user story, write acceptance criteria, define Gherkin scenarios, or author BDD feature files. This should trigger for requests such as Create a user story; Write a user story; I need to write a user story. Part of cursor-rules-java project

日本語の概要は準備中です。原文の説明を表示しています。

aibot88/sec_skill_store42026年5月27日 更新

Facilitates conversational discovery to create Architectural Decision Records (ADRs) for non-functional requirements using the ISO/IEC 25010:2023 quality model. Use when the user wants to document quality attributes, NFR decisions, security/performance/scalability architecture, or design systems with measurable quality criteria. This should trigger for requests such as Create ADR for Non-functional requirements; Document Non-functional requirements; Capture Non-functional requirements; Generate Non-functional requirements in an ADR. Part of cursor-rules-java project

日本語の概要は準備中です。原文の説明を表示しています。

aibot88/sec_skill_store42026年5月27日 更新

Run a health check on an existing project: dependency audit, security scan, test runner detection, CI/CD evaluation, and missing configuration analysis. Maps the three execution gates (pre/in/post) from /10x-bootstrapper to an assessment framework for existing codebases. Reads optional context/foundation/stack-assessment.md from /10x-stack-assess to focus checks on identified gaps. Writes context/foundation/health-check.md with findings, prioritized fixes, and an agent-readiness verdict. Use when the user has an existing project and wants to verify its health before working with an agent. Trigger phrases: "health check", "check my project", "audit my project", "is my project healthy", "sprawdź projekt", "audyt projektu", "health-check", "project health". Use AFTER /10x-stack-assess (brownfield chain), BEFORE agent onboarding (m1-l4).

日本語の概要は準備中です。原文の説明を表示しています。

aibot88/sec_skill_store42026年5月27日 更新

10x-team

無料

You MUST use this when building projects end-to-end. Orchestrates all 12 team roles — automatically switches between CTO, architect, PM, engineers, SRE, security, DBA, QA, and EM based on the current phase of work. Starts with brainstorming before any implementation.

日本語の概要は準備中です。原文の説明を表示しています。

aibot88/sec_skill_store42026年5月27日 更新

Use when you need to add or configure Maven plugins in your pom.xml — including quality tools (enforcer, surefire, failsafe, jacoco, pitest, spotbugs, pmd), security scanning (OWASP), code formatting (Spotless), version management, container image build (Jib), build information tracking, and benchmarking (JMH) — through a consultative, modular step-by-step approach that only adds what you actually need. This should trigger for requests such as Add Maven plugins in pom.xml; Improve Maven plugins in pom.xml. Part of cursor-rules-java project

日本語の概要は準備中です。原文の説明を表示しています。

aibot88/sec_skill_store42026年5月27日 更新

aibot88 のスキルをすべて見る

このスキルの問題を報告する