Skip to content

iodsky/Connectly

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

 ████   ████  ██   ██ ██   ██ ██████  ████  ██████ ██     ██  ██ 
██     ██  ██ ███  ██ ███  ██ ██     ██       ██   ██      ████  
██     ██  ██ ██ █ ██ ██ █ ██ ████   ██       ██   ██       ██   
██     ██  ██ ██  ███ ██  ███ ██     ██       ██   ██       ██   
 ████   ████  ██   ██ ██   ██ ██████  ████    ██   ██████   ██   

Built with the tools and technologies:

Django Pytest Python

📄 Table of Contents

Table of Contents

✨ Overview

Connectly is a Django-based social media platform that enables users to create profiles, share posts, interact with content, and connect with others. The platform provides a robust API for user management, content creation, and social interactions.

Key aspects of Connectly include:

  • Secure user authentication with Google OAuth2 and JWT tokens

  • Content management system for posts and comments with media support

  • Social features including following users and liking content

  • Role-based access control for administrators and moderators

  • Comprehensive testing suite with pytest

  • Scalable architecture with middleware for pagination and rate limiting

The platform is designed to be developer-friendly with clear API endpoints, thorough documentation, and modular structure for easy maintenance and extension.


📌 Features

Component Details
User Management

  • User registration and profile creation
  • Google OAuth2 authentication
  • JWT token-based authentication
  • Role-based permissions (Admin, Moderator)
  • Profile customization (bio, personal info)
Content System
  • Create, read, update, and delete posts
  • Post comments with nested replies
  • Media attachments (images and videos)
  • Automatic media compression
  • Privacy settings for posts
Social Features
  • Follow/unfollow other users
  • Like/unlike posts and comments
  • View user feeds
  • Profile browsing and search
Technical Infrastructure
  • Rate limiting middleware
  • Pagination support
  • Centralized logging
  • Configuration management
  • Standardized response formatting
Development Tools
  • Comprehensive test suite
  • Factory-based test data generation
  • API documentation
  • SQLite database (development)
  • Django admin interface

The features are implemented with a focus on performance, security, and maintainability, following Django best practices and REST API design principles.

📁 Project Structure

└── Connectly/
    ├── apps
    │   ├── medias
    │   ├── posts
    │   └── users
    ├── connectly
    │   ├── middleware
    │   ├── settings.py
    │   ├── urls.py
    │   ├── views.py
    │   └── wsgi.py
    ├── db.sqlite3
    ├── manage.py
    ├── media
    │   ├── comment_images
    │   ├── post_images
    │   └── post_videos
    ├── pytest.ini
    ├── README.md
    ├── requirements.txt
    ├── tests
    │   ├── utils
    │   └── views
    └── utils
        ├── config_manager.py
        ├── logger.py
        ├── media_compressor.py
        ├── rate_limiter.py
        └── response_factory.py

📑 Project Index

