DEV Community

Cover image for Building a Secure Authentication System for CollabSphere Part 2: A Real-Time Communication Platform
kihuni
kihuni

Posted on

Building a Secure Authentication System for CollabSphere Part 2: A Real-Time Communication Platform

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.

System Overview

CollabSphere's authentication system is built with these key requirements in mind:

  • Email-based authentication
  • Role-based access control
  • Real-time user status tracking
  • Multi-device support
  • Secure password management
  • Email verification

Core Components

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)
    #...
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Authentication Flow

Registration Process

Client -> RegisterView -> UserRegistrationSerializer -> CustomUserManager.create_user() -> Database
                      -> Send verification email
                      -> Assign default role
                      -> Generate JWT tokens
Enter fullscreen mode Exit fullscreen mode

When a new user registers:

  1. User submits email, username, and password
  2. System validates the data
  3. Creates user account
  4. Sends verification email
  5. Assign default role
  6. Returns JWT tokens

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),
            }
        })
Enter fullscreen mode Exit fullscreen mode

Login Process

Client -> LoginView -> UserLoginSerializer -> authenticate() -> JWT tokens
                   -> Update online status
                   -> Store device tokens
                   -> Return user permissions
Enter fullscreen mode Exit fullscreen mode

The login flow includes:

  1. Email and password validation
  2. Verification check
  3. Online status update
  4. Device token management
  5. JWT token generation

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'])

Enter fullscreen mode Exit fullscreen mode

Security Features

Password Security

  • Custom password validation
  • Secure password hashing
  • Password change verification

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]
    )
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

Multi-Device Support

The system supports multiple devices per user:

device_tokens = models.JSONField(default=dict)
Enter fullscreen mode Exit fullscreen mode

This allows:

  • Device-specific push notifications
  • Session management
  • Last active device tracking

Best Practices Implemented

Separation of Concerns

  • Models for data structure
  • Serializers for validation
  • Views for business logic

Security Measures

  • Email verification
  • Token-based authentication
  • Password validation
  • Role-based access control

Performance Optimization

  • Efficient database queries
  • Selective field updates
  • Proper indexing

Testing the System

Here's how to test the authentication flow:

# Registration
POST /api/register/
{
    "email": "user@example.com",
    "username": "user123",
    "password": "securepass123",
    "full_name": "John Doe"
}

# Login
POST /api/login/
{
    "email": "user@example.com",
    "password": "securepass123",
    "device_token": "fcm-token-123"
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

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.

Top comments (0)