Skip to content

Commit 5baa02b

Browse files
committed
Feat Implements database schema and migration
Adds a database schema and migration system for the Nuxt Token Authentication module, designed to be Laravel Sanctum-like. This introduces database migrations, table creation, repository classes, and a database service with support for SQLite, MySQL, and PostgreSQL. Also adds a CLI tool to manage migrations.
1 parent 4650364 commit 5baa02b

File tree

12 files changed

+1516
-0
lines changed

12 files changed

+1516
-0
lines changed

docs/DATABASE_SCHEMA.md

Lines changed: 272 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,272 @@
1+
# Database Schema & Migration System
2+
3+
This document describes the database schema and migration system for the Nuxt Token Authentication module, designed to be Laravel Sanctum-like.
4+
5+
## Overview
6+
7+
The module uses a migration-based approach to manage database schema changes. This ensures that your database structure is version-controlled and can be easily deployed across different environments.
8+
9+
## Database Tables
10+
11+
### 1. Users Table (`users`)
12+
13+
The main users table stores user account information:
14+
15+
```sql
16+
CREATE TABLE users (
17+
id INTEGER PRIMARY KEY AUTOINCREMENT,
18+
name TEXT NOT NULL,
19+
email TEXT UNIQUE NOT NULL,
20+
password TEXT NOT NULL,
21+
email_verified_at TIMESTAMP,
22+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
23+
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
24+
);
25+
```
26+
27+
**Columns:**
28+
29+
- `id`: Primary key, auto-incrementing
30+
- `name`: User's display name
31+
- `email`: Unique email address
32+
- `password`: Hashed password (using bcrypt)
33+
- `email_verified_at`: Timestamp when email was verified
34+
- `created_at`: Record creation timestamp
35+
- `updated_at`: Record last update timestamp
36+
37+
**Indexes:**
38+
39+
- `idx_users_email`: Index on email for fast lookups
40+
41+
### 2. Personal Access Tokens Table (`personal_access_tokens`)
42+
43+
This table stores API tokens for authentication, similar to Laravel Sanctum:
44+
45+
```sql
46+
CREATE TABLE personal_access_tokens (
47+
id INTEGER PRIMARY KEY AUTOINCREMENT,
48+
tokenable_type TEXT NOT NULL,
49+
tokenable_id INTEGER NOT NULL,
50+
name TEXT NOT NULL,
51+
token TEXT UNIQUE NOT NULL,
52+
abilities TEXT,
53+
last_used_at TIMESTAMP,
54+
expires_at TIMESTAMP,
55+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
56+
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
57+
);
58+
```
59+
60+
**Columns:**
61+
62+
- `id`: Primary key, auto-incrementing
63+
- `tokenable_type`: Type of the token owner (e.g., 'App\\Models\\User')
64+
- `tokenable_id`: ID of the token owner
65+
- `name`: Human-readable name for the token
66+
- `token`: Unique token hash
67+
- `abilities`: JSON string of token permissions
68+
- `last_used_at`: Last time the token was used
69+
- `expires_at`: Token expiration timestamp
70+
- `created_at`: Token creation timestamp
71+
- `updated_at`: Token last update timestamp
72+
73+
**Indexes:**
74+
75+
- `idx_personal_access_tokens_tokenable`: Composite index on tokenable_type and tokenable_id
76+
- `idx_personal_access_tokens_token`: Index on token for fast lookups
77+
- `idx_personal_access_tokens_expires`: Index on expires_at for cleanup queries
78+
79+
### 3. Password Reset Tokens Table (`password_reset_tokens`)
80+
81+
Stores temporary tokens for password reset functionality:
82+
83+
```sql
84+
CREATE TABLE password_reset_tokens (
85+
id INTEGER PRIMARY KEY AUTOINCREMENT,
86+
email TEXT NOT NULL,
87+
token TEXT UNIQUE NOT NULL,
88+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
89+
);
90+
```
91+
92+
**Columns:**
93+
94+
- `id`: Primary key, auto-incrementing
95+
- `email`: Email address requesting password reset
96+
- `token`: Unique reset token
97+
- `created_at`: Token creation timestamp
98+
99+
**Indexes:**
100+
101+
- `idx_password_reset_tokens_email`: Index on email
102+
- `idx_password_reset_tokens_token`: Index on token
103+
104+
### 4. Migrations Table (`migrations`)
105+
106+
Tracks which migrations have been executed:
107+
108+
```sql
109+
CREATE TABLE migrations (
110+
id INTEGER PRIMARY KEY AUTOINCREMENT,
111+
version INTEGER NOT NULL,
112+
name TEXT NOT NULL,
113+
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
114+
);
115+
```
116+
117+
**Columns:**
118+
119+
- `id`: Primary key, auto-incrementing
120+
- `version`: Migration version number
121+
- `name`: Migration name
122+
- `executed_at`: When the migration was executed
123+
124+
## Migration System
125+
126+
### Available Migrations
127+
128+
1. **create_migrations_table** (v2)
129+
130+
- Creates the migrations tracking table
131+
132+
2. **create_personal_access_tokens_table** (v1)
133+
134+
- Creates the personal access tokens table with indexes
135+
136+
3. **update_users_table** (v3)
137+
138+
- Creates or updates the users table with proper structure
139+
- Adds missing columns if table already exists
140+
141+
4. **create_password_reset_tokens_table** (v4)
142+
- Creates the password reset tokens table with indexes
143+
144+
### Running Migrations
145+
146+
#### Using the CLI
147+
148+
```bash
149+
# Run all pending migrations
150+
npx nuxt-token-authentication migrate up
151+
152+
# Check migration status
153+
npx nuxt-token-authentication migrate status
154+
155+
# Rollback last migration
156+
npx nuxt-token-authentication migrate rollback
157+
158+
# Rollback multiple migrations
159+
npx nuxt-token-authentication migrate rollback 3
160+
```
161+
162+
#### Programmatically
163+
164+
```typescript
165+
import { useDatabaseService } from "nuxt-token-authentication/server/database";
166+
167+
const dbService = useDatabaseService(options);
168+
169+
// Run migrations
170+
await dbService.runMigrations();
171+
172+
// Check status
173+
const status = await dbService.getMigrationStatus();
174+
175+
// Rollback
176+
await dbService.rollbackMigrations(1);
177+
```
178+
179+
### Migration Lifecycle
180+
181+
1. **Development**: Create new migration files in `src/runtime/server/database/migrations/`
182+
2. **Testing**: Run migrations in test environment
183+
3. **Production**: Run migrations during deployment
184+
4. **Rollback**: Use rollback commands if needed
185+
186+
## Token Abilities
187+
188+
Tokens can have specific abilities (permissions) defined as JSON strings:
189+
190+
```typescript
191+
// Example abilities
192+
const abilities = ["read", "write", "delete"];
193+
const adminAbilities = ["*"]; // All permissions
194+
const readOnlyAbilities = ["read"];
195+
```
196+
197+
## Security Considerations
198+
199+
1. **Token Hashing**: All tokens are stored as hashed values
200+
2. **Expiration**: Tokens can have expiration dates
201+
3. **Abilities**: Fine-grained permission control
202+
4. **Cleanup**: Expired tokens are automatically cleaned up
203+
5. **Rate Limiting**: Built-in rate limiting for auth endpoints
204+
205+
## Database Connectors
206+
207+
The module supports multiple database connectors:
208+
209+
- **SQLite**: Default, file-based database
210+
- **MySQL**: Production-ready relational database
211+
- **PostgreSQL**: Advanced relational database
212+
213+
### Configuration Example
214+
215+
```typescript
216+
export default defineNuxtConfig({
217+
nuxtTokenAuthentication: {
218+
connector: {
219+
name: "sqlite", // or 'mysql', 'postgresql'
220+
options: {
221+
path: "./data/db.sqlite3", // SQLite
222+
// host: 'localhost', // MySQL/PostgreSQL
223+
// port: 3306, // MySQL/PostgreSQL
224+
// database: 'myapp', // MySQL/PostgreSQL
225+
// username: 'user', // MySQL/PostgreSQL
226+
// password: 'password', // MySQL/PostgreSQL
227+
},
228+
},
229+
},
230+
});
231+
```
232+
233+
## Best Practices
234+
235+
1. **Always run migrations** before starting your application
236+
2. **Backup your database** before running migrations in production
237+
3. **Test migrations** in a staging environment first
238+
4. **Use meaningful migration names** for better tracking
239+
5. **Keep migrations small** and focused on single changes
240+
6. **Version control** your migration files
241+
242+
## Troubleshooting
243+
244+
### Common Issues
245+
246+
1. **Migration already exists**: Check the migrations table for conflicts
247+
2. **Database locked**: Ensure no other processes are using the database
248+
3. **Permission denied**: Check file/directory permissions for SQLite
249+
4. **Connection failed**: Verify database connection settings
250+
251+
### Debugging
252+
253+
Enable debug logging to see detailed migration information:
254+
255+
```typescript
256+
// In your Nuxt config
257+
export default defineNuxtConfig({
258+
nuxtTokenAuthentication: {
259+
debug: true, // Enable debug logging
260+
},
261+
});
262+
```
263+
264+
## Next Steps
265+
266+
After setting up the database schema, you can:
267+
268+
1. Create authentication endpoints
269+
2. Implement token generation and validation
270+
3. Add user management features
271+
4. Set up password reset functionality
272+
5. Configure rate limiting and security features

0 commit comments

Comments
 (0)