campaign_connector/docs/guides/user-management.md
admin 30c2cfeba5 feat(security): Implement comprehensive security fixes and enhancements
- Added Security Handoff Report detailing resolved issues and current configurations.
- Implemented CSRF protection using Flask-WTF, including token management in templates and JavaScript.
- Created standardized error handling module to log detailed errors while returning generic messages.
- Developed phone number validation module to ensure compliance with E.164 standards.
- Added CSV injection prevention measures during file uploads.
- Updated installation guide for clarity and completeness.
- Created script to update API keys from Android device, ensuring secure key management.
- Enhanced Docker security configurations to remove privileged mode and host networking.
- Implemented logging and sanitization for error messages to prevent information disclosure.
- Added verification script to test security setup flow and validate configurations.
2026-01-01 17:18:50 -07:00

566 lines
11 KiB
Markdown

# User Management Guide - SMS Campaign Manager
## 🎉 No More ModHeader Required!
Your application now has a complete user management system with session-based authentication. Users can log in through a web interface and stay logged in without needing browser extensions or API keys in headers.
---
## 🏗️ System Architecture
### Dual Authentication System
Your application now supports **two types of authentication**:
1. **Session-Based Authentication** (Web Dashboard)
- Users log in with username/password
- Sessions last 24 hours
- Automatic login persistence
- No browser extensions needed
2. **API Key Authentication** (Programmatic Access)
- For external scripts and integrations
- Uses `X-API-Key` header
- Three roles: Admin, User, Termux
---
## 🚀 Quick Start
### Step 1: Add Default Admin to .env
Edit your `.env` file and add:
```env
# User Management
ADMIN_USERNAME=admin
ADMIN_PASSWORD=YourSecurePassword123!
```
### Step 2: Restart Application
```bash
cd /mnt/storagessd1tb/campaign_connector
docker-compose restart
```
On first start, the system will automatically create the admin user from your .env file.
### Step 3: Access the Login Page
Open your browser and go to:
```
http://localhost:5000/login
```
Or via Tailscale:
```
http://your-tailscale-ip:5000/login
```
### Step 4: Log In
- Username: `admin` (or what you set in .env)
- Password: Your password from .env
You'll be redirected to the dashboard and stay logged in for 24 hours!
---
## 👥 Managing Users
### Using the CLI Tool
The easiest way to manage users is with the command-line tool:
```bash
cd /mnt/storagessd1tb/campaign_connector
python3 manage_users.py
```
This provides an interactive menu:
```
📱 SMS Campaign Manager - User Management
══════════════════════════════════════════════════════════════════════
Choose an option:
1. Create new user
2. List all users
3. Delete user
4. Change password
5. Exit
Choice [1-5]:
```
### Creating Users via CLI
```bash
python3 manage_users.py
# Select option 1
# Follow prompts to create user
```
Example:
```
Username: john
Password: ********
Confirm password: ********
Select role:
1. Admin (full access)
2. User (regular access)
Choice [1-2]: 2
Email (optional): john@example.com
Full name (optional): John Doe
✅ User 'john' created successfully (role: user)
```
### Creating Users via API (Admin Only)
```bash
curl -X POST http://localhost:5000/api/admin/users/create \
-H "Cookie: session=YOUR_SESSION_COOKIE" \
-H "Content-Type: application/json" \
-d '{
"username": "jane",
"password": "SecurePassword123!",
"role": "user",
"email": "jane@example.com",
"full_name": "Jane Smith"
}'
```
### Listing Users
```bash
# Via CLI
python3 manage_users.py
# Select option 2
# Via API (admin only)
curl http://localhost:5000/api/admin/users \
-H "Cookie: session=YOUR_SESSION_COOKIE"
```
### Deleting Users
```bash
# Via CLI
python3 manage_users.py
# Select option 3
# Via API (admin only)
curl -X DELETE http://localhost:5000/api/admin/users/username \
-H "Cookie: session=YOUR_SESSION_COOKIE"
```
### Changing Passwords
```bash
# Via CLI
python3 manage_users.py
# Select option 4
# Via Web Dashboard
# User can change their own password through settings
curl -X POST http://localhost:5000/api/auth/change-password \
-H "Cookie: session=YOUR_SESSION_COOKIE" \
-H "Content-Type: application/json" \
-d '{
"old_password": "OldPass123!",
"new_password": "NewSecurePass456!"
}'
```
---
## 🔐 User Roles
### Admin Role
**Full system access**
Permissions:
- ✅ Everything User can do
- ✅ Create/delete other users
- ✅ View all users
- ✅ Database reset
- ✅ System configuration
Use cases:
- System administrators
- Primary account owners
### User Role
**Regular application access**
Permissions:
- ✅ Create and manage campaigns
- ✅ Send SMS messages
- ✅ Upload CSV files
- ✅ View analytics
- ✅ Manage conversations
- ✅ Change own password
- ❌ Cannot create/delete users
- ❌ Cannot reset database
Use cases:
- Team members
- Campaign managers
- Regular users
---
## 🌐 How Login Works
### Login Flow
1. **User visits `/` (dashboard)**
- Not logged in → Redirected to `/login`
- Logged in → Shows dashboard
2. **User enters credentials**
- System checks username/password
- Creates secure session token
- Stores session in database
- Sets HTTP-only session cookie
3. **User accesses protected pages**
- Session cookie sent automatically
- Server validates session token
- User data available in `request.current_user`
4. **Session expires after 24 hours**
- User must log in again
- Old sessions automatically cleaned up
### Security Features
**PBKDF2 password hashing** - 100,000 iterations
**HTTP-only cookies** - Prevents XSS attacks
**Session tokens** - Cryptographically secure
**Constant-time comparison** - Prevents timing attacks
**Session tracking** - IP and user agent logging
**Failed login protection** - Logged for monitoring
---
## 🔧 Configuration
### Session Settings
Configured in `src/app.py`:
```python
'SESSION_COOKIE_SECURE': False, # Set to True for HTTPS
'SESSION_COOKIE_HTTPONLY': True, # Prevent JavaScript access
'SESSION_COOKIE_SAMESITE': 'Lax', # CSRF protection
'PERMANENT_SESSION_LIFETIME': 86400 # 24 hours
```
For production with HTTPS:
- Set `SESSION_COOKIE_SECURE` to `True`
### Database Tables
User system creates two tables:
**users table**:
```sql
- id (primary key)
- username (unique)
- password_hash (PBKDF2)
- role (admin/user)
- created_at
- last_login
- is_active
- email
- full_name
```
**user_sessions table**:
```sql
- id (primary key)
- user_id (foreign key)
- session_token
- ip_address
- user_agent
- created_at
- expires_at
- is_active
```
---
## 🎨 Customizing the Login Page
The login page is at `src/templates/login.html`. You can customize:
- Logo/branding
- Colors (uses Tailwind CSS)
- Additional fields
- Links to help/support
Example customization:
```html
<!-- Add company logo -->
<div class="text-center mb-8">
<img src="/static/logo.png" alt="Company Logo" class="mx-auto mb-4">
<h1 class="text-3xl font-bold text-gray-800">Your Company Name</h1>
</div>
```
---
## 📊 Monitoring and Auditing
### Check Active Sessions
```python
# In your application code
from core.user_auth import UserManager
user_manager = UserManager(config.DATABASE)
sessions = user_manager.list_active_sessions() # Add this method if needed
```
### View Login History
Check the `user_sessions` table:
```bash
docker-compose exec sms-campaign sqlite3 /app/data/campaign.db
```
```sql
SELECT u.username, s.created_at, s.ip_address, s.user_agent
FROM user_sessions s
JOIN users u ON s.user_id = u.id
ORDER BY s.created_at DESC
LIMIT 20;
```
### Monitor Failed Logins
Check application logs:
```bash
docker-compose logs -f sms-campaign | grep "Failed login"
```
---
## 🔄 Migration from API Keys
If you were using ModHeader with API keys:
### Before (with ModHeader):
```
1. Install ModHeader
2. Add X-API-Key header
3. Set value to API key
4. Access dashboard
```
### After (with User Login):
```
1. Go to /login
2. Enter username/password
3. Click Sign In
4. Access dashboard (stays logged in)
```
**API keys still work for:**
- External scripts
- Automation
- Mobile apps
- Third-party integrations
---
## 🛡️ Security Best Practices
### Password Requirements
Enforced by the system:
- Minimum 8 characters
- Recommended: Mix of letters, numbers, symbols
### Recommendations
1. **Use strong passwords**
- 12+ characters
- Mix uppercase, lowercase, numbers, symbols
- Use password manager
2. **Rotate admin credentials**
- Change admin password every 90 days
- Update .env file after changing
3. **Monitor access**
- Review login logs regularly
- Check for suspicious IPs
- Disable inactive users
4. **Limit admin accounts**
- Only create admin users when necessary
- Most users should have 'user' role
5. **Use HTTPS in production**
- Tailscale provides this automatically
- Or set up reverse proxy with SSL
---
## 🐛 Troubleshooting
### Can't Log In
**Issue**: Invalid username or password
**Solutions**:
1. Verify username is correct (case-sensitive)
2. Reset password via CLI:
```bash
python3 manage_users.py
# Choose option 4 (Change password)
```
3. Check if user exists:
```bash
python3 manage_users.py
# Choose option 2 (List users)
```
### Session Expires Too Quickly
**Issue**: Getting logged out frequently
**Solution**: Increase session lifetime in `src/app.py`:
```python
'PERMANENT_SESSION_LIFETIME': 604800 # 7 days instead of 24 hours
```
### Database Locked Error
**Issue**: "database is locked" when creating users
**Solution**:
```bash
# Stop application
docker-compose down
# Start again
docker-compose up -d
# Try creating user again
python3 manage_users.py
```
### Forgot Admin Password
**Solution 1**: Reset via .env
```bash
# Edit .env
ADMIN_PASSWORD=NewSecurePassword789!
# Restart application
docker-compose restart
# System will update the password
```
**Solution 2**: Create new admin via Docker
```bash
docker-compose exec sms-campaign python3 manage_users.py
```
### Login Page Not Showing
**Issue**: Redirects not working
**Solutions**:
1. Clear browser cache
2. Check if logged in: `http://localhost:5000/api/auth/status`
3. Logout manually: `http://localhost:5000/api/auth/logout`
---
## 📱 Mobile/Remote Access
### Access via Tailscale
Your application is accessible via Tailscale VPN:
```
https://your-tailscale-hostname:5000/login
```
### Remember Me Feature
The "Remember me" checkbox (currently cosmetic) can be enhanced to extend session duration for trusted devices.
---
## 🔌 API Endpoints
### Public Endpoints (No Auth Required)
- `GET /login` - Login page
- `POST /api/auth/login` - Login handler
- `GET /health` - Health check
### User Endpoints (Login Required)
- `GET /` - Dashboard
- `GET /api/auth/status` - Check login status
- `POST /api/auth/logout` - Logout
- `POST /api/auth/change-password` - Change password
### Admin Endpoints (Admin Role Required)
- `GET /api/admin/users` - List users
- `POST /api/admin/users/create` - Create user
- `DELETE /api/admin/users/<username>` - Delete user
---
## 🎯 Next Steps
### Recommended Setup
1. **Create initial admin**:
```bash
# Add to .env
ADMIN_USERNAME=your_username
ADMIN_PASSWORD=SecurePassword123!
# Restart
docker-compose restart
```
2. **Log in and test**:
- Visit http://localhost:5000/login
- Log in with credentials
- Access dashboard
3. **Create additional users**:
```bash
python3 manage_users.py
```
4. **Remove .env credentials** (optional for security):
- After creating admin via database
- Remove ADMIN_USERNAME and ADMIN_PASSWORD from .env
- Users only in database (more secure)
5. **Set up monitoring**:
- Monitor logs for failed logins
- Review user list periodically
- Disable inactive users
## Related Documentation
- [Authentication Setup](../setup/authentication.md) - Login configuration
- [API Security](../security/api-security.md) - API key authentication
- [Security Setup](../security/security-setup.md) - Security configuration
- [Quick Start](../setup/quick-start.md) - Getting started