# Janus OAuth2 Login (`add-login`)

Reference for projects with `add-login` installed. Covers the auth flow, environment variables, and how to detect which auth type is active.

---

## Auth flow

```
1. User is not logged in → ProtectedRoute shows <UnauthenticatedPage>
   → User clicks "Ir a Humand" → redirected to main Humand app

2. From Humand app, user triggers OAuth → Janus redirects to /api/auth/callback?code=...

3. /api/auth/callback → api/auth/[...path].ts
   → exchanges code for tokens via Janus server-side
   → sets HttpOnly cookies (hu_access_token, hu_refresh_token)
   → redirects to /

4. AuthProvider calls /api/auth/me on mount
   → resolveSession() reads cookies, auto-renews if expired
   → returns user → ProtectedRoute renders children
```

## Environment variables

| Variable | Side | Purpose |
|---|---|---|
| `HUMAND_CLIENT_ID` | Server | OAuth2 client ID |
| `HUMAND_CLIENT_SECRET` | Server | OAuth2 client secret |
| `JANUS_URL` | Server | Always `https://api.humand.co/api/v1/janus` |
| `REDIRECT_URI` | Server | Registered redirect URI in Janus console |
| `VITE_HUMAND_APP_URL` | Client | Humand app URL (shown on unauthenticated screen) |

- Secrets (`HUMAND_CLIENT_ID`, `HUMAND_CLIENT_SECRET`, `JANUS_URL`, `REDIRECT_URI`) → `.env.local` only, never committed.
- Public var (`VITE_HUMAND_APP_URL`) → `.env.local` only (no need in `.env` for sandboxes).

## Detecting installed auth type

The marker lives in `src/App.tsx`:

```bash
grep '@humand-auth' src/App.tsx
```

| Marker | Installed by |
|---|---|
| `// @humand-auth: janus-oauth2` | `add-login` |
| `// @humand-auth: super-admin` | `add-super-admin-login` |

## Key files

| File | Purpose |
|---|---|
| `api/auth/_lib.ts` | Session resolver, token exchange, cookie helpers |
| `api/auth/[...path].ts` | Vercel routes: `/callback`, `/me`, `/refresh`, `/logout` |
| `src/providers/AuthProvider.tsx` | React context + `useAuth()` hook |
| `src/providers/ProtectedRoute.tsx` | Route guard — renders children only when authenticated |
| `src/pages/Unauthenticated/index.tsx` | "Acceso restringido" page |
| `src/pages/AuthError/index.tsx` | Auth error page (route `/error`) |
