8.8 KiB
8.8 KiB
User Views Documentation
📄 File Location
user/views/user.py
Overview
Handles user authentication, email verification, and registration processes. All views have been converted to asynchronous operations with standardized response codes for better performance and maintainability.
Class Details
@permission_classes([AllowAny])
class SendUserEmailAPIView(APIView):
async def post(self, request): # Email sending
@permission_classes([AllowAny])
class UserLoginOrRegisterAPIView(APIView):
async def post(self, request): # Login/Registration
Permissions
- Access Level: Public (no authentication required)
- Authentication: None (
@permission_classes([AllowAny]))
Method Details
1. SendUserEmailAPIView (Email Verification)
Endpoint: POST /api/send-email/
Description
Sends verification emails for user registration or login. Generates and stores 8-digit verification codes in cache for validation.
Parameters
{
"to_email": "user@example.com" // Required: Recipient email address
}
Response Format
Success - Registration Email:
{
"message": "账号未注册,已发送注册邮件",
"code": "10001",
"data": {
"email_sent": true,
"type": "register"
}
}
Success - Login Email:
{
"message": "邮件发送成功",
"code": "10002",
"data": {
"email_sent": true,
"type": "login"
}
}
Logic Flow
- Validate email parameter
- Check if user exists in database
- If user doesn't exist: send registration email
- If user exists: send login email
- Store verification code in Redis cache with 10-minute timeout
- Return appropriate success response
Error Responses
| Code | Status | Description |
|---|---|---|
| 20002 | Bad Request | Email parameter missing or empty |
| 20003 | Internal Server Error | Email sending failed |
2. UserLoginOrRegisterAPIView (Authentication)
Endpoint: POST /api/login-register/
Description
Handles both user registration and login processes using email verification codes. Supports JWT token generation for authenticated sessions.
Parameters
{
"email": "user@example.com", // Required: User email address
"code": "12345678" // Required: Verification code
}
Response Format
Successful Registration:
{
"message": "注册成功",
"code": "10003",
"data": {
"user": {
"id": 1,
"email": "user@example.com",
"username": "example_user"
},
"refresh": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer",
"expires_in": 604800 // 7 days in seconds
}
}
Successful Login:
{
"message": "登录成功",
"code": "10004",
"data": {
"user": {
"id": 1,
"email": "user@example.com",
"username": "example_user"
},
"refresh": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer",
"expires_in": 604800 // 7 days in seconds
}
}
Logic Flow
Registration Flow:
- Validate email and code parameters
- Get user from database (expecting None for registration)
- Retrieve verification code from cache (
register_{email}) - Verify code matches
- Validate user data via serializer
- Create user account
- Generate JWT tokens
- Return success response
Login Flow:
- Validate email and code parameters
- Get existing user from database
- Retrieve verification code from cache (
login_{email}) - Verify code matches
- Generate JWT tokens for existing user
- Return success response
Error Responses
| Code | Status | Description |
|---|---|---|
| 20001 | Bad Request | Parameter validation error |
| 20004 | Bad Request | Registration verification code expired |
| 20005 | Bad Request | User data validation failed |
| 20006 | Bad Request | Registration verification code incorrect |
| 20007 | Bad Request | Login verification code expired |
| 20008 | Bad Request | Login verification code incorrect |
| 20009 | Internal Server Error | Server internal error |
Implementation Details
Async Operations
All database operations use sync_to_async for non-blocking execution:
# Database query becomes async
user = await sync_to_async(FUser.objects.filter)(email=to_email).first()
Email System
- Uses Django's
EmailMessageclass - Sends from
cs10086086@qq.com - Verification codes stored in Redis with 10-minute timeout
- Separate cache keys:
register_{email}andlogin_{email}
Token System
- Uses Django REST Framework Simple JWT
- Access token expires in 7 days
- Refresh token system implemented
- Token payload includes expiration time calculation
Data Validation
- UserSerializer handles data validation
- create_by_email method handles user creation
- Comprehensive error handling for invalid data
Security & Performance
Verification Code Security
- 8-digit numeric codes generated randomly
- 10-minute expiration window
- One-time use (consumed after validation)
- Stored in secure Redis cache
Rate Limiting Considerations
- No built-in rate limiting
- Consider implementing client-side limits
- Redis can be used for distributed rate limiting
Input Validation
- Email format validation
- Code length and format validation
- Parameter presence validation
- Database constraint enforcement
Error Handling
- Comprehensive try-catch blocks
- Meaningful error messages
- Proper HTTP status codes
- No sensitive information leakage
Usage Examples
Python Client
import requests
# Send registration email
response = requests.post('/api/send-email/', json={'to_email': 'test@example.com'})
if response.status_code == 201:
print("Registration email sent")
# Register user
response = requests.post('/api/login-register/', json={
'email': 'test@example.com',
'code': '12345678'
})
if response.status_code == 200:
tokens = response.json()['data']
print(f"Access token: {tokens['access']}")
JavaScript Frontend
// Send email verification
const sendVerificationEmail = async (email) => {
const response = await fetch('/api/send-email/', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({to_email: email})
});
return response.json();
};
// Register user
const registerUser = async (email, code, userData) => {
const response = await fetch('/api/login-register/', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({email, code, ...userData})
});
return response.json();
};
Testing Endpoints
# Send email verification
curl -X POST http://localhost:8000/api/send-email/
-H "Content-Type: application/json"
-d '{"to_email":"test@example.com"}'
# Register user
curl -X POST http://localhost:8000/api/login-register/
-H "Content-Type: application/json"
-d '{"email":"test@example.com","code":"12345678","username":"testuser"}'
# Login user
curl -X POST http://localhost:8000/api/login-register/
-H "Content-Type: application/json"
-d '{"email":"test@example.com","code":"87654321"}'
Integration Notes
Django URL Configuration
# urls.py
from django.urls import path
from user.views.user import SendUserEmailAPIView, UserLoginOrRegisterAPIView
urlpatterns = [
path('send-email/', SendUserEmailAPIView.as_view(), name='send-email'),
path('login-register/', UserLoginOrRegisterAPIView.as_view(), name='login-register'),
]
Frontend Integration
- Use response
data.accessfor API authentication - Store
data.refreshfor token refresh - Handle different message codes for user feedback
- Implement countdown timer for code expiration
Mobile App Integration
- Same API endpoints work for mobile apps
- Include proper error handling for network issues
- Implement offline caching for better UX
Third-party Services
- Email service: QQ Mail SMTP
- Authentication: JWT-based
- Storage: MySQL + Redis cache
Monitoring & Debugging
Logging
- Email sending operations logged
- Parameter validation errors logged
- Consider adding structured logging for production
Metrics
- Email delivery success rates
- Registration completion rates
- Login success rates
- Token refresh patterns
Health Checks
- Redis connectivity
- SMTP server availability
- Database connection pool
Last Updated: Current Session Version: 1.0