Skip to content

Commit b451e9c

Browse files
committed
fix issue causing the better-auth table to be deleted after db reset
1 parent b7ce6f9 commit b451e9c

File tree

7 files changed

+141
-23
lines changed

7 files changed

+141
-23
lines changed

docs/authentication.md

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,19 @@ openssl rand -base64 32
4949

5050
## Database Setup
5151

52-
### Run Better Auth Migration
52+
### Better Auth Tables
5353

5454
The authentication system requires additional database tables:
55+
- `user` - User accounts with email, name, image
56+
- `session` - Active user sessions
57+
- `account` - OAuth and credential accounts
58+
- `verification` - Email verification and password reset tokens
59+
60+
**Automatic Setup**: These tables are automatically created when you run `python init_db.py` or any database reset script.
61+
62+
**Manual Migration** (if needed):
63+
64+
If you have an existing database without Better Auth tables, you can add them manually:
5565

5666
```bash
5767
cd web-next
@@ -65,12 +75,6 @@ cd web-next
6575
pnpm auth:migrate
6676
```
6777

68-
This creates the following tables:
69-
- `user` - User accounts with email, name, image
70-
- `session` - Active user sessions
71-
- `account` - OAuth and credential accounts
72-
- `verification` - Email verification and password reset tokens
73-
7478
**Note**: The migration script is idempotent and safe to run multiple times.
7579

7680
### Schema Details

docs/database-reset-fix.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Database Reset Fix - Better Auth Tables
2+
3+
## Problem
4+
When resetting the database using `init_db.py`, `reset_db.py`, or `scripts/reset_db.sh`, the Better Auth tables were not being created, causing "Failed to sign up" errors.
5+
6+
## Root Cause
7+
The database initialization scripts only loaded `migrations/schema.sql`, which contains the main application tables (students, cards, accounts, etc.) but not the Better Auth tables (user, session, account, verification).
8+
9+
## Solution Applied
10+
Updated all database initialization scripts to automatically include Better Auth schema:
11+
12+
### Files Modified
13+
1. **`init_db.py`** - Added Better Auth schema loading
14+
2. **`reset_db.py`** - Added Better Auth schema to initialize_database()
15+
3. **`scripts/reset_db.sh`** - Added Better Auth migration step
16+
17+
### Documentation Updated
18+
1. **`docs/getting-started.md`** - Updated Database Setup section to mention Better Auth tables
19+
2. **`docs/authentication.md`** - Clarified that Better Auth tables are now automatic
20+
3. **`docs/troubleshooting.md`** - Updated signup code troubleshooting and added "Failed to sign up" section
21+
22+
## How It Works Now
23+
When you run any of these commands:
24+
```bash
25+
python init_db.py
26+
python reset_db.py
27+
./scripts/reset_db.sh
28+
```
29+
30+
They will automatically:
31+
1. Create main tables from `migrations/schema.sql`
32+
2. Create Better Auth tables from `web-next/migrations/better_auth_schema.sql`
33+
3. Print confirmation that both schemas were applied
34+
35+
## Verification
36+
After any database reset, verify all tables exist:
37+
```bash
38+
sqlite3 stuco.db ".tables"
39+
```
40+
41+
Should include: `account`, `session`, `user`, `verification` (Better Auth) plus your application tables.
42+
43+
## Environment Variable Fix
44+
Also fixed the signup code issue:
45+
- The `SIGNUP_CODE` environment variable in `web-next/.env.local` should NOT have quotes
46+
- Correct: `SIGNUP_CODE=Xn0tj#9y`
47+
- Wrong: `SIGNUP_CODE="Xn0tj#9y"`
48+
49+
After changing environment variables, always restart the web server:
50+
```bash
51+
sudo systemctl restart stuco-web
52+
```
53+
54+
## Date Applied
55+
November 13, 2025
56+

docs/getting-started.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,15 +80,17 @@ This verifies all tools and provides installation instructions if missing.
8080
python init_db.py
8181
```
8282

83-
This creates `stuco.db` with the schema from `migrations/schema.sql` (students, cards, accounts, transactions, overdraft_weeks).
83+
This creates `stuco.db` with:
84+
- Main schema from `migrations/schema.sql` (students, cards, accounts, transactions, overdraft_weeks)
85+
- Better Auth schema (user, session, account, verification) for web authentication
8486

8587
2. **Verify**:
8688

8789
```bash
8890
sqlite3 stuco.db ".tables"
8991
```
9092

91-
Should show all tables.
93+
Should show all tables including Better Auth tables (account, session, user, verification).
9294

9395
3. **Optional: Run Migrations** (if needed):
9496

docs/troubleshooting.md

Lines changed: 42 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -150,23 +150,27 @@ pnpm install
150150

151151
**Solutions**:
152152

153-
1. **Verify Code in Source**:
153+
1. **Check Environment Variable**:
154154

155-
Check `web-next/app/(auth)/signup/page.tsx`:
156-
```typescript
157-
const SIGNUP_CODE = "12345678"; // Current code
155+
Verify the `SIGNUP_CODE` is set in `web-next/.env.local`:
156+
```env
157+
SIGNUP_CODE=your_code_here
158158
```
159-
160-
2. **Check Environment Variable**:
161159

