Building a secure and scalable authentication system is crucial for any real-time communication platform in today's digital landscape. In this article, I'll walk you through how I built the authentication system for CollabSphere, a modern real-time collaboration platform, using Django and Django REST Framework.
CollabSphere's authentication system is built with these key requirements in mind:
Custom User Model
At the heart of this system is a custom user model that extends Django's AbstractBaseUser:
class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=50, unique=True) full_name = models.CharField(max_length=255) # Profile fields avatar = models.ImageField(upload_to='avatars/', null=True) bio = models.TextField(max_length=500, blank=True) # Status tracking is_online = models.BooleanField(default=False) last_seen = models.DateTimeField(null=True) #...
Role-Based Access Control
I implemented a flexible role system to manage user permissions:
class Role(models.Model): name = models.CharField(max_length=50, unique=True) description = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) priority = models.IntegerField(default=0) custom_permissions = models.JSONField(default=dict) # Define permissions for each role can_moderate = models.BooleanField(default=False) can_manage_users = models.BooleanField(default=False) can_manage_roles = models.BooleanField(default=False) can_delete_messages = models.BooleanField(default=False) can_ban_users = models.BooleanField(default=False) class Meta: verbose_name = _('role') verbose_name_plural = _('roles') ordering = ['-priority'] def __str__(self): return self.name
Registration Process
Client -> RegisterView -> UserRegistrationSerializer -> CustomUserManager.create_user() -> Database -> Send verification email -> Assign default role -> Generate JWT tokens
When a new user registers:
Example registration endpoint:
class RegisterView(generics.CreateAPIView): def create(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() # Send verification email user.send_verification_email() # Generate tokens refresh = RefreshToken.for_user(user) return Response({ 'user': UserSerializer(user).data, 'tokens': { 'refresh': str(refresh), 'access': str(refresh.access_token), } })
Login Process
Client -> LoginView -> UserLoginSerializer -> authenticate() -> JWT tokens -> Update online status -> Store device tokens -> Return user permissions
The login flow includes:
Real-Time Status Management
The system tracks user status in real time:
def update_online_status(self, status): self.is_online = status self.last_seen = timezone.now() self.save(update_fields=['is_online', 'last_seen'])
Password Security
Email Verification
def send_verification_email(self): token = self.generate_verification_token() verification_url = f"{settings.FRONTEND_URL}/verify-email/{token}" send_mail( 'Verify your email address', render_to_string('users/verify_email.html', { 'user': self, 'verification_url': verification_url }), settings.DEFAULT_FROM_EMAIL, [self.email] )
JWT Authentication
The system uses JWT tokens for secure API access:
refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token) }
The system supports multiple devices per user:
device_tokens = models.JSONField(default=dict)
This allows:
Separation of Concerns
Security Measures
Performance Optimization
Here's how to test the authentication flow:
class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=50, unique=True) full_name = models.CharField(max_length=255) # Profile fields avatar = models.ImageField(upload_to='avatars/', null=True) bio = models.TextField(max_length=500, blank=True) # Status tracking is_online = models.BooleanField(default=False) last_seen = models.DateTimeField(null=True) #...
Building a secure authentication system requires careful planning and implementation. Following Django's best practices and implementing proper security measures, we've created a robust system for CollabSphere that effectively handles user authentication, authorization, and real-time status management.
The complete code for this implementation is available on the GitHub repository.
The above is the detailed content of Building a Secure Authentication System for CollabSphere Part A Real-Time Communication Platform. For more information, please follow other related articles on the PHP Chinese website!