đī¸ CreatorContent.net
U
User
!
-
!
-
Manage Subscription
Manage Tokens
Storage
Media Library â
Documentation
User Dashboard
Podcasts
Podcasts
Episodes
Transcriptions
Contributors
Studio
Public Profile
Public Profiles
Blog
Event Lists
Surveys
Contact Forms
Subscribers
Notifications & Shoutouts
Development
React Test
Media Library
Help Center
Admin Dashboard
Logout
Back to Documentation
Authentication
Authentication
File: 02-authentication.md
Documentation Index
Loading documentation...
# Authentication System ## Overview CreatorContent.net uses Laravel Sanctum with a custom token-based authentication system that provides secure, session-like authentication via HTTP-only cookies. The system supports multiple login methods including password-based and OTP (One-Time Password) authentication. ## Architecture ### Authentication Flow 1. **Login Request** â User submits credentials (password or requests OTP) 2. **Token Creation** â Laravel Sanctum creates PersonalAccessToken 3. **Cookie Storage** â Token stored in HTTP-only cookie (`auth_token`) 4. **Token Validation** â `TokenAuth` middleware validates token on each request 5. **User Authentication** â User is authenticated via `auth()->login($user)` ### Token Storage - **Storage Method**: HTTP-only cookie - **Cookie Name**: `auth_token` - **Expiration**: 7 days from creation - **SameSite**: Lax (for password login) / Strict (for OTP login) - **Secure**: HTTPS only (true) - **HttpOnly**: Yes (prevents XSS attacks) ## Database Schema ### Users Table ```sql users: - id (bigint, primary key) - username (string, unique) - URL-safe identifier - name (string) - Full name - email (string, unique) - phone (string, nullable, unique) - E.164 format - password (string, hashed) - Bcrypt - role (enum: 'creator', 'viewer', 'admin') - email_verified_at (timestamp, nullable) - phone_verified_at (timestamp, nullable) - two_factor_enabled (boolean, default false) - is_suspended (boolean, default false) - is_admin (boolean, default false) - created_at, updated_at (timestamps) ``` ### Login Tokens Table (for OTP) ```sql login_tokens: - id (bigint, primary key) - user_id (bigint, foreign key to users) - token (string, unique) - 8-digit OTP - type (enum: 'email', 'phone', 'phone_change', 'password_reset') - expires_at (timestamp) - 10 minutes - created_at, updated_at (timestamps) ``` ### Personal Access Tokens (Sanctum) ```sql personal_access_tokens: - id (bigint, primary key) - tokenable_type (string) - 'App\Models\User' - tokenable_id (bigint) - User ID - name (string) - 'auth-token' - token (string, unique) - Hashed token - abilities (text, nullable) - last_used_at (timestamp, nullable) - expires_at (timestamp, nullable) - created_at, updated_at (timestamps) ``` ## Login Methods ### 1. Password-Based Authentication Users can log in with: - **Email + Password** - **Phone + Password** - **Username + Password** **API Endpoint**: `POST /api/login` **Request**: ```json { "identifier": "user@example.com", "method": "password", "password": "password123" } ``` **Response**: ```json { "success": true, "message": "Login successful.", "user": { "id": 1, "username": "testuser", "name": "Test User", "email": "test@example.com", "phone": "+1234567890", "role": "creator", "is_admin": false } } ``` Cookie is automatically set via `Set-Cookie` header. ### 2. OTP Authentication Users can log in with one-time passwords sent via: - **Email OTP**: 8-digit code sent to email - **Phone OTP**: 8-digit code sent via SMS **Step 1 - Request OTP**: `POST /api/login` ```json { "identifier": "user@example.com", "method": "otp" } ``` **Response**: ```json { "success": true, "message": "OTP sent to your email.", "expires_at": "2024-06-27T23:00:00.000000Z" } ``` **Step 2 - Verify OTP**: `POST /api/login` ```json { "identifier": "user@example.com", "method": "otp", "token": "12345678" } ``` **Note**: OTP tokens expire after 10 minutes and are single-use. ## Registration **API Endpoint**: `POST /api/register` **Request**: ```json { "username": "newuser", "name": "New User", "email": "newuser@example.com", "phone": "+1234567890", "password": "password123", "password_confirmation": "password123", "role": "creator" } ``` **Validation**: - Username must be unique, URL-safe (alphanumeric + hyphens) - Email must be unique - Phone must be unique (if provided), E.164 format - Password minimum 8 characters **Response**: ```json { "success": true, "message": "Registration successful!", "user": { "id": 2, "username": "newuser", "name": "New User", "email": "newuser@example.com", "role": "creator" } } ``` Cookie is set automatically upon successful registration. ## Verification System ### Email Verification **Send Verification Code**: `POST /api/send-verification-email` ```json { "email": "user@example.com" } ``` **Verify Email**: `POST /api/verify-email` ```json { "email": "user@example.com", "token": "12345678" } ``` ### Phone Verification **Send Verification Code**: `POST /api/send-verification-phone` ```json { "phone": "+1234567890" } ``` **Verify Phone**: `POST /api/verify-phone` ```json { "phone": "+1234567890", "token": "12345678" } ``` **Note**: OTP login requires email or phone to be verified first. ## Password Reset ### Email Password Reset **Request Reset**: `POST /api/password/reset/email` ```json { "email": "user@example.com" } ``` **Reset Password**: `POST /api/password/reset` ```json { "identifier": "user@example.com", "token": "12345678", "password": "newpassword123", "password_confirmation": "newpassword123" } ``` ### SMS Password Reset **Request Reset**: `POST /api/password/reset/sms` ```json { "phone": "+1234567890" } ``` **Reset Password**: Same as email method above. ## Token Authentication Middleware ### TokenAuth Middleware Located in: `app/Http/Middleware/TokenAuth.php` **Process**: 1. Retrieves token from `auth_token` cookie 2. Finds token in `personal_access_tokens` table via Sanctum 3. Validates token is not expired (7-day limit) 4. Checks user is not suspended 5. Authenticates user via `auth()->login($user)` **Usage**: ```php Route::middleware('token.auth')->group(function () { Route::get('/api/user', [AuthController::class, 'me']); // Protected routes... }); ``` **Responses**: - **Unauthorized (401)**: Returns JSON error for API routes - **Redirect to Login**: Redirects to login page for web routes ## Profile Management ### Get Current User **Endpoint**: `GET /api/user` **Headers**: Requires authentication (token in cookie) **Response**: ```json { "success": true, "user": { "id": 1, "username": "testuser", "name": "Test User", "email": "test@example.com", "phone": "+1234567890", "role": "creator", "email_verified_at": "2024-06-27T22:00:00.000000Z", "phone_verified_at": "2024-06-27T22:00:00.000000Z" } } ``` ### Update Profile **Endpoint**: `POST /api/profile/update` **Request**: ```json { "name": "Updated Name", "role": "viewer" } ``` ### Change Password **Endpoint**: `POST /api/profile/password/change` **Request**: ```json { "current_password": "oldpassword123", "new_password": "newpassword123", "new_password_confirmation": "newpassword123" } ``` ### Change Phone Number **Step 1 - Send Token**: `POST /api/profile/phone/send-token` ```json { "new_phone": "+1987654321" } ``` **Step 2 - Change Phone**: `POST /api/profile/phone/change` ```json { "new_phone": "+1987654321", "token": "12345678" } ``` ## Logout **Endpoint**: `POST /api/logout` **Response**: ```json { "success": true, "message": "Logged out successfully." } ``` **Action**: - Destroys the authentication token - Cookie is automatically invalidated - User session is cleared ## Security Features ### Token Security - **HTTP-only Cookies**: Prevents JavaScript access (XSS protection) - **Secure Flag**: Only sent over HTTPS - **Token Expiration**: 7-day automatic expiration - **Token Hashing**: Sanctum stores hashed tokens in database - **Single Use OTP**: OTP tokens deleted after use ### Password Security - **Bcrypt Hashing**: All passwords hashed with bcrypt - **Current Password Verification**: Required for password changes - **Minimum Length**: 8 characters - **Verification**: Password confirmation required ### Rate Limiting - OTP requests: Limited per identifier - Login attempts: Limited per IP - Password reset: Limited per identifier ### User Suspension - Suspended users cannot authenticate - Admin can suspend users via admin panel - Suspended users receive "Account suspended" error ## Frontend Integration ### API Helper Methods All authentication API calls use the helper methods from `resources/views/layouts/app.blade.php`: ```javascript // Login const response = await apiPost('/api/login', { identifier: 'user@example.com', method: 'password', password: 'password123' }); // Get current user const user = await apiGet('/api/user'); // Logout await apiPost('/api/logout'); ``` **Important**: All API methods automatically include the `auth_token` cookie via `credentials: 'include'`. No manual token handling required. ### Checking Authentication ```javascript // Check if user is authenticated async function checkAuth() { try { const user = await apiGet('/api/user'); if (user.success) { return user.user; } return null; } catch (error) { return null; } } ``` ## Testing Authentication ### Test Users The system includes seeded test users for development: - **testuser** (password: password123) - **creator** (password: password123) - **viewer** (password: password123) ### Manual Testing ```bash # Test login via curl curl -X POST http://localhost/api/login \ -H "Content-Type: application/json" \ -d '{"identifier":"testuser","method":"password","password":"password123"}' \ -c cookies.txt # Use cookie for authenticated request curl http://localhost/api/user \ -b cookies.txt ``` ## Troubleshooting ### Common Issues 1. **Token Not Found** - Check cookie is being sent (browser DevTools â Application â Cookies) - Verify token exists in `personal_access_tokens` table - Check token expiration (7 days) 2. **Cookie Not Set** - Verify HTTPS is enabled (required for secure cookies) - Check SameSite policy matches your domain setup - Ensure cookie path includes API routes 3. **OTP Not Received** - Check email/SMS service configuration - Verify Twilio credentials (for SMS) - Check email service configuration (SMTP) - Review application logs for errors 4. **User Suspended** - User will receive "Account suspended" message - Admin must unsuspend via admin panel - Check `users.is_suspended` field ## Related Documentation - **API Reference**: See `docs/03-api-reference.md` for all authentication endpoints - **Frontend Architecture**: See `docs/05-frontend-architecture.md` for API method usage
0
đ Page Notes
+ Add New
Add New Note
Type
âšī¸ Info
đ Bug
⨠Feature Request
đĄ Improvement
â Missing Feature
đ¨ Design Changes
Title (optional)
Note Content
đ Add Note