sojorn/sojorn_docs/ENHANCED_REGISTRATION_FLOW.md

283 lines
8.4 KiB
Markdown

# Enhanced Registration Flow - Implementation Guide
## 🎯 **Overview**
Complete registration system with Cloudflare Turnstile verification, terms acceptance, and email preferences. Provides robust security and compliance while maintaining user experience.
## 🔐 **Security Features**
### **Cloudflare Turnstile Integration**
- **Bot Protection**: Prevents automated registrations
- **Human Verification**: Ensures real users only
- **Development Bypass**: Automatic success when no secret key configured
- **IP Validation**: Optional remote IP verification
- **Error Handling**: User-friendly error messages
### **Required Validations**
- **✅ Turnstile Token**: Must be valid and verified
- **✅ Terms Acceptance**: Must accept Terms of Service
- **✅ Privacy Acceptance**: Must accept Privacy Policy
- **✅ Email Format**: Valid email address required
- **✅ Password Strength**: Minimum 6 characters
- **✅ Handle Uniqueness**: No duplicate handles allowed
- **✅ Email Uniqueness**: No duplicate emails allowed
## 📧 **Email Preferences**
### **Newsletter Opt-In**
- **Optional**: User can choose to receive newsletter emails
- **Default**: `false` (user must explicitly opt-in)
- **Purpose**: Marketing updates, feature announcements
### **Contact Opt-In**
- **Optional**: User can choose to receive contact emails
- **Default**: `false` (user must explicitly opt-in)
- **Purpose**: Transactional emails, important updates
## 🔧 **API Specification**
### **Registration Endpoint**
```http
POST /api/v1/auth/register
Content-Type: application/json
```
### **Request Body**
```json
{
"email": "user@example.com",
"password": "SecurePassword123!",
"handle": "username",
"display_name": "User Display Name",
"turnstile_token": "0xAAAAAA...",
"accept_terms": true,
"accept_privacy": true,
"email_newsletter": false,
"email_contact": true
}
```
### **Required Fields**
- `email` (string, valid email)
- `password` (string, min 6 chars)
- `handle` (string, min 3 chars)
- `display_name` (string)
- `turnstile_token` (string)
- `accept_terms` (boolean, must be true)
- `accept_privacy` (boolean, must be true)
### **Optional Fields**
- `email_newsletter` (boolean, default false)
- `email_contact` (boolean, default false)
### **Success Response**
```json
{
"email": "user@example.com",
"message": "Registration successful. Please verify your email to activate your account.",
"state": "verification_pending"
}
```
### **Error Responses**
```json
// Missing Turnstile token
{"error": "Key: 'RegisterRequest.TurnstileToken' Error:Field validation for 'TurnstileToken' failed on the 'required' tag"}
// Terms not accepted
{"error": "Key: 'RegisterRequest.AcceptTerms' Error:Field validation for 'AcceptTerms' failed on the 'required' tag"}
// Turnstile verification failed
{"error": "Security check failed, please try again"}
// Email already exists
{"error": "Email already registered"}
// Handle already taken
{"error": "Handle already taken"}
```
## 🗄️ **Database Schema**
### **Users Table Updates**
```sql
-- New columns added
ALTER TABLE users ADD COLUMN IF NOT EXISTS email_newsletter BOOLEAN DEFAULT false;
ALTER TABLE users ADD COLUMN IF NOT EXISTS email_contact BOOLEAN DEFAULT false;
-- Performance indexes
CREATE INDEX IF NOT EXISTS idx_users_email_newsletter ON users(email_newsletter);
CREATE INDEX IF NOT EXISTS idx_users_email_contact ON users(email_contact);
```
### **User Record Example**
```sql
SELECT email, status, email_newsletter, email_contact, created_at
FROM users
WHERE email = 'user@example.com';
-- Result:
-- email | status | email_newsletter | email_contact | created_at
-- user@example.com | pending | false | true | 2026-02-05 15:59:48
```
## ⚙️ **Configuration**
### **Environment Variables**
```bash
# Cloudflare Turnstile
TURNSTILE_SECRET_KEY=your_turnstile_secret_key_here
# Development Mode (no verification)
TURNSTILE_SECRET_KEY=""
```
### **Frontend Integration**
#### **Turnstile Widget**
```html
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
<form id="registration-form">
<!-- Your form fields -->
<div class="cf-turnstile" data-sitekey="YOUR_SITE_KEY"></div>
<button type="submit">Register</button>
</form>
```
#### **JavaScript Integration**
```javascript
const form = document.getElementById('registration-form');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const turnstileToken = turnstile.getResponse();
if (!turnstileToken) {
alert('Please complete the security check');
return;
}
const formData = {
email: document.getElementById('email').value,
password: document.getElementById('password').value,
handle: document.getElementById('handle').value,
display_name: document.getElementById('displayName').value,
turnstile_token: turnstileToken,
accept_terms: document.getElementById('terms').checked,
accept_privacy: document.getElementById('privacy').checked,
email_newsletter: document.getElementById('newsletter').checked,
email_contact: document.getElementById('contact').checked
};
try {
const response = await fetch('/api/v1/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
});
const result = await response.json();
if (response.ok) {
// Handle success
console.log('Registration successful:', result);
} else {
// Handle error
console.error('Registration failed:', result.error);
}
} catch (error) {
console.error('Network error:', error);
}
});
```
## 🔄 **Registration Flow**
### **Step-by-Step Process**
1. **📝 User fills registration form**
- Email, password, handle, display name
- Accepts terms and privacy policy
- Chooses email preferences
- Completes Turnstile challenge
2. **🔐 Frontend validation**
- Required fields checked
- Email format validated
- Terms acceptance verified
3. **🛡️ Security verification**
- Turnstile token sent to backend
- Cloudflare validation performed
- Bot protection enforced
4. **✅ Backend validation**
- Email uniqueness checked
- Handle uniqueness checked
- Password strength verified
5. **👤 User creation**
- Password hashed with bcrypt
- User record created with preferences
- Profile record created
- Verification token generated
6. **📧 Email verification**
- Verification email sent
- User status set to "pending"
- 24-hour token expiry
7. **🎉 Success response**
- Confirmation message returned
- Next steps communicated
## 🧪 **Testing**
### **Development Mode**
```bash
# No Turnstile verification when secret key is empty
TURNSTILE_SECRET_KEY=""
```
### **Test Cases**
```bash
# Valid registration
curl -X POST http://localhost:8080/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com","password":"TestPassword123!","handle":"test","display_name":"Test","turnstile_token":"test_token","accept_terms":true,"accept_privacy":true,"email_newsletter":true,"email_contact":false}'
# Missing Turnstile token (should fail)
curl -X POST http://localhost:8080/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com","password":"TestPassword123!","handle":"test","display_name":"Test","accept_terms":true,"accept_privacy":true}'
# Terms not accepted (should fail)
curl -X POST http://localhost:8080/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com","password":"TestPassword123!","handle":"test","display_name":"Test","turnstile_token":"test_token","accept_terms":false,"accept_privacy":true}'
```
## 🚀 **Deployment Status**
### **✅ Fully Implemented**
- Cloudflare Turnstile integration
- Terms and privacy acceptance
- Email preference tracking
- Database schema updates
- Comprehensive validation
- Error handling and logging
### **✅ Production Ready**
- Security verification active
- User preferences stored
- Validation rules enforced
- Error messages user-friendly
- Development bypass available
### **🔧 Configuration Required**
- Add Turnstile secret key to environment
- Configure Turnstile site key in frontend
- Update terms and privacy policy links
- Test with real Turnstile implementation
**The enhanced registration flow provides robust security, legal compliance, and user control over email communications while maintaining excellent user experience!** 🎉