162-
If using env var, verify `.env.local`:
163-
```env
164-
NEXT_PUBLIC_SIGNUP_CODE=your_code
160+
Note: Do NOT use quotes around the value (use `SIGNUP_CODE=abc123` not `SIGNUP_CODE="abc123"`)
161+
162+
2. **Restart Server**: After changing `.env.local`, restart the server:
163+
```bash
164+
cd web-next
165+
# Stop the server (Ctrl+C), then:
166+
pnpm dev
167+
# Or in production:
168+
sudo systemctl restart stuco-web
165169
```
166170

167-
3. **Restart Server**: After changing code, restart dev server
171+
3. **Verify Code Has No Spaces**: Ensure the code has no leading/trailing spaces
168172

169-
4. **No Spaces**: Ensure code has no leading/trailing spaces
173+
4. **Check Server Logs**: Look for "SIGNUP_CODE environment variable is not set" errors
170174

171175
### "CORS error" or "Origin not allowed"
172176

@@ -176,13 +180,37 @@ pnpm install
176180
2. **Check trustedOrigins**: In `web-next/lib/auth.ts`
177181
3. **Browser Console**: Check exact error message
178182

183+
### "Failed to sign up" Error
184+
185+
**Problem**: Signup code is accepted but account creation fails.
186+
187+
**Cause**: Better Auth database tables are missing (usually after a database reset).
188+
189+
**Solution**:
190+
191+
Since v2.0+, Better Auth tables are automatically created by `init_db.py` and reset scripts. If you're using an older database or manually reset it, run:
192+
193+
```bash
194+
cd web-next
195+
sqlite3 ../stuco.db < migrations/better_auth_schema.sql
196+
sudo systemctl restart stuco-web
197+
```
198+
199+
**Verify tables exist**:
200+
```bash
201+
sqlite3 stuco.db "SELECT name FROM sqlite_master WHERE type='table' AND name IN ('user', 'session', 'account', 'verification');"
202+
```
203+
204+
Should return all 4 table names.
205+
179206
### "Database error" or "Table not found"
180207

181208
**Solutions**:
182209

183-
1. **Run Migration**: See [Authentication Guide](authentication.md#database-setup)
184-
2. **Check DATABASE_PATH**: Must be absolute path
185-
3. **Verify Permissions**: Database file must be readable/writable
210+
1. **Check Better Auth Tables**: Run the verification command above to ensure auth tables exist
211+
2. **Run Database Init**: If starting fresh, use `python init_db.py` (automatically includes Better Auth tables)
212+
3. **Check DATABASE_PATH**: Must be absolute path in `.env.local`
213+
4. **Verify Permissions**: Database file must be readable/writable by the web server user
186214

187215
### Testing Authentication
188216

init_db.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,27 @@
22

33
DB = "stuco.db"
44
SCHEMA_FILE = "migrations/schema.sql"
5+
BETTER_AUTH_SCHEMA = "web-next/migrations/better_auth_schema.sql"
56

67
con = sqlite3.connect(DB)
78
con.execute("PRAGMA journal_mode=WAL;") # enable Write-Ahead Logging for smoother writes/reads
89
con.execute("PRAGMA foreign_keys=ON;") # enforce FK relations
910
con.execute("PRAGMA busy_timeout=5000;") # handle brief contention politely
1011

12+
# Load main schema
1113
with open(SCHEMA_FILE,"r",encoding="utf-8") as f:
1214
con.executescript(f.read())
1315

16+
# Load Better Auth schema
17+
if os.path.exists(BETTER_AUTH_SCHEMA):
18+
with open(BETTER_AUTH_SCHEMA,"r",encoding="utf-8") as f:
19+
con.executescript(f.read())
20+
print("✓ Better Auth schema applied")
21+
else:
22+
print("⚠ Better Auth schema not found, skipping")
23+
1424
con.commit()
1525
con.close()
1626
print("Database initialized at", os.path.abspath(DB))
27+
print("✓ Main schema applied")
1728

reset_db.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,19 @@ def initialize_database():
6666
con.execute("PRAGMA foreign_keys=ON;")
6767
con.execute("PRAGMA busy_timeout=5000;")
6868

69+
# Load main schema
6970
with open(SCHEMA_FILE, "r", encoding="utf-8") as f:
7071
con.executescript(f.read())
7172

73+
# Load Better Auth schema
74+
BETTER_AUTH_SCHEMA = "web-next/migrations/better_auth_schema.sql"
75+
if os.path.exists(BETTER_AUTH_SCHEMA):
76+
with open(BETTER_AUTH_SCHEMA, "r", encoding="utf-8") as f:
77+
con.executescript(f.read())
78+
print("✓ Better Auth schema applied")
79+
else:
80+
print("⚠ Better Auth schema not found, skipping")
81+
7282
con.commit()
7383
return con
7484

scripts/reset_db.sh

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,13 @@ echo "------------------------------------------------------------"
6868
# Initialize database
6969
python3 init_db.py
7070

71+
# Apply Better Auth migration
72+
if [ -f "web-next/migrations/better_auth_schema.sql" ]; then
73+
echo "Applying Better Auth migration..."
74+
sqlite3 "$DB_FILE" < "web-next/migrations/better_auth_schema.sql"
75+
echo "✓ Better Auth schema applied"
76+
fi
77+
7178
echo ""
7279
echo "============================================================"
7380
echo "✓ Database reset complete!"

0 commit comments

Comments
 (0)