Skip to content

amirabbas-gh/university-basic-programming-python

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

18 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

University of Tehran Logo

πŸ“š Library Management System

A comprehensive library management system built with Python and FastAPI, featuring role-based access control, book management, loan tracking, and advanced analytics. This project demonstrates modern software development practices including RESTful API design, database integration, containerization, and security best practices.


🎯 Project Overview

This library management system is a full-featured application that allows different user roles (Members, Librarians, and Admins) to interact with a library's book inventory and loan system. The project was developed as the final assignment for the Fundamentals of Computer and Basic Programming course, implementing all core requirements plus several bonus features.

Key Features

  • βœ… Role-Based Access Control - Three distinct user roles with appropriate permissions
  • βœ… Book Management - Add, edit, delete, and search books
  • βœ… Loan System - Request, approve, renew, and return books with status tracking
  • βœ… User Management - Registration, authentication, and user administration
  • βœ… Analytics Dashboard - Insights into popular books, reliable users, and overdue items
  • βœ… Secure Authentication - JWT-based authentication with password encryption
  • βœ… RESTful API - Modern API design with FastAPI
  • βœ… Database Integration - MongoDB for persistent data storage
  • βœ… Containerization - Docker support for easy deployment

πŸ—οΈ Architecture

Technology Stack

  • Framework: FastAPI (Python web framework)
  • Database: MongoDB (NoSQL database)
  • Authentication: JWT (JSON Web Tokens)
  • Password Hashing: bcrypt
  • Containerization: Docker & Docker Compose
  • API Documentation: Automatic OpenAPI/Swagger docs

Architecture Pattern

This project follows Domain Driven Design (DDD) principles, organizing the codebase around business domains and bounded contexts. The architecture is structured to reflect the core business domains of the library management system:

  • Domain Separation: Each domain (admin, librarian, member, analytics, auth) is organized as a separate module with its own router and service layer
  • Bounded Contexts: Clear boundaries between different business contexts (user management, book management, loan management)
  • Domain Models: Business logic encapsulated in domain-specific models and services
  • Layered Architecture: Clear separation between presentation layer (routers), business logic layer (services), and data access layer (database)

This architectural approach ensures:

  • Maintainability: Easy to understand and modify domain-specific features
  • Scalability: New domains can be added without affecting existing ones
  • Testability: Each domain can be tested independently
  • Business Alignment: Code structure mirrors the business domain model

Project Structure

university-basic-programming-python/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ core/              # Core configuration and utilities
β”‚   β”‚   β”œβ”€β”€ config.py      # Application settings
β”‚   β”‚   β”œβ”€β”€ jwt.py         # JWT token management
β”‚   β”‚   └── mongo_base.py  # MongoDB base model
β”‚   β”œβ”€β”€ db/                # Database configuration
β”‚   β”‚   β”œβ”€β”€ mongo.py       # MongoDB connection
β”‚   β”‚   └── seed.py        # Database seeding script
β”‚   β”œβ”€β”€ models/            # Business logic and routes
β”‚   β”‚   β”œβ”€β”€ admin/         # Admin endpoints
β”‚   β”‚   β”‚   β”œβ”€β”€ router.py  # Admin API routes
β”‚   β”‚   β”‚   └── services.py # Admin business logic
β”‚   β”‚   β”œβ”€β”€ analytics/     # Analytics endpoints
β”‚   β”‚   β”‚   β”œβ”€β”€ router.py  # Analytics API routes
β”‚   β”‚   β”‚   └── services.py # Analytics business logic
β”‚   β”‚   β”œβ”€β”€ auth/          # Authentication endpoints
β”‚   β”‚   β”‚   β”œβ”€β”€ router.py  # Auth API routes
β”‚   β”‚   β”‚   └── services.py # Auth business logic
β”‚   β”‚   β”œβ”€β”€ librarian/     # Librarian endpoints
β”‚   β”‚   β”‚   β”œβ”€β”€ router.py  # Librarian API routes
β”‚   β”‚   β”‚   └── services.py # Librarian business logic
β”‚   β”‚   └── member/        # Member endpoints
β”‚   β”‚       β”œβ”€β”€ router.py  # Member API routes
β”‚   β”‚       └── services.py # Member business logic
β”‚   β”œβ”€β”€ schema/            # Pydantic models
β”‚   β”‚   β”œβ”€β”€ book.py        # Book schemas
β”‚   β”‚   β”œβ”€β”€ loan.py        # Loan schemas
β”‚   β”‚   └── user.py        # User schemas
β”‚   └── utils/             # Utility functions
β”‚       β”œβ”€β”€ days_left.py   # Date calculations
β”‚       β”œβ”€β”€ hasher.py      # Password hashing
β”‚       └── object_id.py   # Object ID utilities
β”œβ”€β”€ tests/                 # Test suite
β”‚   β”œβ”€β”€ __init__.py        # Package initialization
β”‚   β”œβ”€β”€ conftest.py        # Pytest configuration and fixtures
β”‚   β”œβ”€β”€ test_admin.py      # Admin functionality tests
β”‚   β”œβ”€β”€ test_analytics.py  # Analytics endpoint tests
β”‚   β”œβ”€β”€ test_auth.py       # Authentication tests
β”‚   β”œβ”€β”€ test_experimental.py # Experimental tests
β”‚   β”œβ”€β”€ test_librarian.py  # Librarian functionality tests
β”‚   └── test_member.py     # Member functionality tests
β”œβ”€β”€ main.py                # Application entry point
β”œβ”€β”€ requirements.txt       # Python dependencies
β”œβ”€β”€ pytest.ini            # Pytest configuration
β”œβ”€β”€ Dockerfile             # Docker image configuration
β”œβ”€β”€ docker-compose.yml     # Docker Compose configuration
β”œβ”€β”€ logo.png               # University logo
└── README.md              # This file

πŸ‘₯ User Roles & Permissions

πŸ”΅ Member

  • Search for books
  • Request book loans
  • View personal loan history
  • Request loan renewal
  • Request book return

🟒 Librarian

  • All Member permissions, plus:
  • View and manage all loan requests
  • Approve/reject loan requests
  • Approve/reject return and renewal requests
  • Add new books to the library
  • Edit existing book information
  • Delete books from the system

πŸ”΄ Admin

  • All Librarian permissions, plus:
  • Register new users
  • Delete or disable user accounts
  • Access analytics dashboard

πŸš€ Getting Started

Prerequisites

  • Python 3.9 or higher
  • MongoDB (or use Docker Compose)
  • Docker & Docker Compose (optional, for containerized setup)

Installation

Option 1: Local Development Setup

  1. Clone the repository

    git clone <repository-url>
    cd university-basic-programming-python
  2. Create a virtual environment

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
  3. Install dependencies

    pip install -r requirements.txt
  4. Set up environment variables

    Create a .env file in the root directory:

    MONGO_HOST=localhost
    MONGO_PORT=27017
    MONGO_DB=appdb
    MONGO_USER=admin
    MONGO_PASSWORD=adminpassword
    MONGO_AUTH_DB=admin
    JWT_SECRET=your-secret-key-change-in-production
  5. Start MongoDB

    Make sure MongoDB is running on your system, or use Docker Compose:

    docker-compose up -d mongo
  6. Seed the database (optional)

    python -m app.db.seed
  7. Run the application

    uvicorn main:app --reload

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

Option 2: Docker Setup (Recommended)

  1. Clone the repository

    git clone <repository-url>
    cd university-basic-programming-python
  2. Create .env file (same as above)

  3. Start services with Docker Compose

    docker-compose up -d

    This will start both MongoDB and the application.


πŸ“– API Documentation

Once the application is running, you can access:

  • Interactive API Docs (Swagger UI): http://localhost:8000/docs
  • Alternative API Docs (ReDoc): http://localhost:8000/redoc
  • OpenAPI Schema: http://localhost:8000/openapi.json

API Endpoints Overview

Authentication (/auth)

  • POST /auth/login - User login
  • POST /auth/register - Register new user (Admin only)

Member (/member)

  • GET /member/s/{query} - Search books
  • GET /member/loan - Get personal loan list
  • POST /member/loan - Request a book loan
  • POST /member/loan/{loan_id}/return - Request book return

Librarian (/librarian)

  • GET /librarian/loan - View all loan requests
  • PUT /librarian/loan/{id}/accept - Approve loan request
  • PUT /librarian/loan/{id}/reject - Reject loan request
  • PUT /librarian/loan/{id}/returned - Confirm book return
  • POST /librarian/book - Add new book
  • PUT /librarian/book/{id} - Update book information
  • DELETE /librarian/book/{id} - Delete book

Admin (/admin)

  • POST /admin/user - Register new user
  • DELETE /admin/user/{username} - Delete user
  • PUT /admin/user/{username}/disable - Disable user account
  • PUT /admin/user/{username}/enable - Enable user account

Analytics (/analytics)

  • GET /analytics/popular-books - Get most popular books
  • GET /analytics/reliable-users - Get most reliable users
  • GET /analytics/overdue-books - Get overdue books list

πŸ” Authentication

The API uses JWT (JSON Web Tokens) for authentication. To access protected endpoints:

  1. Login to get an access token:

    curl -X POST "http://localhost:8000/auth/login" \
      -H "Content-Type: application/json" \
      -d '{"username": "member", "password": "123"}'
  2. Use the token in subsequent requests:

    curl -X GET "http://localhost:8000/member/loan" \
      -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Default Test Users

After seeding the database, you can use these test accounts:

  • Admin: username: amir, password: 123
  • Librarian: username: librarian, password: 123
  • Member: username: member, password: 123

πŸ“Š Data Models

User

{
    "username": "string",
    "password": "string (hashed)",
    "full_name": "string",
    "role": "admin | librarian | member",
    "score": "integer (default: 0)",
    "disabled_at": "datetime | null"
}

Book

{
    "title": "string",
    "author": "string",
    "category": "string",
    "total_count": "integer",
    "aviable_count": "integer"
}

Loan

{
    "username": "string",
    "book_title": "string",
    "date": "datetime",
    "status": "pending | approved | returned_awaiting | returned | renew_pending | rejected",
    "returned_date": "datetime | null"
}

✨ Bonus Features Implemented

This project goes beyond the basic requirements and includes several advanced features:

🎯 1. NoSQL Database (MongoDB)

  • Modern document-based database instead of file-based storage
  • Efficient querying and data relationships
  • Scalable architecture

πŸ”’ 2. Password Encryption

  • bcrypt hashing for secure password storage
  • Industry-standard security practices
  • No plain-text passwords in database

🐳 3. Docker Containerization

  • Complete Docker setup with Dockerfile and docker-compose.yml
  • Easy deployment across different environments
  • Isolated development and production environments

πŸ“ˆ 4. Analytics System

  • Popular Books: Track most borrowed books
  • Reliable Users: Identify users with good borrowing history
  • Overdue Books: Monitor books that are past due date

🌐 5. RESTful API (FastAPI)

  • Modern API design instead of CLI interface
  • Automatic API documentation
  • Type validation with Pydantic
  • Async/await support for better performance

πŸ“ 6. Version Control (Git)

  • Proper Git repository structure
  • Organized commit history
  • Ready for GitHub deployment

πŸ§ͺ Testing the API

Using cURL

Login as Member:

curl -X POST "http://localhost:8000/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username": "member", "password": "123"}'

Search for Books:

curl -X GET "http://localhost:8000/member/s/clean" \
  -H "Authorization: Bearer YOUR_TOKEN"

Request a Loan:

curl -X POST "http://localhost:8000/member/loan" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"book_id": "BOOK_ID", "date": "2024-01-15T10:00:00Z"}'

Using the Interactive Docs

The easiest way to test the API is through the Swagger UI at http://localhost:8000/docs. You can:

  • View all available endpoints
  • See request/response schemas
  • Test endpoints directly from the browser
  • Authenticate using the "Authorize" button

πŸ› οΈ Development

Code Quality

The project follows Python best practices:

  • Modular Design: Separated concerns with routers, services, and schemas
  • Type Hints: Full type annotations for better code clarity
  • Pydantic Models: Data validation and serialization
  • Clean Architecture: Separation of business logic and API routes

Key Design Patterns

  • Domain Driven Design (DDD): Architecture organized around business domains with clear bounded contexts
  • Dependency Injection: FastAPI's dependency system for authentication
  • Repository Pattern: Database operations abstracted in service layer
  • Schema Validation: Pydantic models for request/response validation

πŸ§ͺ Testing

This project includes comprehensive test coverage using Pytest and GitHub Actions CI/CD.

Running Tests Locally

  1. Install test dependencies (if not already installed):

    pip install -r requirements.txt
  2. Ensure MongoDB is running:

    docker-compose up -d mongo
  3. Set environment variables for testing:

    export MONGO_URI="mongodb://localhost:27017"
    export JWT_SECRET="test_secret_key"
  4. Run all tests:

    pytest tests/ -v
  5. Run specific test file:

    pytest tests/test_auth.py -v
  6. Run with coverage:

    pip install pytest-cov
    pytest tests/ --cov=app --cov-report=html

Test Structure

The test suite is organized by domain:

  • tests/test_auth.py - Authentication and authorization tests
  • tests/test_member.py - Member role functionality tests
  • tests/test_librarian.py - Librarian role functionality tests
  • tests/test_admin.py - Admin role functionality tests
  • tests/test_analytics.py - Analytics endpoint tests
  • tests/conftest.py - Shared fixtures and test configuration

Continuous Integration

The project uses GitHub Actions for automated testing:

  • Workflow: .github/workflows/ci.yml
  • Triggers: Runs on push and pull requests to main/master/develop branches
  • Services: Automatically sets up MongoDB service container
  • Test Execution: Runs full test suite with coverage reporting
  • Status Badge: View test status directly in repository

The CI pipeline:

  1. Sets up Python 3.9 environment
  2. Installs dependencies
  3. Starts MongoDB service container
  4. Runs all tests with pytest
  5. Generates coverage reports
  6. Uploads coverage to Codecov (optional)

Test Coverage

The test suite covers:

  • βœ… Authentication and JWT token validation
  • βœ… Role-based access control
  • βœ… Book management operations
  • βœ… Loan request and approval workflows
  • βœ… User management (admin functions)
  • βœ… Analytics endpoints
  • βœ… Error handling and edge cases

πŸ“ Project Requirements Checklist

Core Requirements βœ…

  • User management with three roles (Admin, Librarian, Member)
  • Book management (add, edit, delete, search)
  • Loan system (request, approve, renew, return)
  • Status tracking for loans
  • Data persistence (MongoDB)
  • Authentication and authorization

Bonus Features βœ…

  • NoSQL Database (MongoDB)
  • Password Encryption (bcrypt)
  • Docker Containerization
  • Analytics System
  • RESTful API (FastAPI)
  • Version Control (Git)
  • Testing with Pytest
  • CI/CD with GitHub Actions

πŸ“„ License

This project is developed as part of a university course assignment. All rights reserved.

πŸ™ Acknowledgments

  • University of Tehran for the project
  • FastAPI community for excellent documentation
  • MongoDB for the robust database solution

Note: This project was developed as a learning exercise. For production use, additional security measures, error handling, and testing would be recommended.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published