Connectly
__root__
⦿ __root__
File Name Summary
cert.crt - Generate Certificate Files
- The cert.crt file provides a self-signed certificate for testing purposes, ensuring secure communication between systems
- It enables the creation of trusts and secure connections without relying on external certificate authorities
- This certificate file is used to establish a secure connection between clients and servers in various development environments.
db.sqlite3 Real-time Data AggregationIt enables efficient collection and aggregation of product data from various sources, ensuring seamless synchronization across the platform. Automated Inventory updates by integrating with our existing backend infrastructure, it facilitates automated updates to inventory levels, reducing manual errors and improving overall accuracy. Data-Driven Decision making the code provides a robust foundation for data analysis, enabling us to gain valuable insights into product trends, demand patterns, and supply chain efficiency.By leveraging this component, EcoSphere is poised to deliver a streamlined user experience, enhanced operational efficiency, and data-driven decision support capabilities.
manage.py - Launches the Django development server to execute administrative tasks
- The manage.py script serves as a command-line utility for various Django-related operations
- It ensures proper setup and activation of virtual environments, setting the stage for project initialization and management
- With this script, users can effortlessly run administrative tasks, facilitating efficient project development and deployment.
pytest.ini - Reorganizes test configurations
- The pytest.ini file configures Pytest to run tests in the project, utilizing the Django settings module and specifying test files with a .py extension
- It enables reporting of test results, allowing for efficient testing of connected components within the Connectly application.
requirements.txt - Architecture OverviewThe requirements.txt file serves as the central configuration point for the projects dependencies, specifying a comprehensive set of packages to ensure seamless integration and execution across the entire codebase architecture
- It enables smooth collaboration and versioning management, ultimately supporting the efficient development, testing, and deployment of the Django-based application.
apps
⦿ apps
medias
⦿ apps.medias
File Name Summary
admin.py - Simplifies media administration by registering models with the Django admin interface.The admin.py file plays a crucial role in setting up media management capabilities within the project, enabling administrators to efficiently manage and interact with media-related data
- By registering models here, you enable the admin interface to display and edit media content according to your projects structure and requirements.
apps.py - Configures Django Application**MediasConfig enables a Django application with database configuration and naming conventions
- It sets the default auto-field to BigAutoField and defines the applications namespace as apps.medias
- This configuration provides a solid foundation for building media-related features within the Django application, aligning with the broader project structure.
factories.py - The media factory class in apps.medias.factories.py creates and manages different types of media files associated with content objects, such as images and videos
- It provides a standardized way to create and save media files, ensuring consistency across the project
- By leveraging Djangos built-in models and content types, it streamlines media file creation and upload processes.
models.py - Model Definition Purpose**Defines a Media model that stores files with corresponding metadata, automatically generating unique file names and timestamps
- The model supports image and video types, with optional JSON metadata fields and a foreign key referencing the content type of associated objects
- This design enables flexible storage and retrieval of media assets within the applications architecture.
serializers.py - The serializers.py file provides a serializer class for the Media model, enabling data exchange between the models and external applications
- It determines the valid media types and compresses files accordingly, while maintaining metadata integrity
- This serialization process ensures consistent and efficient data transfer within the projects architecture.
migrations
⦿ apps.medias.migrations
File Name Summary
0001_initial.py - The 0001_initial.py migration file sets up the initial database schema for the media management system
- It creates a new Media model with fields to store various types of media files, such as images and videos, along with metadata and object IDs
- This marks the foundation of the projects data structure, providing a starting point for further development and expansion.
posts
⦿ apps.posts
File Name Summary
admin.py - The admin.py file serves as a critical entry point for configuring Djangos admin interface for posts management
- It enables administrators to view, create, edit, and delete post-related data in a centralized manner
- By registering models within this file, users can efficiently manage their content, allowing for streamlined content creation and updates.
apps.py - Configures the posts application within the Django project
- Establishes the default auto-field type and app name, enabling the post application to function correctly
- Integrates with the broader project structure, allowing for seamless deployment and management of posts-related features and functionality
- Enables app registration and configuration for proper Django maintenance and updates.
factories.py - The post factories provide a crucial foundation for the entire codebase architecture by enabling efficient creation of post and comment instances
- By leveraging Djangos ORM, these factories standardize the process of generating posts and comments, ensuring data consistency across the application
- They serve as a critical building block for populating the project with sample data, facilitating testing and development workflows.
models.py - Validates and restricts post and comment content creation to adhere to established guidelines
- The clean method checks for excessive media files (20 images, 1 video), while the save method ensures that author changes are not allowed on existing posts
- Similarly, it prevents changing of comments associated posts or commenters
- These constraints maintain data coherence and prevent misuse, ensuring a secure and organized content management system.
permissions.py - Provides fine-grained permission control for posts within the application
- The IsAuthor class restricts access to post creation and editing only for the posts author, while allowing read-only access to all users
- The IsOwnerOrReadOnly class grants read-only access to others posts if the user is not the owner, ensuring a balance between authorization and data accessibility.
serializers.py - Provides a comprehensive API serialization framework for managing comments on posts within the platforms content management system
- Enables efficient data exchange between front-end and back-end applications, ensuring seamless integration of comment features and media support
- Facilitates validation, creation, and updating of comments and associated media files.
tests.py - Test Suite Enabler**The tests.py file enables the test suite for the post application, allowing users to create and run tests to ensure the functionality and integrity of the codebase
- By leveraging Djangos built-in testing framework, this module facilitates a structured approach to quality assurance, ultimately contributing to a more robust and reliable project environment.
urls.py - Defines the URL patterns for a Django-based blog application, mapping URLs to view functions that handle post and comment listings, details, liking, and commenting actions
- The code enables users to navigate and interact with posts and comments in a structured and efficient manner, facilitating the core functionality of the application.
views.py - Invalid likes and dislikes are being stored multiple times due to a faulty many-to-many relationship
- The liked_by field is storing user IDs but not the associated post comment IDs
- This can be resolved by adding foreign key fields to the models.
migrations
⦿ apps.posts.migrations
File Name Summary
0001_initial.py - Initialize the projects database schema
- The 0001_initial.py file creates the core models for a blog application, including Post, Comment, and their respective image and video extensions, which establish relationships with user authentication and liking functionality
- This migration sets the foundation for the entire codebase architecture, enabling data storage and interaction between users, posts, comments, images, and videos.
0002_remove_comment_image.py - Migrates Django database schema by removing the image field from the comment model, effectively reversing a previous migration step
- This change is part of a larger refactoring effort to improve the overall structure and maintainability of the project
- The removal of this field aligns with the project's goal of streamlining its functionality and promoting data consistency across different models.
0003_remove_postimage_post_remove_postvideo_post_and_more.py - This migration file updates the database schema by removing fields from the PostImage model and deleting associated models
- It ensures data integrity by removing references to non-existent models, enabling future schema changes without breaking existing data
- The migration is part of a larger project restructuring effort to improve data management and scalability.
0004_alter_comment_content_alter_post_content.py - Migrates Django Post Model FieldsThe provided migration script updates two model fields in the posts' application to allow blank values
- It aligns with the project's database schema evolution, ensuring data integrity and enabling the collection of optional post content
- This change enables a flexible and scalable content management system for the application.
0005_post_privacy_type.py - Public, Private, and Followers
- It builds upon an existing migration framework, leveraging Django's built-in features
- The update expands the post's metadata to accommodate more granular privacy settings, enhancing data security and management capabilities within the project.
users
⦿ apps.users
File Name Summary
admin.py - Establishes the Django admin interface for user management
- Enables administrators to view, edit, and manage users within the system
- Facilitates data entry and modification of user information, ensuring a centralized and organized approach to user management
- Integrates with existing project structure, allowing for streamlined data access and manipulation.
apps.py - Initialize User Configuration**The apps.py file initializes the user configuration for the project, setting up the necessary configuration for Djangos built-in authentication and authorization system
- It enables role-based access controls by defining default auto-field settings and imports signals to create groups after applying migrations
- This setup ensures seamless integration with other parts of the project, ensuring secure and efficient user management.
authentication.py - Validates Google OAuth2 access tokens for authentication purposes
- The GoogleAuthentication class checks the token against Googles Userinfo API to verify its validity and retrieves user data, which is then used to create or update a corresponding user in the database
- It integrates with Djangos authentication system and Simple JWT middleware to handle various authentication scenarios.
factories.py - Fabricates user profiles and handles user role assignments
- The UserFactory class creates users with associated profiles, checks for existing usernames and emails, and sets up roles through group associations
- It also provides methods to create admin users specifically
- The factory ensures data consistency and validation for user creation, making it a crucial component of the projects backend logic.
models.py - Profile and Follow
- The
Profile model creates a one-to-one relationship between a user and their profile information, including first name, last name, bio, and creation date
- Meanwhile, the
Follow` model establishes a many-to-many relationship for user follow relationships, ensuring that each follower is only associated with unique followed users.
permissions.py - Summary**Enforces fine-grained permission control on user actions, distinguishing between Admin, Moderator, and Owner/Admin roles
- Validates user groups against predefined names to grant or deny access to protected routes
- Integrates seamlessly with the projects authentication system, ensuring secure authorization and access management for users within the users app.
serializers.py - Generates User Data Representation**The provided serializers generate JSON representations of users, profiles, and follow relationships, enabling data exchange between the frontend and backend
- They validate user input, create new profiles, and handle updates to existing ones
- The serializers ensure data consistency and integrity across different parts of the application.
signals.py - Initializes Default User Groups and Admin User After Migrations**The signals.py file plays a crucial role in setting up the initial user groups and admin user upon migrations, ensuring a solid foundation for the project
- It creates default user groups (Admin and Moderator) and a default admin user with associated profile and group assignments
- This setup is critical for the projects core functionality and security.
tests.py - The tests.py file serves as a testing foundation for the user application, ensuring its functionality is thoroughly tested and validated
- It provides a robust set of tests that verify the correctness of user-related endpoints, allowing developers to confidently deploy and maintain the application
- By leveraging Djangos testing framework, this codebase prioritizes reliability and quality assurance.
urls.py - Configures URL routes for the users app, establishing connections between user data management and profile-related features
- Enables interaction with various views, including listing users, updating profiles, registering new accounts, changing roles, and accessing user feeds, profiles, posts, comments, and follow status
- Facilitates seamless navigation within the apps core functionality.
views.py - Retrieves the profile of a specific user. POSTCreates a new profile for an authenticated user. PUT/{user_id}Updates an existing profile. DELETE/{user_id}Deletes a profile.Comments and Posts GETRetrieves comments or posts from a specific user. POSTCreates a new comment or post for an authenticated user. PUT/{comment_id}/{post_id}Updates an existing comment or post. DELETE/{comment_id}/{post_id}Deletes a comment or post.Followers and Following GET/{user_id}?type=following/followerRetrieves followers or following users for a specific user. Follows or unfollows another user.The API uses caching to improve performance by storing frequently accessed data in memory
- It also employs authentication and authorization mechanisms using Djangos built-in system to ensure only authorized users can modify their profiles, create comments and posts, and follow/unfollow other users.
migrations
⦿ apps.users.migrations
File Name Summary
0001_initial.py - This migration script creates the initial database schema for a user management system, including Profile and Follow models
- It establishes relationships between users and allows followers to follow each other while maintaining uniqueness constraints
- The schema provides a foundation for user profiles and friend relationships, enabling data storage and retrieval for the application.
0002_alter_profile_id.py - The 0002_alter_profile_id.py migration file upgrades the database schema by altering the id field of the Profile model to use an auto-incrementing primary key
- This change ensures data consistency and enables efficient management of user profiles
- Part of a larger Django project, this migration is triggered automatically when running migrations.
connectly
⦿ connectly
File Name Summary
asgi.py - Configures the ASGI environment for the Connectly project
- Establishes a connection to Djangos settings and exposes it as an ASGI application
- Enabling the project to run under ASGI, allowing for efficient asynchronous request handling
- Facilitating deployment and integration with other frameworks in an async-friendly manner.
settings.py - *Configures Django Environment*This settings file configures the Django environment for a Connectly project
- It enables authentication through Google and Simple JWT, sets up CORS headers, and defines application definitions and middleware classes
- The configuration also specifies database connections, caching, and security settings for the project
- This file serves as the backbone of the projects infrastructure, providing a solid foundation for development and deployment.
urls.py - Configures URLs for the Connectly project, defining routes for various endpoints, including administrative dashboards, user profiles, and authentication tokens
- Establishes a foundation for handling incoming requests and directing them to corresponding views, ensuring seamless interaction between different aspects of the application
- Provides a centralized hub for URL routing and validation.
views.py - The connectly/views.py file implements a logout request handler that verifies the validity of a refresh token and blacklists it upon successful logout
- Upon successful verification, it returns a success response with a status code of 200
- If any errors occur during validation or token processing, an error response is returned with a relevant HTTP status code.
wsgi.py - *Initialize API Framework* The wsgi.py file serves as the entry point for the Connectly projects web application framework, exposing the WSGI callable as a module-level variable named application
- It sets up Django's environment and initializes logging
- By running this file, the API is made available for deployment, enabling users to access the project's features and functionality.
middleware
⦿ connectly.middleware
File Name Summary
pagination_middleware.py - The pagination_middleware.py file enables paginated responses for API queries, allowing users to navigate through results efficiently
- It leverages Djangos built-in pagination functionality with customizable page size settings
- This middleware ensures that response data is properly formatted and serializable for JSON output, making it easier for clients to handle pagination in their applications.
rate_limit_middleware.py - *Enforce Rate Limiting Across API Endpoints*This middleware class enforces rate limiting on API requests to prevent abuse and ensure fair usage
- It integrates with a memory-based rate limiter, allowing clients to reach their allowed request rates within a specified time window
- By implementing rate limiting, the project ensures the integrity of its API and protects it from excessive traffic.
utils
⦿ utils
File Name Summary
config_manager.py - Manages the applications configuration settings as a singleton class, providing access to default values and allowing setting updates through methods such as get_settings and set_settings
- Ensures consistency across the project by initializing settings with a predefined set of defaults
- Facilitates centralized management of application configuration.
logger.py - Achieves centralized logging configuration across the application
- The Logger class ensures a single instance is created and reused throughout the project, providing a consistent logging experience with configurable output formats and levels
- Facilitates controlled logging behavior, allowing for easy adaptation to different environments and use cases.
media_compressor.py This implements the ImageAndVideoProcessing class, offering functionality for compressing images and videos. The `compress_image` method handles resizing and saving images in formats like JPEG or PNG, while `compress_video` uses ffmpeg to compress video files with specified bitrates. Both methods include error handling using ValidationError.
rate_limiter.py - The rate limiter factory enables the creation of various rate limiters, including an in-memory rate limiter that stores request timestamps and cleans up old data regularly to maintain a specified request threshold within a given time window
- The factory provides a flexible way to create different types of rate limiters based on user configuration settings.
response_factory.py Creates standardized HTTP responses for Django REST framework applications.Generates responses with various HTTP status codes (200 OK, 201 Created, 204 No Content, etc.) and logs messages at different levels.Facilitates uniform error handling and provides a consistent response structure across the application.

🚀 Getting Started

📋 Prerequisites

This project requires the following dependencies:

  • Programming Language: Python
  • Package Manager: Pip

⚙️ Installation

Build Connectly from the source and intsall dependencies:

  1. Clone the repository:
git clone https://github.com/IbraDoesCode/connectly.git
  1. Create a virtual environment and activate it:
python -m venv venv
source venv/bin/activate
  1. Install the required dependencies:
pip install -r requirements.txt
  1. Apply the database migrations:
python manage.py migrate
  1. Start the development server:
python manage.py runserver

The API will be available at http://localhost:8000/.

💻 Usage

The Connectly API provides the following endpoints:

User Endpoints

  • POST /users/register/: Register a new user.
  • PATCH /users/<int:user_id>: Update a user's profile.
  • DELETE /users/<int:user_id>: Delete a user.
  • POST /users/role/<int:user_id>: Change a user's role (Admin or Moderator).

Post Endpoints

  • GET /posts/: List all posts.
  • POST /posts/: Create a new post.
  • GET /posts/<int:post_id>/: Retrieve a specific post.
  • PATCH /posts/<int:post_id>/: Update a post.
  • DELETE /posts/<int:post_id>/: Delete a post.
  • POST /posts/<int:post_id>/like: Like a post.
  • DELETE /posts/<int:post_id>/like: Unlike a post.

Comment Endpoints

  • GET /posts/<int:post_id>/comments/: List comments for a specific post.
  • POST /posts/<int:post_id>/comments/: Create a new comment.
  • GET /posts/<int:post_id>/comments/<int:comment_id>/: Retrieve a specific comment.
  • PUT /posts/<int:post_id>/comments/<int:comment_id>/: Update a comment.
  • DELETE /posts/<int:post_id>/comments/<int:comment_id>/: Delete a comment.
  • POST /posts/<int:post_id>/comments/<int:comment_id>/like: Like a comment.
  • DELETE /posts/<int:post_id>/comments/<int:comment_id>/like: Unlike a comment.

Profile Endpoints

  • GET /profiles/: Search for user profiles.
  • GET /profiles/<str:user_id>/: Retrieve a user's profile.
  • PATCH /profiles/<str:user_id>/: Update a user's profile.
  • DELETE /profiles/<str:user_id>/: Delete a user's profile.
  • GET /profiles/<str:user_id>/posts/: Retrieve a user's posts.
  • GET /profiles/<str:user_id>/comments/: Retrieve a user's comments.
  • POST /profiles/<str:user_id>/follow: Follow a user.
  • DELETE /profiles/<str:user_id>/follow: Unfollow a user.

📲 API

The Connectly API uses the following technologies:

  • Django
  • Django REST Framework
  • Simple JWT for authentication
  • SQLite database (for development)

The API supports the following features:

  • User registration and authentication
  • CRUD operations for posts and comments
  • Liking and unliking posts and comments
  • Searching and retrieving user profiles
  • Following and unfollowing users
  • Role-based access control (Admin and Moderator roles)

🧪 Testing

The project includes a comprehensive test suite built with pytest. To run the tests, execute the following command:

pytest

The test suite covers the following areas:

  • User registration and authentication
  • Post and comment CRUD operations
  • Liking and unliking posts and comments
  • Profile search and retrieval
  • Following and unfollowing users
  • Role-based access control

The test suite also includes fixtures for setting up the test environment and mocking external dependencies (eg., image and video processing).


✨ Acknowledgments


About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages