Spaces:
Runtime error
Runtime error
Commit ·
c34f45e
1
Parent(s): 25039bc
email invite implemented
Browse files- INVITATION_FLOW_IMPLEMENTATION.md +0 -208
- test_invitation_flow.py +0 -152
- user_invitation_flow_backend.md +0 -425
INVITATION_FLOW_IMPLEMENTATION.md
DELETED
|
@@ -1,208 +0,0 @@
|
|
| 1 |
-
# User Invitation Flow Implementation
|
| 2 |
-
|
| 3 |
-
## Overview
|
| 4 |
-
|
| 5 |
-
The user invitation flow has been successfully implemented as a replacement for the direct user creation functionality. This system ensures that user accounts are only created after the invitee accepts the invitation via email.
|
| 6 |
-
|
| 7 |
-
## Features Implemented
|
| 8 |
-
|
| 9 |
-
### 1. Email-Based Invitation System
|
| 10 |
-
- ✅ Admins can send invitations via email
|
| 11 |
-
- ✅ Invitations include unique tokens with 48-hour expiry
|
| 12 |
-
- ✅ Beautiful HTML email templates with invitation links
|
| 13 |
-
- ✅ Console email backend for development (can be switched to SMTP for production)
|
| 14 |
-
|
| 15 |
-
### 2. Security Features
|
| 16 |
-
- ✅ UUID-based invitation tokens (secure and unique)
|
| 17 |
-
- ✅ Tokens expire after 48 hours
|
| 18 |
-
- ✅ One-time use tokens (marked as accepted after use)
|
| 19 |
-
- ✅ Prevents duplicate invitations to existing users
|
| 20 |
-
- ✅ Admin-only invitation sending
|
| 21 |
-
|
| 22 |
-
### 3. Database Models
|
| 23 |
-
- ✅ `Invitation` model with proper relationships
|
| 24 |
-
- ✅ Admin panel integration for invitation management
|
| 25 |
-
- ✅ Automatic cleanup of accepted invitations
|
| 26 |
-
|
| 27 |
-
## API Endpoints
|
| 28 |
-
|
| 29 |
-
### 1. Send Invitation
|
| 30 |
-
**Endpoint**: `POST /admin_app/invite/`
|
| 31 |
-
**Permission**: Admin only
|
| 32 |
-
**Request Body**:
|
| 33 |
-
```json
|
| 34 |
-
{
|
| 35 |
-
"email": "researcher@example.com",
|
| 36 |
-
"role": "RESEARCHER"
|
| 37 |
-
}
|
| 38 |
-
```
|
| 39 |
-
**Response**: `{"message": "Invitation sent."}`
|
| 40 |
-
|
| 41 |
-
### 2. Verify Invitation
|
| 42 |
-
**Endpoint**: `GET /admin_app/verify-invite/{token}/`
|
| 43 |
-
**Permission**: Public
|
| 44 |
-
**Response**:
|
| 45 |
-
```json
|
| 46 |
-
{
|
| 47 |
-
"valid": true,
|
| 48 |
-
"email": "researcher@example.com",
|
| 49 |
-
"expires_at": "2025-09-16T15:16:07.370590Z"
|
| 50 |
-
}
|
| 51 |
-
```
|
| 52 |
-
|
| 53 |
-
### 3. Accept Invitation
|
| 54 |
-
**Endpoint**: `POST /admin_app/accept-invite/{token}/`
|
| 55 |
-
**Permission**: Public
|
| 56 |
-
**Request Body**:
|
| 57 |
-
```json
|
| 58 |
-
{
|
| 59 |
-
"username": "researcher123",
|
| 60 |
-
"password": "securepass",
|
| 61 |
-
"first_name": "John",
|
| 62 |
-
"last_name": "Doe"
|
| 63 |
-
}
|
| 64 |
-
```
|
| 65 |
-
**Response**: `{"message": "User created successfully."}`
|
| 66 |
-
|
| 67 |
-
## Workflow
|
| 68 |
-
|
| 69 |
-
1. **Admin sends invitation**:
|
| 70 |
-
- Admin calls `POST /admin_app/invite/` with email and role
|
| 71 |
-
- System creates `Invitation` record with unique token
|
| 72 |
-
- Email sent with invitation link pointing to frontend
|
| 73 |
-
|
| 74 |
-
2. **User receives email**:
|
| 75 |
-
- Email contains both HTML and text versions
|
| 76 |
-
- Link format: `http://frontend-url/accept-invite/{token}`
|
| 77 |
-
- 48-hour expiry clearly communicated
|
| 78 |
-
|
| 79 |
-
3. **Frontend verification** (optional):
|
| 80 |
-
- Frontend can call `GET /admin_app/verify-invite/{token}/` to validate token
|
| 81 |
-
- Display appropriate UI based on token validity
|
| 82 |
-
|
| 83 |
-
4. **User accepts invitation**:
|
| 84 |
-
- Frontend calls `POST /admin_app/accept-invite/{token}/` with user details
|
| 85 |
-
- User account created with email from invitation
|
| 86 |
-
- Role assigned from invitation
|
| 87 |
-
- Token marked as accepted (one-time use)
|
| 88 |
-
|
| 89 |
-
5. **User can login**:
|
| 90 |
-
- New user can immediately login with created credentials
|
| 91 |
-
- Full access to researcher functionality
|
| 92 |
-
|
| 93 |
-
## Email Configuration
|
| 94 |
-
|
| 95 |
-
### Development (Current)
|
| 96 |
-
```python
|
| 97 |
-
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
|
| 98 |
-
```
|
| 99 |
-
Emails are printed to console for testing.
|
| 100 |
-
|
| 101 |
-
### Production (Example)
|
| 102 |
-
```python
|
| 103 |
-
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
|
| 104 |
-
EMAIL_HOST = "smtp.gmail.com"
|
| 105 |
-
EMAIL_PORT = 587
|
| 106 |
-
EMAIL_USE_TLS = True
|
| 107 |
-
EMAIL_HOST_USER = "your_email@gmail.com"
|
| 108 |
-
EMAIL_HOST_PASSWORD = "<your-app-password>"
|
| 109 |
-
DEFAULT_FROM_EMAIL = "noreply@neurostack.com"
|
| 110 |
-
```
|
| 111 |
-
|
| 112 |
-
## Database Schema
|
| 113 |
-
|
| 114 |
-
### Invitation Model
|
| 115 |
-
```python
|
| 116 |
-
class Invitation(models.Model):
|
| 117 |
-
email = models.EmailField(unique=True)
|
| 118 |
-
role = models.CharField(max_length=50, default="RESEARCHER")
|
| 119 |
-
token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
|
| 120 |
-
invited_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
|
| 121 |
-
is_accepted = models.BooleanField(default=False)
|
| 122 |
-
created_at = models.DateTimeField(auto_now_add=True)
|
| 123 |
-
expires_at = models.DateTimeField(default=default_expiry) # 48 hours
|
| 124 |
-
```
|
| 125 |
-
|
| 126 |
-
## Testing Results
|
| 127 |
-
|
| 128 |
-
### Manual Testing Completed ✅
|
| 129 |
-
1. ✅ Admin login successful
|
| 130 |
-
2. ✅ Invitation sent successfully
|
| 131 |
-
3. ✅ Email generated with proper HTML formatting
|
| 132 |
-
4. ✅ Token verification works
|
| 133 |
-
5. ✅ User account creation successful
|
| 134 |
-
6. ✅ New user login successful
|
| 135 |
-
7. ✅ Token becomes invalid after acceptance (security)
|
| 136 |
-
|
| 137 |
-
### Sample Test Commands
|
| 138 |
-
```bash
|
| 139 |
-
# 1. Admin Login
|
| 140 |
-
POST /auth/login/ {"username": "admin", "password": "admin123"}
|
| 141 |
-
|
| 142 |
-
# 2. Send Invitation
|
| 143 |
-
POST /admin_app/invite/ {"email": "test@example.com", "role": "RESEARCHER"}
|
| 144 |
-
|
| 145 |
-
# 3. Verify Token
|
| 146 |
-
GET /admin_app/verify-invite/{token}/
|
| 147 |
-
|
| 148 |
-
# 4. Accept Invitation
|
| 149 |
-
POST /admin_app/accept-invite/{token}/ {
|
| 150 |
-
"username": "testresearcher",
|
| 151 |
-
"password": "testpass123",
|
| 152 |
-
"first_name": "Test",
|
| 153 |
-
"last_name": "Researcher"
|
| 154 |
-
}
|
| 155 |
-
|
| 156 |
-
# 5. New User Login
|
| 157 |
-
POST /auth/login/ {"username": "testresearcher", "password": "testpass123"}
|
| 158 |
-
```
|
| 159 |
-
|
| 160 |
-
## Migration Applied ✅
|
| 161 |
-
- Database migrations created and applied successfully
|
| 162 |
-
- `Invitation` model available in Django admin
|
| 163 |
-
- Foreign key relationships established
|
| 164 |
-
|
| 165 |
-
## Files Modified
|
| 166 |
-
|
| 167 |
-
### Models
|
| 168 |
-
- `admin_app/models.py` - Added Invitation model
|
| 169 |
-
|
| 170 |
-
### Serializers
|
| 171 |
-
- `admin_app/serializers.py` - Added InvitationSerializer, AcceptInvitationSerializer
|
| 172 |
-
|
| 173 |
-
### Views
|
| 174 |
-
- `admin_app/views.py` - Added invite_user, accept_invite, verify_invite views
|
| 175 |
-
|
| 176 |
-
### URLs
|
| 177 |
-
- `admin_app/urls.py` - Added invitation endpoints
|
| 178 |
-
|
| 179 |
-
### Settings
|
| 180 |
-
- `pms_server/settings.py` - Added email configuration and template path
|
| 181 |
-
|
| 182 |
-
### Templates
|
| 183 |
-
- `admin_app/templates/emails/invite.html` - Beautiful HTML email template
|
| 184 |
-
|
| 185 |
-
### Admin
|
| 186 |
-
- `admin_app/admin.py` - Added InvitationAdmin for management
|
| 187 |
-
|
| 188 |
-
## Security Considerations
|
| 189 |
-
|
| 190 |
-
1. **Token Security**: UUIDs provide sufficient entropy for invitation tokens
|
| 191 |
-
2. **Expiry**: 48-hour limit prevents indefinite token validity
|
| 192 |
-
3. **One-time Use**: Tokens cannot be reused after acceptance
|
| 193 |
-
4. **Email Validation**: Prevents duplicate invitations to existing users
|
| 194 |
-
5. **Admin Authorization**: Only admins can send invitations
|
| 195 |
-
6. **CSRF Protection**: Properly configured for API endpoints
|
| 196 |
-
|
| 197 |
-
## Future Enhancements
|
| 198 |
-
|
| 199 |
-
1. **Async Email**: Integrate Celery for non-blocking email sending
|
| 200 |
-
2. **Resend Invitations**: Allow admins to resend expired invitations
|
| 201 |
-
3. **Bulk Invitations**: Support CSV upload for multiple invitations
|
| 202 |
-
4. **Custom Roles**: Support for custom role definitions
|
| 203 |
-
5. **Invitation Analytics**: Track invitation acceptance rates
|
| 204 |
-
6. **Email Templates**: Multiple template options for different invitation types
|
| 205 |
-
|
| 206 |
-
## Conclusion
|
| 207 |
-
|
| 208 |
-
The user invitation flow has been successfully implemented and tested. The system replaces direct user creation with a secure, email-based invitation process that ensures users are properly onboarded through email verification. All security requirements have been met, and the system is ready for production use with proper SMTP configuration.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 2 |
-
"""
|
| 3 |
-
Test script for the invitation flow
|
| 4 |
-
"""
|
| 5 |
-
import requests
|
| 6 |
-
import json
|
| 7 |
-
import sys
|
| 8 |
-
|
| 9 |
-
BASE_URL = "http://127.0.0.1:8000"
|
| 10 |
-
|
| 11 |
-
def test_invitation_flow():
|
| 12 |
-
print("🧪 Testing User Invitation Flow")
|
| 13 |
-
print("=" * 50)
|
| 14 |
-
|
| 15 |
-
# Step 1: Create an admin user first (you may need to create one manually via Django admin)
|
| 16 |
-
print("📝 Note: Make sure you have an admin user created via Django admin or command line")
|
| 17 |
-
print(" You can create one with: python manage.py createsuperuser")
|
| 18 |
-
|
| 19 |
-
# Get admin credentials
|
| 20 |
-
admin_username = input("Enter admin username: ").strip() or "admin"
|
| 21 |
-
admin_password = input("Enter admin password: ").strip() or "admin123"
|
| 22 |
-
|
| 23 |
-
# Step 2: Login as admin to get JWT token
|
| 24 |
-
print("\n🔐 Step 1: Admin Login")
|
| 25 |
-
login_data = {
|
| 26 |
-
"username": admin_username,
|
| 27 |
-
"password": admin_password
|
| 28 |
-
}
|
| 29 |
-
|
| 30 |
-
try:
|
| 31 |
-
login_response = requests.post(f"{BASE_URL}/auth/login/", json=login_data)
|
| 32 |
-
if login_response.status_code == 200:
|
| 33 |
-
token_data = login_response.json()
|
| 34 |
-
access_token = token_data.get("access")
|
| 35 |
-
print(f"✅ Admin login successful")
|
| 36 |
-
print(f" Access token: {access_token[:20]}...")
|
| 37 |
-
else:
|
| 38 |
-
print(f"❌ Admin login failed: {login_response.status_code}")
|
| 39 |
-
print(f" Response: {login_response.text}")
|
| 40 |
-
return False
|
| 41 |
-
except Exception as e:
|
| 42 |
-
print(f"❌ Login error: {e}")
|
| 43 |
-
return False
|
| 44 |
-
|
| 45 |
-
# Step 3: Send invitation
|
| 46 |
-
print("\n📨 Step 2: Send User Invitation")
|
| 47 |
-
invite_email = input("Enter email to invite (or press enter for test@example.com): ").strip() or "test@example.com"
|
| 48 |
-
|
| 49 |
-
headers = {"Authorization": f"Bearer {access_token}"}
|
| 50 |
-
invite_data = {
|
| 51 |
-
"email": invite_email,
|
| 52 |
-
"role": "RESEARCHER"
|
| 53 |
-
}
|
| 54 |
-
|
| 55 |
-
try:
|
| 56 |
-
invite_response = requests.post(f"{BASE_URL}/admin/invite/", json=invite_data, headers=headers)
|
| 57 |
-
if invite_response.status_code == 201:
|
| 58 |
-
print(f"✅ Invitation sent successfully to {invite_email}")
|
| 59 |
-
print(f" Response: {invite_response.json()}")
|
| 60 |
-
else:
|
| 61 |
-
print(f"❌ Invitation failed: {invite_response.status_code}")
|
| 62 |
-
print(f" Response: {invite_response.text}")
|
| 63 |
-
return False
|
| 64 |
-
except Exception as e:
|
| 65 |
-
print(f"❌ Invitation error: {e}")
|
| 66 |
-
return False
|
| 67 |
-
|
| 68 |
-
# Step 4: Check invitation in database (simulate getting token)
|
| 69 |
-
print("\n🔍 Step 3: Get Invitation Token")
|
| 70 |
-
print(" In a real scenario, the user would get this token from the email link")
|
| 71 |
-
print(" For testing, you can check the database or console output for the token")
|
| 72 |
-
|
| 73 |
-
# Get token from user input for testing
|
| 74 |
-
token = input("Enter invitation token from email/console (UUID format): ").strip()
|
| 75 |
-
|
| 76 |
-
if not token:
|
| 77 |
-
print("❌ Token required for testing accept invitation flow")
|
| 78 |
-
return False
|
| 79 |
-
|
| 80 |
-
# Step 5: Verify invitation
|
| 81 |
-
print(f"\n🔍 Step 4: Verify Invitation Token")
|
| 82 |
-
try:
|
| 83 |
-
verify_response = requests.get(f"{BASE_URL}/admin/verify-invite/{token}/")
|
| 84 |
-
if verify_response.status_code == 200:
|
| 85 |
-
verify_data = verify_response.json()
|
| 86 |
-
print(f"✅ Invitation token is valid")
|
| 87 |
-
print(f" Email: {verify_data.get('email')}")
|
| 88 |
-
print(f" Expires at: {verify_data.get('expires_at')}")
|
| 89 |
-
else:
|
| 90 |
-
print(f"❌ Token verification failed: {verify_response.status_code}")
|
| 91 |
-
print(f" Response: {verify_response.text}")
|
| 92 |
-
return False
|
| 93 |
-
except Exception as e:
|
| 94 |
-
print(f"❌ Verification error: {e}")
|
| 95 |
-
return False
|
| 96 |
-
|
| 97 |
-
# Step 6: Accept invitation (create user account)
|
| 98 |
-
print(f"\n✅ Step 5: Accept Invitation (Create User Account)")
|
| 99 |
-
username = input("Enter username for new user: ").strip() or "testuser"
|
| 100 |
-
password = input("Enter password for new user: ").strip() or "testpass123"
|
| 101 |
-
first_name = input("Enter first name (optional): ").strip() or "Test"
|
| 102 |
-
last_name = input("Enter last name (optional): ").strip() or "User"
|
| 103 |
-
|
| 104 |
-
accept_data = {
|
| 105 |
-
"username": username,
|
| 106 |
-
"password": password,
|
| 107 |
-
"first_name": first_name,
|
| 108 |
-
"last_name": last_name
|
| 109 |
-
}
|
| 110 |
-
|
| 111 |
-
try:
|
| 112 |
-
accept_response = requests.post(f"{BASE_URL}/admin/accept-invite/{token}/", json=accept_data)
|
| 113 |
-
if accept_response.status_code == 201:
|
| 114 |
-
print(f"✅ User account created successfully!")
|
| 115 |
-
print(f" Response: {accept_response.json()}")
|
| 116 |
-
else:
|
| 117 |
-
print(f"❌ Account creation failed: {accept_response.status_code}")
|
| 118 |
-
print(f" Response: {accept_response.text}")
|
| 119 |
-
return False
|
| 120 |
-
except Exception as e:
|
| 121 |
-
print(f"❌ Account creation error: {e}")
|
| 122 |
-
return False
|
| 123 |
-
|
| 124 |
-
# Step 7: Test new user login
|
| 125 |
-
print(f"\n🔐 Step 6: Test New User Login")
|
| 126 |
-
new_user_login = {
|
| 127 |
-
"username": username,
|
| 128 |
-
"password": password
|
| 129 |
-
}
|
| 130 |
-
|
| 131 |
-
try:
|
| 132 |
-
new_login_response = requests.post(f"{BASE_URL}/auth/login/", json=new_user_login)
|
| 133 |
-
if new_login_response.status_code == 200:
|
| 134 |
-
new_token_data = new_login_response.json()
|
| 135 |
-
print(f"✅ New user login successful!")
|
| 136 |
-
print(f" User: {username}")
|
| 137 |
-
print(f" Access token: {new_token_data.get('access')[:20]}...")
|
| 138 |
-
else:
|
| 139 |
-
print(f"❌ New user login failed: {new_login_response.status_code}")
|
| 140 |
-
print(f" Response: {new_login_response.text}")
|
| 141 |
-
return False
|
| 142 |
-
except Exception as e:
|
| 143 |
-
print(f"❌ New user login error: {e}")
|
| 144 |
-
return False
|
| 145 |
-
|
| 146 |
-
print(f"\n🎉 SUCCESS: Complete invitation flow tested successfully!")
|
| 147 |
-
print("=" * 50)
|
| 148 |
-
return True
|
| 149 |
-
|
| 150 |
-
if __name__ == "__main__":
|
| 151 |
-
success = test_invitation_flow()
|
| 152 |
-
sys.exit(0 if success else 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
user_invitation_flow_backend.md
DELETED
|
@@ -1,425 +0,0 @@
|
|
| 1 |
-
# User Invitation Flow (Django + DRF)
|
| 2 |
-
|
| 3 |
-
A step-by-step guide to implement a **user invitation flow** where an admin sends an invite by email and the user account is _created only after the invitee accepts the invitation_. This document covers configuring email, the `Invitation` model, serializers, views, URL routes, optional Celery integration for async emails, and tests.
|
| 4 |
-
|
| 5 |
-
---
|
| 6 |
-
|
| 7 |
-
## Table of Contents
|
| 8 |
-
|
| 9 |
-
1. Prerequisites
|
| 10 |
-
2. Configure email (settings.py)
|
| 11 |
-
3. `Invitation` model (models.py)
|
| 12 |
-
4. Admin registration
|
| 13 |
-
5. Serializers (serializers.py)
|
| 14 |
-
6. Views (views.py)
|
| 15 |
-
- `invite_user`
|
| 16 |
-
- `accept_invite`
|
| 17 |
-
- optional: `verify_invite`
|
| 18 |
-
7. URL routes (urls.py)
|
| 19 |
-
8. Email sending helpers & templates
|
| 20 |
-
9. Expiry cleanup (management command)
|
| 21 |
-
10. Optional: Send email asynchronously (Celery)
|
| 22 |
-
11. Tests
|
| 23 |
-
12. Security & UX considerations
|
| 24 |
-
13. Next steps / optional improvements
|
| 25 |
-
|
| 26 |
-
---
|
| 27 |
-
|
| 28 |
-
## 1) Prerequisites
|
| 29 |
-
|
| 30 |
-
- Django >= 3.2 or 4.x
|
| 31 |
-
- Django REST Framework
|
| 32 |
-
- A working email backend for production (SMTP, SendGrid, SES, etc.). For local dev you can use Django's console backend.
|
| 33 |
-
- If you want async sending: Celery + Redis/RabbitMQ (optional)
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
## 2) Configure email (settings.py)
|
| 37 |
-
|
| 38 |
-
**For production (SMTP example — Gmail / App Password):**
|
| 39 |
-
|
| 40 |
-
```python
|
| 41 |
-
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
|
| 42 |
-
EMAIL_HOST = "smtp.gmail.com"
|
| 43 |
-
EMAIL_PORT = 587
|
| 44 |
-
EMAIL_USE_TLS = True
|
| 45 |
-
EMAIL_HOST_USER = "your_email@gmail.com"
|
| 46 |
-
EMAIL_HOST_PASSWORD = "<your-app-password>"
|
| 47 |
-
DEFAULT_FROM_EMAIL = "noreply@neurostack.com"
|
| 48 |
-
FRONTEND_URL = "http://localhost:5173"
|
| 49 |
-
```
|
| 50 |
-
|
| 51 |
-
> **NOTE:** store secrets in environment variables and never commit them to source control.
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
## 3) `Invitation` model (models.py)
|
| 55 |
-
|
| 56 |
-
Create a model that tracks pending invitations, token, expiry and whether it's accepted.
|
| 57 |
-
|
| 58 |
-
```python
|
| 59 |
-
# admin_app/models.py
|
| 60 |
-
import uuid
|
| 61 |
-
from datetime import timedelta
|
| 62 |
-
from django.db import models
|
| 63 |
-
from django.utils import timezone
|
| 64 |
-
from django.conf import settings
|
| 65 |
-
|
| 66 |
-
User = settings.AUTH_USER_MODEL
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
def default_expiry():
|
| 70 |
-
return timezone.now() + timedelta(hours=48) # 48-hour expiry
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
class Invitation(models.Model):
|
| 74 |
-
email = models.EmailField(unique=True)
|
| 75 |
-
role = models.CharField(max_length=50, default="RESEARCHER")
|
| 76 |
-
token = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
|
| 77 |
-
invited_by = models.ForeignKey(
|
| 78 |
-
settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name="sent_invitations"
|
| 79 |
-
)
|
| 80 |
-
is_accepted = models.BooleanField(default=False)
|
| 81 |
-
created_at = models.DateTimeField(auto_now_add=True)
|
| 82 |
-
expires_at = models.DateTimeField(default=default_expiry)
|
| 83 |
-
|
| 84 |
-
class Meta:
|
| 85 |
-
ordering = ["-created_at"]
|
| 86 |
-
|
| 87 |
-
def __str__(self):
|
| 88 |
-
return f"Invitation({self.email})"
|
| 89 |
-
|
| 90 |
-
def is_expired(self):
|
| 91 |
-
return timezone.now() > self.expires_at
|
| 92 |
-
|
| 93 |
-
def time_remaining(self):
|
| 94 |
-
return max(self.expires_at - timezone.now(), timedelta(seconds=0))
|
| 95 |
-
```
|
| 96 |
-
|
| 97 |
-
Run migrations:
|
| 98 |
-
|
| 99 |
-
```bash
|
| 100 |
-
python manage.py makemigrations
|
| 101 |
-
python manage.py migrate
|
| 102 |
-
```
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
## 4) Admin registration
|
| 106 |
-
|
| 107 |
-
```python
|
| 108 |
-
# admin_app/admin.py
|
| 109 |
-
from django.contrib import admin
|
| 110 |
-
from .models import Invitation
|
| 111 |
-
|
| 112 |
-
@admin.register(Invitation)
|
| 113 |
-
class InvitationAdmin(admin.ModelAdmin):
|
| 114 |
-
list_display = ("email", "role", "invited_by", "is_accepted", "created_at", "expires_at")
|
| 115 |
-
readonly_fields = ("token", )
|
| 116 |
-
search_fields = ("email",)
|
| 117 |
-
```
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
## 5) Serializers (serializers.py)
|
| 121 |
-
|
| 122 |
-
Create a small serializer for creating invites and another for accepting invite (user creation).
|
| 123 |
-
|
| 124 |
-
```python
|
| 125 |
-
# admin_app/serializers.py
|
| 126 |
-
from rest_framework import serializers
|
| 127 |
-
from django.contrib.auth import get_user_model
|
| 128 |
-
from .models import Invitation
|
| 129 |
-
|
| 130 |
-
User = get_user_model()
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
class InvitationSerializer(serializers.ModelSerializer):
|
| 134 |
-
class Meta:
|
| 135 |
-
model = Invitation
|
| 136 |
-
fields = ("email", "role")
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
class AcceptInvitationSerializer(serializers.Serializer):
|
| 140 |
-
username = serializers.CharField(max_length=150)
|
| 141 |
-
password = serializers.CharField(write_only=True)
|
| 142 |
-
first_name = serializers.CharField(max_length=30, required=False, allow_blank=True)
|
| 143 |
-
last_name = serializers.CharField(max_length=150, required=False, allow_blank=True)
|
| 144 |
-
|
| 145 |
-
def validate_username(self, value):
|
| 146 |
-
if User.objects.filter(username=value).exists():
|
| 147 |
-
raise serializers.ValidationError("Username is already taken")
|
| 148 |
-
return value
|
| 149 |
-
```
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
## 6) Views (views.py)
|
| 153 |
-
|
| 154 |
-
This section provides three views:
|
| 155 |
-
|
| 156 |
-
- `invite_user` — admin endpoint to create `Invitation` and send email
|
| 157 |
-
- `accept_invite` — user endpoint to accept invite and create their account
|
| 158 |
-
- `verify_invite` (optional) — to quick-check token validity from frontend
|
| 159 |
-
|
| 160 |
-
```python
|
| 161 |
-
# admin_app/views.py
|
| 162 |
-
from rest_framework.decorators import api_view, permission_classes
|
| 163 |
-
from rest_framework.permissions import IsAuthenticated, IsAdminUser, AllowAny
|
| 164 |
-
from rest_framework.response import Response
|
| 165 |
-
from rest_framework import status
|
| 166 |
-
from django.conf import settings
|
| 167 |
-
from django.shortcuts import get_object_or_404
|
| 168 |
-
from django.core.mail import EmailMultiAlternatives, send_mail
|
| 169 |
-
from django.template.loader import render_to_string
|
| 170 |
-
from django.urls import reverse
|
| 171 |
-
from django.utils import timezone
|
| 172 |
-
|
| 173 |
-
from .models import Invitation
|
| 174 |
-
from .serializers import InvitationSerializer, AcceptInvitationSerializer
|
| 175 |
-
from django.contrib.auth import get_user_model
|
| 176 |
-
|
| 177 |
-
User = get_user_model()
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
def _build_invite_link(token: str) -> str:
|
| 181 |
-
# Use FRONTEND_URL so the user clicks a frontend route which then POSTs to API
|
| 182 |
-
return f"{settings.FRONTEND_URL}/accept-invite/{token}"
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
def _send_invite_email(email: str, invite_link: str, inviter: str = None):
|
| 186 |
-
"""Send an HTML + text email. You can replace render_to_string with your templates."""
|
| 187 |
-
subject = "You're invited to join"
|
| 188 |
-
text_content = f"You have been invited to join. Click the link to accept: {invite_link}"
|
| 189 |
-
html_content = render_to_string("emails/invite.html", {"invite_link": invite_link, "inviter": inviter})
|
| 190 |
-
|
| 191 |
-
msg = EmailMultiAlternatives(subject, text_content, settings.DEFAULT_FROM_EMAIL, [email])
|
| 192 |
-
msg.attach_alternative(html_content, "text/html")
|
| 193 |
-
msg.send()
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
@api_view(["POST"])
|
| 197 |
-
@permission_classes([IsAuthenticated, IsAdminUser])
|
| 198 |
-
def invite_user(request):
|
| 199 |
-
serializer = InvitationSerializer(data=request.data)
|
| 200 |
-
serializer.is_valid(raise_exception=True)
|
| 201 |
-
|
| 202 |
-
email = serializer.validated_data["email"].lower()
|
| 203 |
-
role = serializer.validated_data.get("role", "RESEARCHER")
|
| 204 |
-
|
| 205 |
-
# Prevent inviting an email that already has a user
|
| 206 |
-
if User.objects.filter(email__iexact=email).exists():
|
| 207 |
-
return Response({"error": "A user with this email already exists."}, status=status.HTTP_400_BAD_REQUEST)
|
| 208 |
-
|
| 209 |
-
# If there's an existing pending invite, optionally reuse or return error
|
| 210 |
-
invitation, created = Invitation.objects.get_or_create(email=email, defaults={"role": role, "invited_by": request.user})
|
| 211 |
-
if not created:
|
| 212 |
-
# update expiry and role if you want
|
| 213 |
-
invitation.role = role
|
| 214 |
-
invitation.expires_at = timezone.now() + timezone.timedelta(hours=48)
|
| 215 |
-
invitation.invited_by = request.user
|
| 216 |
-
invitation.is_accepted = False
|
| 217 |
-
invitation.save()
|
| 218 |
-
|
| 219 |
-
invite_link = _build_invite_link(invitation.token)
|
| 220 |
-
|
| 221 |
-
# Send email (sync). Replace with async task if needed.
|
| 222 |
-
_send_invite_email(email, invite_link, inviter=getattr(request.user, "username", None))
|
| 223 |
-
|
| 224 |
-
return Response({"message": "Invitation sent."}, status=status.HTTP_201_CREATED)
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
@api_view(["POST"])
|
| 228 |
-
@permission_classes([AllowAny])
|
| 229 |
-
def accept_invite(request, token):
|
| 230 |
-
# Validate invitation
|
| 231 |
-
try:
|
| 232 |
-
invitation = Invitation.objects.get(token=token, is_accepted=False)
|
| 233 |
-
except Invitation.DoesNotExist:
|
| 234 |
-
return Response({"error": "Invalid or already used invitation."}, status=status.HTTP_400_BAD_REQUEST)
|
| 235 |
-
|
| 236 |
-
if invitation.is_expired():
|
| 237 |
-
return Response({"error": "Invitation has expired."}, status=status.HTTP_400_BAD_REQUEST)
|
| 238 |
-
|
| 239 |
-
serializer = AcceptInvitationSerializer(data=request.data)
|
| 240 |
-
serializer.is_valid(raise_exception=True)
|
| 241 |
-
|
| 242 |
-
username = serializer.validated_data["username"]
|
| 243 |
-
password = serializer.validated_data["password"]
|
| 244 |
-
first_name = serializer.validated_data.get("first_name", "")
|
| 245 |
-
last_name = serializer.validated_data.get("last_name", "")
|
| 246 |
-
|
| 247 |
-
# Create the user
|
| 248 |
-
user = User.objects.create_user(username=username, email=invitation.email, password=password)
|
| 249 |
-
user.first_name = first_name
|
| 250 |
-
user.last_name = last_name
|
| 251 |
-
|
| 252 |
-
# Set role if your User model supports it
|
| 253 |
-
if hasattr(user, "role"):
|
| 254 |
-
user.role = invitation.role
|
| 255 |
-
|
| 256 |
-
user.save()
|
| 257 |
-
|
| 258 |
-
# Mark invitation accepted
|
| 259 |
-
invitation.is_accepted = True
|
| 260 |
-
invitation.save()
|
| 261 |
-
|
| 262 |
-
return Response({"message": "User created successfully."}, status=status.HTTP_201_CREATED)
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
@api_view(["GET"])
|
| 266 |
-
@permission_classes([AllowAny])
|
| 267 |
-
def verify_invite(request, token):
|
| 268 |
-
"""Optional endpoint for the frontend to check token validity before rendering the sign up form."""
|
| 269 |
-
try:
|
| 270 |
-
invitation = Invitation.objects.get(token=token, is_accepted=False)
|
| 271 |
-
except Invitation.DoesNotExist:
|
| 272 |
-
return Response({"valid": False, "reason": "not_found"}, status=status.HTTP_404_NOT_FOUND)
|
| 273 |
-
|
| 274 |
-
if invitation.is_expired():
|
| 275 |
-
return Response({"valid": False, "reason": "expired"}, status=status.HTTP_400_BAD_REQUEST)
|
| 276 |
-
|
| 277 |
-
return Response({"valid": True, "email": invitation.email, "expires_at": invitation.expires_at})
|
| 278 |
-
```
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
## 7) URL routes (urls.py)
|
| 282 |
-
|
| 283 |
-
```python
|
| 284 |
-
# admin_app/urls.py
|
| 285 |
-
from django.urls import path
|
| 286 |
-
from . import views
|
| 287 |
-
|
| 288 |
-
urlpatterns = [
|
| 289 |
-
path("invite/", views.invite_user, name="invite-user"),
|
| 290 |
-
path("accept-invite/<uuid:token>/", views.accept_invite, name="accept-invite"),
|
| 291 |
-
path("verify-invite/<uuid:token>/", views.verify_invite, name="verify-invite"),
|
| 292 |
-
]
|
| 293 |
-
```
|
| 294 |
-
|
| 295 |
-
Include `app.urls` into your project `urls.py`.
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
## 8) Expiry cleanup (management command)
|
| 300 |
-
|
| 301 |
-
A management command to remove stale invitations (optional):
|
| 302 |
-
|
| 303 |
-
```python
|
| 304 |
-
# app/management/commands/cleanup_invitations.py
|
| 305 |
-
from django.core.management.base import BaseCommand
|
| 306 |
-
from django.utils import timezone
|
| 307 |
-
from app.models import Invitation
|
| 308 |
-
|
| 309 |
-
class Command(BaseCommand):
|
| 310 |
-
help = "Delete expired invitations that haven't been accepted"
|
| 311 |
-
|
| 312 |
-
def handle(self, *args, **kwargs):
|
| 313 |
-
qs = Invitation.objects.filter(expires_at__lt=timezone.now(), is_accepted=False)
|
| 314 |
-
count = qs.count()
|
| 315 |
-
qs.delete()
|
| 316 |
-
self.stdout.write(self.style.SUCCESS(f"Deleted {count} expired invitations"))
|
| 317 |
-
```
|
| 318 |
-
|
| 319 |
-
Schedule this in cron or a periodic task if desired.
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
## 9) Optional: Send emails asynchronously (Celery)
|
| 323 |
-
|
| 324 |
-
**Install & configure** Celery and a broker (Redis example). This example shows a task and how to call it.
|
| 325 |
-
|
| 326 |
-
```python
|
| 327 |
-
# project/celery.py (basic setup)
|
| 328 |
-
import os
|
| 329 |
-
from celery import Celery
|
| 330 |
-
|
| 331 |
-
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
|
| 332 |
-
app = Celery('project')
|
| 333 |
-
app.config_from_object('django.conf:settings', namespace='CELERY')
|
| 334 |
-
app.autodiscover_tasks()
|
| 335 |
-
```
|
| 336 |
-
|
| 337 |
-
```python
|
| 338 |
-
# admin_app/tasks.py
|
| 339 |
-
from celery import shared_task
|
| 340 |
-
from .views import _send_invite_email
|
| 341 |
-
|
| 342 |
-
@shared_task
|
| 343 |
-
def send_invite_email_task(email, invite_link, inviter=None):
|
| 344 |
-
_send_invite_email(email, invite_link, inviter=inviter)
|
| 345 |
-
```
|
| 346 |
-
|
| 347 |
-
In the `invite_user` view, replace the synchronous send with:
|
| 348 |
-
|
| 349 |
-
```python
|
| 350 |
-
from .tasks import send_invite_email_task
|
| 351 |
-
# ...
|
| 352 |
-
send_invite_email_task.delay(email, invite_link, getattr(request.user, 'username', None))
|
| 353 |
-
```
|
| 354 |
-
|
| 355 |
-
And add Celery settings in `settings.py` (example):
|
| 356 |
-
|
| 357 |
-
```python
|
| 358 |
-
CELERY_BROKER_URL = env('REDIS_URL', default='redis://localhost:6379/0')
|
| 359 |
-
CELERY_ACCEPT_CONTENT = ['json']
|
| 360 |
-
CELERY_TASK_SERIALIZER = 'json'
|
| 361 |
-
```
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
## 10) Tests (basic examples)
|
| 365 |
-
|
| 366 |
-
Example tests using DRF's APIClient.
|
| 367 |
-
|
| 368 |
-
```python
|
| 369 |
-
# admin_app/tests.py
|
| 370 |
-
from django.urls import reverse
|
| 371 |
-
from rest_framework.test import APITestCase, APIClient
|
| 372 |
-
from django.contrib.auth import get_user_model
|
| 373 |
-
from django.conf import settings
|
| 374 |
-
from .models import Invitation
|
| 375 |
-
|
| 376 |
-
User = get_user_model()
|
| 377 |
-
|
| 378 |
-
class InviteFlowTests(APITestCase):
|
| 379 |
-
def setUp(self):
|
| 380 |
-
self.admin = User.objects.create_superuser(username='admin', email='admin@example.com', password='pass')
|
| 381 |
-
self.client = APIClient()
|
| 382 |
-
self.client.login(username='admin', password='pass')
|
| 383 |
-
|
| 384 |
-
def test_invite_creates_invitation(self):
|
| 385 |
-
url = reverse('invite-user')
|
| 386 |
-
resp = self.client.post(url, {'email': 'new@example.com', 'role': 'RESEARCHER'}, format='json')
|
| 387 |
-
self.assertEqual(resp.status_code, 201)
|
| 388 |
-
self.assertTrue(Invitation.objects.filter(email='new@example.com').exists())
|
| 389 |
-
|
| 390 |
-
def test_accept_invite_creates_user(self):
|
| 391 |
-
inv = Invitation.objects.create(email='accept@example.com')
|
| 392 |
-
url = reverse('accept-invite', kwargs={'token': inv.token})
|
| 393 |
-
resp = self.client.post(url, {'username': 'accepted', 'password': 'secret'}, format='json')
|
| 394 |
-
self.assertEqual(resp.status_code, 201)
|
| 395 |
-
self.assertTrue(User.objects.filter(username='accepted').exists())
|
| 396 |
-
```
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
## 11) Security & UX considerations
|
| 400 |
-
|
| 401 |
-
- **Token strength:** `uuid4` is generally fine for invitation tokens kept in DB. If you want tamper-proof tokens without DB, consider `django.core.signing` or JWTs; but DB-backed tokens let you revoke easily.
|
| 402 |
-
- **Expiry:** keep a reasonable expiry (48 hours is common). Consider letting admins re-send invitations which issues a new token.
|
| 403 |
-
- **One-time use:** mark token `is_accepted=True` once used to prevent reuse.
|
| 404 |
-
- **Check duplicates:** prevent sending invitations to emails already registered.
|
| 405 |
-
- **Rate limiting:** avoid spammy invite endpoints by rate-limiting admin actions.
|
| 406 |
-
- **Logging:** avoid logging full tokens in plaintext logs.
|
| 407 |
-
- **Email privacy:** do not put sensitive info in the invite link.
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
## 12) Next steps / optional improvements
|
| 411 |
-
|
| 412 |
-
- Let admin **revoke** invites and show invitation status in admin panel.
|
| 413 |
-
- Provide an endpoint to **resend** invites (generate new token or extend expiry).
|
| 414 |
-
- Add frontend flow: a page that `GET /verify-invite/<token>/` to confirm validity and show a friendly sign-up form.
|
| 415 |
-
- Add analytics (who accepted invites, conversion rates).
|
| 416 |
-
- Use a transactional email provider (SendGrid/SES) and templates for better deliverability.
|
| 417 |
-
|
| 418 |
-
---
|
| 419 |
-
|
| 420 |
-
If you want, I can also:
|
| 421 |
-
|
| 422 |
-
- Add **Celery + Redis** full setup examples and supervisor systemd unit for worker
|
| 423 |
-
- Provide a **ready-to-drop-in `views.py` file** or a **backend repo skeleton**
|
| 424 |
-
- Produce a **downloadable `.md` file** or a GH gist
|
| 425 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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