# URL-Based Mock Authentication

This document describes how to use URL hash parameters to log in as different users during development, with automatic session persistence.

## Overview

Instead of hardcoding a single user in `.env`, you can now log in as different users by visiting URLs with hash parameters. The session persists across page reloads via localStorage.

## Usage

### Basic Login via URL

Visit your local frontend with the `#tgWebAppData` hash parameter:

```
http://localhost:5173/#tgWebAppData=<URL_ENCODED_INIT_DATA>&tgWebAppVersion=7.0&tgWebAppPlatform=weba
```

**Example:**
```
http://localhost:5173/#tgWebAppData=user=%7B%22id%22%3A12230%2C%22first_name%22%3A%22first002%22%2C%22username%22%3A%22user002%22%2C%22language_code%22%3A%22en%22%7D&auth_date=1765949842&query_id=dev-query-id&start_param=1oaw3cbi3n&hash=ba669ed8497f42d201a27355d6d066481e633862b95eef87ce66077a2b94943c&tgWebAppVersion=7.0&tgWebAppPlatform=weba
```

### What Happens

1. **URL is parsed:** The frontend extracts `tgWebAppData` from the URL hash
2. **Saved to localStorage:** The `initData` is saved to `localStorage.mockTelegramInitData`
3. **URL is cleaned:** The hash is removed from the URL to keep it clean
4. **Session persists:** On page reload, the saved `initData` is used automatically

### Switching Users

To switch to a different user:

1. Generate new `initData` for the new user:
   ```bash
   python scripts/generate_telegram_init_data.py --user-id 99999 --username newuser
   ```

2. Visit the URL with the new `initData`:
   ```
   http://localhost:5173/#tgWebAppData=<NEW_INIT_DATA>&tgWebAppVersion=7.0&tgWebAppPlatform=weba
   ```

3. The new user session will replace the old one in localStorage

### Clearing Session

To log out or clear the current mock session:

```javascript
// In browser console
localStorage.removeItem('mockTelegramInitData');
location.reload();
```

## Priority Order

The frontend checks for `initData` in this order:

1. **URL hash parameter** (`#tgWebAppData=...`) - Highest priority
2. **localStorage** (`mockTelegramInitData`) - Persisted from previous URL login
3. **Environment variable** (`VITE_MOCK_TELEGRAM_INIT_DATA`) - Fallback from `.env`

## Testing Referrals

To test referrals with URL-based auth:

1. **Get the referrer's code:**
   ```bash
   python manage.py shell
   >>> from apps.users.models import User
   >>> referrer = User.objects.get(telegram_user_id=12345)
   >>> print(referrer.referral_code)  # e.g., "1oaw3cbi3n"
   ```

2. **Generate initData for new user with referral:**
   ```bash
   python scripts/generate_telegram_init_data.py \
     --user-id 99999 \
     --username newuser \
     --start-param 1oaw3cbi3n
   ```

3. **Visit URL with the generated initData:**
   ```
   http://localhost:5173/#tgWebAppData=<INIT_DATA_WITH_START_PARAM>&tgWebAppVersion=7.0&tgWebAppPlatform=weba
   ```

4. The new user will be created with `referred_by` set to the referrer

## Implementation Details

### Frontend Hook

The `useTelegram` hook (`src/hooks/useTelegram.ts`) implements the URL parsing:

```typescript
const getMockInitData = () => {
  if (!mockAllowed) return null;

  // Check URL hash first
  const hash = window.location.hash.slice(1);
  if (hash) {
    const hashParams = new URLSearchParams(hash);
    const tgWebAppData = hashParams.get('tgWebAppData');
    if (tgWebAppData) {
      localStorage.setItem('mockTelegramInitData', tgWebAppData);
      window.history.replaceState(null, '', window.location.pathname);
      return tgWebAppData;
    }
  }

  // Fallback to localStorage or env var
  return localStorage.getItem('mockTelegramInitData') || 
         import.meta.env.VITE_MOCK_TELEGRAM_INIT_DATA || 
         null;
};
```

### URL Format

The URL hash follows Telegram's WebApp format:
- `tgWebAppData`: URL-encoded `initData` string (required)
- `tgWebAppVersion`: Version string (optional, e.g., `7.0`)
- `tgWebAppPlatform`: Platform identifier (optional, e.g., `weba`)

Only `tgWebAppData` is extracted and used for authentication.

## Advantages

✅ **No .env editing:** Switch users without restarting the dev server  
✅ **Session persistence:** Stays logged in across page reloads  
✅ **Clean URLs:** Hash is removed after parsing  
✅ **Easy sharing:** Share URLs with teammates for testing specific scenarios  
✅ **Referral testing:** Easy to test referral flows with different users

## Troubleshooting

### "Still logged in as old user"

The localStorage value takes precedence over `.env`. Clear it:
```javascript
localStorage.removeItem('mockTelegramInitData');
location.reload();
```

### "URL doesn't work"

- Ensure `VITE_ENABLE_MOCK_TELEGRAM=true` is set in `.env`
- Verify the `initData` is properly URL-encoded
- Check browser console for warnings from `useTelegram` hook

### "initData expired"

Regenerate with a fresh timestamp:
```bash
python scripts/generate_telegram_init_data.py --user-id 12345 --username testuser
```
