Files
chunyu_project/user/views/user.md
T
2026-08-05 23:59:15 +08:00

348 lines
8.8 KiB
Markdown

# 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**
```python
@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**
```json
{
"to_email": "user@example.com" // Required: Recipient email address
}
```
##### **Response Format**
**Success - Registration Email:**
```json
{
"message": "账号未注册,已发送注册邮件",
"code": "10001",
"data": {
"email_sent": true,
"type": "register"
}
}
```
**Success - Login Email:**
```json
{
"message": "邮件发送成功",
"code": "10002",
"data": {
"email_sent": true,
"type": "login"
}
}
```
##### **Logic Flow**
1. Validate email parameter
2. Check if user exists in database
3. If user doesn't exist: send registration email
4. If user exists: send login email
5. Store verification code in Redis cache with 10-minute timeout
6. 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**
```json
{
"email": "user@example.com", // Required: User email address
"code": "12345678" // Required: Verification code
}
```
##### **Response Format**
**Successful Registration:**
```json
{
"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:**
```json
{
"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:**
1. Validate email and code parameters
2. Get user from database (expecting None for registration)
3. Retrieve verification code from cache (`register_{email}`)
4. Verify code matches
5. Validate user data via serializer
6. Create user account
7. Generate JWT tokens
8. Return success response
**Login Flow:**
1. Validate email and code parameters
2. Get existing user from database
3. Retrieve verification code from cache (`login_{email}`)
4. Verify code matches
5. Generate JWT tokens for existing user
6. 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:
```python
# Database query becomes async
user = await sync_to_async(FUser.objects.filter)(email=to_email).first()
```
#### **Email System**
- Uses Django's `EmailMessage` class
- Sends from `cs10086086@qq.com`
- Verification codes stored in Redis with 10-minute timeout
- Separate cache keys: `register_{email}` and `login_{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**
```python
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**
```javascript
// 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**
```bash
# 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**
```python
# 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.access` for API authentication
- Store `data.refresh` for 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