Skip to content

Commit 56db30d

Browse files
committed
CRITICAL FIX: Correct authentication architecture
🚨 IMPORTANT: Preview environments should use Firebase Auth, NOT dev auth Fixed authentication logic: - Local development: Dev auth + test credentials + DEV_ data - Vercel preview: Firebase auth + real credentials + production data - Vercel production: Firebase auth + real credentials + production data Changes: - Removed incorrect preview environment dev auth logic - Updated all auth routes to only use dev auth in local development - Fixed AuthProvider client-side environment detection - Created comprehensive authentication architecture documentation - Updated environment architecture docs with auth requirements Preview environments should now accept jamiegray2234@gmail.com and reject test credentials.
1 parent a6e0d78 commit 56db30d

6 files changed

Lines changed: 223 additions & 52 deletions

File tree

app/api/auth/login/route.ts

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -49,26 +49,28 @@ function createSuccessResponse(user: LoginResponse['user']): NextResponse {
4949
export async function POST(request: NextRequest) {
5050
try {
5151
console.log('[Auth] Login request received');
52+
console.log('[Auth] Request headers:', Object.fromEntries(request.headers.entries()));
53+
console.log('[Auth] Request URL:', request.url);
5254

5355
const body = await request.json() as LoginRequest;
5456
const { emailOrUsername, password } = body;
5557

58+
console.log('[Auth] Login attempt for:', emailOrUsername);
59+
console.log('[Auth] Password provided:', password ? 'YES' : 'NO');
60+
5661
// Validate required fields
5762
if (!emailOrUsername || !password) {
63+
console.log('[Auth] Missing required fields');
5864
return createErrorResponse('Email/username and password are required');
5965
}
6066

6167
// Check if we should use dev auth system
62-
// Use dev auth for:
63-
// 1. Local development (NODE_ENV=development + USE_DEV_AUTH=true)
64-
// 2. Preview environments (VERCEL_ENV=preview) - for testing with production data
65-
const environmentType = getEnvironmentType();
66-
const isLocalDev = process.env.NODE_ENV === 'development' && process.env.USE_DEV_AUTH === 'true';
67-
const isPreviewEnv = environmentType === 'preview';
68-
const useDevAuth = isLocalDev || isPreviewEnv;
68+
// ONLY use dev auth for local development with USE_DEV_AUTH=true
69+
// Preview and production environments should use Firebase Auth with real credentials
70+
const useDevAuth = process.env.NODE_ENV === 'development' && process.env.USE_DEV_AUTH === 'true';
6971

7072
if (useDevAuth) {
71-
console.log(`[Auth] Using dev auth system (environment: ${environmentType}, local dev: ${isLocalDev}, preview: ${isPreviewEnv})`);
73+
console.log('[Auth] Using dev auth system (local development only)');
7274

7375
// In development mode, check against known test accounts
7476
const testAccounts = [
@@ -82,7 +84,7 @@ export async function POST(request: NextRequest) {
8284
);
8385

8486
if (!account) {
85-
console.log(`[Auth] Dev auth login failed: invalid credentials (environment: ${environmentType})`);
87+
console.log('[Auth] Dev auth login failed: invalid credentials');
8688
return createErrorResponse('Invalid credentials');
8789
}
8890

@@ -103,7 +105,7 @@ export async function POST(request: NextRequest) {
103105
maxAge: 60 * 60 * 24 * 7 // 7 days
104106
});
105107

106-
console.log(`[Auth] Dev auth login successful for: ${account.email} (environment: ${environmentType})`);
108+
console.log('[Auth] Dev auth login successful for:', account.email);
107109

108110
return createSuccessResponse({
109111
uid: account.uid,

app/api/auth/session/route.ts

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,10 @@ export async function GET(request: NextRequest) {
4949
return createErrorResponse(AuthErrorCode.SESSION_EXPIRED, 'Invalid session data');
5050
}
5151

52-
// Check if we should use dev auth system (same logic as login)
53-
const environmentType = getEnvironmentType();
54-
const isLocalDev = process.env.NODE_ENV === 'development' && process.env.USE_DEV_AUTH === 'true';
55-
const isPreviewEnv = environmentType === 'preview';
56-
const useDevAuth = isLocalDev || isPreviewEnv;
52+
// Check if we should use dev auth system
53+
// ONLY use dev auth for local development with USE_DEV_AUTH=true
54+
// Preview and production environments should use Firebase Auth with real credentials
55+
const useDevAuth = process.env.NODE_ENV === 'development' && process.env.USE_DEV_AUTH === 'true';
5756

5857
if (useDevAuth) {
5958
const user: User = {
@@ -67,7 +66,7 @@ export async function GET(request: NextRequest) {
6766
lastLoginAt: new Date().toISOString()
6867
};
6968

70-
console.log(`[Session] Dev auth session valid for: ${user.email} (environment: ${environmentType})`);
69+
console.log('[Session] Dev auth session valid for:', user.email);
7170
return createSuccessResponse(user);
7271
}
7372

@@ -126,14 +125,13 @@ export async function POST(request: NextRequest) {
126125
return createErrorResponse(AuthErrorCode.INVALID_CREDENTIALS, 'ID token is required');
127126
}
128127

129-
// Check if we should use dev auth system (same logic as other auth routes)
130-
const environmentType = getEnvironmentType();
131-
const isLocalDev = process.env.NODE_ENV === 'development' && process.env.USE_DEV_AUTH === 'true';
132-
const isPreviewEnv = environmentType === 'preview';
133-
const useDevAuth = isLocalDev || isPreviewEnv;
128+
// Check if we should use dev auth system
129+
// ONLY use dev auth for local development with USE_DEV_AUTH=true
130+
// Preview and production environments should use Firebase Auth with real credentials
131+
const useDevAuth = process.env.NODE_ENV === 'development' && process.env.USE_DEV_AUTH === 'true';
134132

135133
if (useDevAuth) {
136-
console.log(`[Session] Dev auth mode: bypassing Firebase ID token verification (environment: ${environmentType})`);
134+
console.log('[Session] Dev auth mode: bypassing Firebase ID token verification (local development only)');
137135

138136
try {
139137
// In development mode, decode the token without verification
@@ -185,7 +183,7 @@ export async function POST(request: NextRequest) {
185183
lastActiveAt: new Date().toISOString()
186184
});
187185

188-
console.log(`[Session] Dev auth session created for: ${user.email} (environment: ${environmentType})`);
186+
console.log('[Session] Dev auth session created for:', user.email);
189187
return createSuccessResponse(user);
190188

191189
} catch (devError) {

app/api/debug/auth-environment/route.ts

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ export async function GET(request: NextRequest) {
1818
const environmentContext = getEnvironmentContext();
1919

2020
// Check auth configuration (same logic as login/session routes)
21-
const isLocalDev = process.env.NODE_ENV === 'development' && process.env.USE_DEV_AUTH === 'true';
22-
const isPreviewEnv = environmentType === 'preview';
23-
const useDevAuth = isLocalDev || isPreviewEnv;
21+
// ONLY use dev auth for local development with USE_DEV_AUTH=true
22+
// Preview and production environments should use Firebase Auth with real credentials
23+
const useDevAuth = process.env.NODE_ENV === 'development' && process.env.USE_DEV_AUTH === 'true';
2424

2525
// Log environment config for server logs
2626
logEnvironmentConfig();
@@ -36,10 +36,9 @@ export async function GET(request: NextRequest) {
3636
useDevAuth: process.env.USE_DEV_AUTH
3737
},
3838
authConfiguration: {
39-
isLocalDev,
40-
isPreviewEnv,
4139
useDevAuth,
42-
authSystem: useDevAuth ? 'dev-auth' : 'firebase-auth'
40+
authSystem: useDevAuth ? 'dev-auth' : 'firebase-auth',
41+
description: useDevAuth ? 'Local development with test accounts' : 'Production Firebase Auth with real credentials'
4342
},
4443
testCredentials: useDevAuth ? {
4544
available: [
@@ -54,24 +53,24 @@ export async function GET(request: NextRequest) {
5453
troubleshooting: {
5554
expectedBehavior: {
5655
'local development': 'Should use dev auth when USE_DEV_AUTH=true',
57-
'vercel preview': 'Should use dev auth for testing with production data',
58-
'vercel production': 'Should use Firebase auth with real credentials'
56+
'vercel preview': 'Should use Firebase auth with your production credentials',
57+
'vercel production': 'Should use Firebase auth with your production credentials'
5958
},
6059
commonIssues: {
61-
'401 on preview': 'Check that VERCEL_ENV=preview is set correctly',
62-
'wrong auth system': 'Verify environment detection logic',
63-
'missing credentials': 'Ensure test accounts exist in dev auth system'
60+
'401 on preview/production': 'Use your real Firebase Auth credentials (jamiegray2234@gmail.com)',
61+
'wrong auth system': 'Only local development should use dev auth',
62+
'missing credentials': 'Preview/production need real user accounts, not test accounts'
6463
}
6564
},
6665
recommendations: [
6766
...(useDevAuth ? [
6867
'Dev authentication is active - test users are available',
69-
'Use the provided test credentials for testing',
68+
'Use the provided test credentials for local development',
7069
'Production user accounts are protected from development access'
7170
] : [
72-
'Firebase Auth is active - use your production credentials',
73-
'Be careful when testing - you may be using real user accounts',
74-
'Consider using preview environment for safer testing'
71+
'Firebase Auth is active - use your real production credentials',
72+
'Use jamiegray2234@gmail.com or other real Firebase Auth accounts',
73+
'Preview environments test with production data using real credentials'
7574
])
7675
]
7776
};

app/providers/AuthProvider.tsx

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -103,15 +103,13 @@ export function AuthProvider({ children }: AuthProviderProps) {
103103
setLoading(true);
104104
clearError();
105105

106-
// Check if we should use dev auth system (client-side environment detection)
107-
// Note: Client-side can't access server-only env vars, so we use NEXT_PUBLIC_ vars and URL detection
108-
const isLocalDev = process.env.NODE_ENV === 'development' && process.env.NEXT_PUBLIC_USE_DEV_AUTH === 'true';
109-
const isPreviewEnv = typeof window !== 'undefined' &&
110-
(window.location.hostname.includes('vercel.app') || window.location.hostname.includes('preview'));
111-
const useDevAuth = isLocalDev || isPreviewEnv;
106+
// Check if we should use dev auth system
107+
// ONLY use dev auth for local development with NEXT_PUBLIC_USE_DEV_AUTH=true
108+
// Preview and production environments should use Firebase Auth with real credentials
109+
const useDevAuth = process.env.NODE_ENV === 'development' && process.env.NEXT_PUBLIC_USE_DEV_AUTH === 'true';
112110

113111
if (useDevAuth) {
114-
console.log(`[Auth] Using dev auth system (local dev: ${isLocalDev}, preview: ${isPreviewEnv}, hostname: ${typeof window !== 'undefined' ? window.location.hostname : 'server'})`);
112+
console.log('[Auth] Using dev auth system (local development only)');
115113

116114
// Use server-side login endpoint for development
117115
const loginResponse = await fetch('/api/auth/login', {
@@ -127,7 +125,7 @@ export function AuthProvider({ children }: AuthProviderProps) {
127125
const loginData = await loginResponse.json();
128126
if (loginData.success && loginData.user) {
129127
setUser(loginData.user);
130-
console.log(`[Auth] Dev auth sign in successful for user: ${loginData.user.email} (preview: ${isPreviewEnv})`);
128+
console.log('[Auth] Dev auth sign in successful for user:', loginData.user.email);
131129
} else {
132130
throw new AuthError(loginData.error || 'Login failed', AuthErrorCode.INVALID_CREDENTIALS);
133131
}
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
# Authentication Architecture
2+
3+
## 🚨 CRITICAL: Environment-Specific Authentication Rules
4+
5+
**This document defines the EXACT authentication behavior for each environment. Never deviate from these rules.**
6+
7+
## Authentication by Environment
8+
9+
### 🏠 **Local Development**
10+
- **Auth System**: Dev Auth (test accounts)
11+
- **Data Access**: DEV_ prefixed collections (isolated dev data)
12+
- **Credentials**: Test accounts only (jamie@wewrite.app, test@wewrite.app, etc.)
13+
- **Trigger**: `NODE_ENV=development` AND `USE_DEV_AUTH=true`
14+
15+
### 🔍 **Vercel Preview**
16+
- **Auth System**: Firebase Auth (production auth)
17+
- **Data Access**: Production collections (no DEV_ prefix)
18+
- **Credentials**: Real Firebase Auth accounts (jamiegray2234@gmail.com, etc.)
19+
- **Purpose**: Test with production data using real credentials
20+
21+
### 🚀 **Vercel Production**
22+
- **Auth System**: Firebase Auth (production auth)
23+
- **Data Access**: Production collections (no DEV_ prefix)
24+
- **Credentials**: Real Firebase Auth accounts (jamiegray2234@gmail.com, etc.)
25+
- **Purpose**: Live production environment
26+
27+
## Environment Detection Logic
28+
29+
### Server-Side (API Routes)
30+
```typescript
31+
// ONLY use dev auth for local development
32+
const useDevAuth = process.env.NODE_ENV === 'development' && process.env.USE_DEV_AUTH === 'true';
33+
34+
if (useDevAuth) {
35+
// Use test accounts and dev auth system
36+
} else {
37+
// Use Firebase Auth with real credentials
38+
}
39+
```
40+
41+
### Client-Side (AuthProvider)
42+
```typescript
43+
// ONLY use dev auth for local development
44+
const useDevAuth = process.env.NODE_ENV === 'development' && process.env.NEXT_PUBLIC_USE_DEV_AUTH === 'true';
45+
46+
if (useDevAuth) {
47+
// Call /api/auth/login with test credentials
48+
} else {
49+
// Use Firebase Auth SDK with real credentials
50+
}
51+
```
52+
53+
## Data Access Patterns
54+
55+
### Local Development
56+
- Collections: `DEV_users`, `DEV_pages`, `DEV_subscriptions`
57+
- Purpose: Isolated development data
58+
- Safety: Cannot affect production data
59+
60+
### Preview & Production
61+
- Collections: `users`, `pages`, `subscriptions` (base names)
62+
- Purpose: Real production data
63+
- Safety: Use real credentials, real data
64+
65+
## Test Credentials (Local Development Only)
66+
67+
```typescript
68+
const testAccounts = [
69+
{ email: 'jamie@wewrite.app', password: 'TestPassword123!', isAdmin: true },
70+
{ email: 'test@wewrite.app', password: 'TestPassword123!', isAdmin: false },
71+
{ email: 'getwewrite@gmail.com', password: 'TestPassword123!', isAdmin: false },
72+
{ email: 'test@local.dev', password: 'TestPassword123!', isAdmin: false }
73+
];
74+
```
75+
76+
**⚠️ These test credentials ONLY work in local development with dev auth enabled.**
77+
78+
## Production Credentials (Preview & Production)
79+
80+
Use real Firebase Auth accounts:
81+
- `jamiegray2234@gmail.com` (admin account)
82+
- Any other real Firebase Auth user accounts
83+
84+
## Common Mistakes to Avoid
85+
86+
### **WRONG: Using dev auth in preview**
87+
```typescript
88+
// DON'T DO THIS
89+
const isPreviewEnv = environmentType === 'preview';
90+
const useDevAuth = isLocalDev || isPreviewEnv; // WRONG!
91+
```
92+
93+
### **CORRECT: Only dev auth in local development**
94+
```typescript
95+
// DO THIS
96+
const useDevAuth = process.env.NODE_ENV === 'development' && process.env.USE_DEV_AUTH === 'true';
97+
```
98+
99+
### **WRONG: Expecting test credentials in preview**
100+
Preview environments should NOT accept `jamie@wewrite.app` or other test credentials.
101+
102+
### **CORRECT: Use real credentials in preview**
103+
Preview environments should accept `jamiegray2234@gmail.com` and other real Firebase Auth accounts.
104+
105+
## Debugging Authentication Issues
106+
107+
### Check Environment Detection
108+
Visit: `/api/debug/auth-environment`
109+
110+
Expected responses:
111+
112+
**Local Development:**
113+
```json
114+
{
115+
"environment": { "type": "development" },
116+
"authConfiguration": { "useDevAuth": true, "authSystem": "dev-auth" },
117+
"testCredentials": { "available": ["jamie@wewrite.app / TestPassword123!"] }
118+
}
119+
```
120+
121+
**Preview/Production:**
122+
```json
123+
{
124+
"environment": { "type": "preview" },
125+
"authConfiguration": { "useDevAuth": false, "authSystem": "firebase-auth" },
126+
"testCredentials": { "note": "Using Firebase Auth - use your production credentials" }
127+
}
128+
```
129+
130+
## Environment Variables
131+
132+
### Local Development
133+
```bash
134+
NODE_ENV=development
135+
USE_DEV_AUTH=true
136+
NEXT_PUBLIC_USE_DEV_AUTH=true
137+
```
138+
139+
### Preview/Production
140+
```bash
141+
NODE_ENV=production
142+
# USE_DEV_AUTH should be undefined or false
143+
# NEXT_PUBLIC_USE_DEV_AUTH should be undefined or false
144+
```
145+
146+
## File Locations
147+
148+
### Authentication Logic
149+
- **Login**: `app/api/auth/login/route.ts`
150+
- **Session**: `app/api/auth/session/route.ts`
151+
- **Client**: `app/providers/AuthProvider.tsx`
152+
153+
### Environment Detection
154+
- **Server**: `app/utils/environmentConfig.ts`
155+
- **Debug**: `app/api/debug/auth-environment/route.ts`
156+
157+
## Summary
158+
159+
**Remember: Preview environments are for testing with production data using real credentials, NOT for using test accounts with production data.**
160+
161+
- **Local**: Dev auth + dev data + test credentials
162+
- **Preview**: Firebase auth + production data + real credentials
163+
- **Production**: Firebase auth + production data + real credentials

docs/ENVIRONMENT_ARCHITECTURE.md

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,23 @@ This document provides a comprehensive overview of WeWrite's environment configu
66

77
WeWrite uses a **four-environment architecture** with strict data separation to ensure safe development and testing:
88

9-
| Environment | Data Source | Stripe Keys | Collections | Purpose |
10-
|-------------|-------------|-------------|-------------|---------|
11-
| **Local Development** | Dev Data | Test Keys | `dev_*` | Local development and testing |
12-
| **Vercel Dev** | Dev Data | Test Keys | `dev_*` | Development branch testing |
13-
| **Vercel Preview** | **Production Data** | Live Keys | No prefix | Pre-production testing with real data |
14-
| **Vercel Production** | Production Data | Live Keys | No prefix | Live production environment |
9+
| Environment | Data Source | Auth System | Collections | Credentials | Purpose |
10+
|-------------|-------------|-------------|-------------|-------------|---------|
11+
| **Local Development** | Dev Data | **Dev Auth** | `DEV_*` | Test accounts | Local development and testing |
12+
| **Vercel Preview** | **Production Data** | **Firebase Auth** | No prefix | Real accounts | Pre-production testing with real data |
13+
| **Vercel Production** | Production Data | **Firebase Auth** | No prefix | Real accounts | Live production environment |
14+
15+
## 🔐 Authentication Architecture
16+
17+
### Local Development
18+
- **Auth System**: Dev Auth (test accounts)
19+
- **Credentials**: `jamie@wewrite.app`, `test@wewrite.app` with `TestPassword123!`
20+
- **Data**: Isolated dev collections (`DEV_users`, `DEV_pages`, etc.)
21+
22+
### Preview & Production
23+
- **Auth System**: Firebase Auth (real accounts)
24+
- **Credentials**: `jamiegray2234@gmail.com` and other real Firebase users
25+
- **Data**: Production collections (`users`, `pages`, etc.)
1526

1627
## 🎯 Key Design Principles
1728

0 commit comments

Comments
 (0)