Skip to content

Himanshu0508Raturi/iLibrary-Backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

27 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“š iLibrary Backend

Spring Boot MySQL Docker LinkedIn

A robust Spring Boot backend for a private study-library management system

Features β€’ Tech Stack β€’ Getting Started β€’ API Documentation β€’ Database Schema


πŸ“‹ Overview

iLibrary Backend is a comprehensive RESTful API service designed for managing private study libraries. It provides a complete solution for user management, subscription handling, seat booking with real-time availability tracking, QR-based authentication, and automated seat release mechanisms.

πŸ” Authentication & Authorization Flow

Authentication Architecture

The iLibrary Backend implements a multi-layered security architecture with JWT-based authentication, role-based access control, and QR code verification for physical check-ins.

sequenceDiagram
    participant User
    participant Frontend
    participant PublicController
    participant SecurityFilter
    participant JwtUtil
    participant Database
    participant EmailService

    Note over User,EmailService: πŸ”Ή User Registration Flow
    User->>Frontend: Fill signup form
    Frontend->>PublicController: POST /public/signup
    PublicController->>PublicController:  Validate input (@Valid)
    PublicController->>PublicController: Add ROLE_ prefix
    PublicController->>Database: Save user (BCrypt password)
    Database-->>PublicController: User saved
    PublicController->>EmailService: Send welcome email
    EmailService-->>User: Welcome email
    PublicController-->>Frontend: 201 Created
    Frontend-->>User: Registration successful

    Note over User,EmailService:  πŸ”Ή User Login Flow
    User->>Frontend: Enter credentials
    Frontend->>PublicController: POST /public/login
    PublicController->>PublicController: AuthenticationManager.authenticate()
    PublicController->>Database: Verify credentials (BCrypt)
    Database-->>PublicController: User authenticated
    PublicController->>JwtUtil: generateToken(username, roles)
    JwtUtil->>JwtUtil: Create JWT with HS256
    JwtUtil-->>PublicController: JWT Token (10 hours expiry)
    PublicController-->>Frontend: {token, roles:  ["ROLE_USER"]}
    Frontend-->>User: Login successful + Store JWT

    Note over User,EmailService:  πŸ”Ή Authenticated Request Flow
    User->>Frontend:  Book a seat
    Frontend->>SecurityFilter: GET /booking/seat<br/>Header: Bearer <JWT>
    SecurityFilter->>JwtUtil: extractUsername(token)
    JwtUtil-->>SecurityFilter: username
    SecurityFilter->>JwtUtil: isTokenValid(token)
    JwtUtil->>JwtUtil: Check expiration & signature
    JwtUtil-->>SecurityFilter: Valid βœ“
    SecurityFilter->>JwtUtil: extractRoles(token)
    JwtUtil-->>SecurityFilter: ["ROLE_USER"]
    SecurityFilter->>SecurityFilter: Create Authentication object
    SecurityFilter->>SecurityFilter: Set SecurityContext
    SecurityFilter->>PublicController: Forward request
    PublicController->>Database: Book seat
    Database-->>PublicController: Booking created
    PublicController->>EmailService: Send QR code email
    EmailService-->>User:  QR code with JWT token
    PublicController-->>Frontend:  Booking successful
    Frontend-->>User:  Confirmation displayed

    Note over User,EmailService: πŸ”Ή QR Code Verification Flow
    User->>Frontend: Show QR at library entrance
    Frontend->>PublicController: POST /librarian/verify-qr<br/>Body: {qrToken}
    PublicController->>JwtUtil: Parse QR JWT token
    JwtUtil-->>PublicController: {bookingId, seatNumber, status}
    PublicController->>Database: Update booking to CONFIRMED
    Database-->>PublicController: Booking confirmed
    PublicController->>EmailService: Send confirmation email
    EmailService-->>User: Booking confirmed email
    PublicController-->>Frontend:  Verification successful
    Frontend-->>User:  Entry granted βœ“
Loading

πŸ“Š Authentication State Diagram

stateDiagram-v2
    [*] --> Anonymous:  Application Start
    Anonymous --> Authenticated: POST /public/login<br/>(valid credentials)
    Anonymous --> Anonymous: POST /public/signup
    
    Authenticated --> BookingSeat: POST /booking/seat<br/>(with JWT)
    BookingSeat --> AwaitingQRScan: QR code sent via email
    
    AwaitingQRScan --> ConfirmedBooking: POST /librarian/verify-qr<br/>(valid QR JWT)
    AwaitingQRScan --> Cancelled: DELETE /booking/cancel
    
    ConfirmedBooking --> Active: User enters library
    Active --> [*]:  Booking time expires
    Cancelled --> Authenticated:  Seat released
    
    Authenticated --> [*]: Token expires (10 hours)
    Authenticated --> [*]: User logs out
Loading

✨ Features

πŸ” Authentication & Authorization

  • JWT-based Authentication - Secure token-based user authentication
  • Role-Based Access Control (RBAC) - Admin and User roles with different permissions
  • Spring Security Integration - Industry-standard security implementation

πŸ’Ί Seat Management

  • Real-time Seat Availability - Live tracking of seat status
  • Flexible Booking System - Book seats for specific durations
  • Automated Seat Release - Automatic release after booking expiry
  • QR Code Check-in - Quick and secure seat verification using QR codes

πŸ’³ Subscription Management

  • Multiple Plans - Weekly, Monthly, and Yearly subscription options
  • Stripe Payment Integration - Secure payment processing
  • Auto-renewal Support - Seamless subscription renewal
  • Subscription Status Tracking - Monitor active/inactive subscriptions

πŸ“§ Notifications

  • Email Integration - Automated email notifications using JavaMail
  • Booking Confirmations - Email receipts for seat bookings
  • Subscription Alerts - Renewal and expiry notifications

πŸ”§ Additional Features

  • Swagger UI Documentation - Interactive API documentation at /swagger-ui.html
  • Docker Support - Easy deployment using Docker and Docker Compose
  • Webhook Integration - Stripe webhooks for payment event handling
  • PDF Invoice Generation - Automated invoice creation using iText
  • Redis Caching - Performance optimization with Redis

πŸ›  Tech Stack

Core Technologies

  • Java 17 - Latest LTS version
  • Spring Boot 3.5.6 - Modern application framework
  • Spring Security - Authentication and authorization
  • Spring Data JPA - Database abstraction layer
  • Hibernate - ORM implementation

Database

  • MySQL 8.0 - Primary relational database
  • Redis - Caching layer for performance

Payment & Communication

  • Stripe API - Payment processing
  • JavaMail - Email service integration

Other Libraries

  • JWT (jjwt 0.11.5) - Token generation and validation
  • Lombok - Reduces boilerplate code
  • ZXing - QR code generation and scanning
  • iText 7 - PDF generation for invoices
  • SpringDoc OpenAPI - API documentation

DevOps

  • Docker - Containerization
  • Docker Compose - Multi-container orchestration
  • Maven - Build and dependency management

πŸš€ Getting Started

Prerequisites

  • Java 17 or higher
  • MySQL 8.0 or higher
  • Maven 3.6+
  • Docker & Docker Compose (optional)
  • Redis (optional, for caching)

Installation

Option 1: Local Setup

  1. Clone the repository
git clone https://github.com/Himanshu0508Raturi/iLibrary-Backend.git
cd iLibrary-Backend/iLibrary
  1. Configure the database

Create a MySQL database and update src/main/resources/application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/ilibrary_db
spring.datasource.username=your_username
spring.datasource. password=your_password
spring. jpa.hibernate.ddl-auto=update
  1. Configure environment variables

Set up the following environment variables or add them to application.properties:

# JWT Secret
jwt.secret=your-secret-key

# Email Configuration
spring.mail. host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-email@gmail.com
spring. mail.password=your-email-password

# Stripe Configuration
stripe.api.key=your-stripe-secret-key
stripe.webhook.secret=your-webhook-secret

# Redis Configuration (optional)
spring.redis.host=localhost
spring.redis.port=6379
  1. Build and run the application
./mvnw clean install
./mvnw spring-boot:run

The application will start at http://localhost:8080

Option 2: Docker Setup

  1. Clone the repository
git clone https://github.com/Himanshu0508Raturi/iLibrary-Backend.git
cd iLibrary-Backend/iLibrary
  1. Run with Docker Compose
docker-compose up -d

This will start:

  • Spring Boot application on port 8080
  • MySQL database on port 3306
  • Redis (if configured) on port 6379

πŸ“– API Documentation

Base URL

http://localhost:8080

Authentication

All protected endpoints require JWT Bearer token authorization.

Header Format:

Authorization: Bearer <your-jwt-token>

API Endpoints

πŸ“˜ Public APIs

Method Endpoint Description
POST /public/signup Register a new user
POST /public/login Authenticate and receive JWT token
GET /public/healthCheck Check API health status

🎫 Booking APIs

Method Endpoint Description
POST /booking/seat Book a seat for specific duration
DELETE /booking/cancel/{bookingId} Cancel an existing booking

πŸ’³ Subscription APIs

Method Endpoint Description
POST /subscription/buy Purchase a new subscription
PUT /subscription/renew Renew existing subscription
PUT /subscription/cancel Cancel active subscription
GET /subscription/status Check current subscription status

πŸ§‘β€πŸ’Ό Admin APIs

Method Endpoint Description
GET /admin/allUsers List all registered users
GET /admin/allSeats List all seats and their status
GET /admin/allBooking List all bookings
GET /admin/allSubscription List all subscriptions

πŸ’° Payment APIs

Method Endpoint Description
GET /payment/seat Initiate seat payment checkout
GET /payment/subscription Initiate subscription payment checkout

βš™οΈ Webhook APIs

Method Endpoint Description
POST /webhook/subscription Handle Stripe subscription webhooks
POST /webhook/seat Handle Stripe seat booking webhooks

πŸ“š Example API Usage

User Registration

curl -X POST http://localhost:8080/public/signup \
  -H "Content-Type: application/json" \
  -d '{
    "username": "john_doe",
    "password": "SecurePass123",
    "email": "john@example.com"
  }'

User Login

curl -X POST http://localhost:8080/public/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "john_doe",
    "password": "SecurePass123"
  }'

Response:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "type": "Bearer",
  "username": "john_doe",
  "roles": ["ROLE_USER"]
}

Book a Seat

curl -X POST http://localhost:8080/booking/seat \
  -H "Authorization: Bearer <your-jwt-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "seatNumber": "A12",
    "hours": 3
  }'

Check Subscription Status

curl -X GET http://localhost:8080/subscription/status \
  -H "Authorization: Bearer <your-jwt-token>"

πŸ—‚ Data Schemas

User Registration/Login

{
  "username": "string (required)",
  "password": "string (required, min 6 chars)",
  "email": "string (required, valid email format)"
}

Subscription Request

{
  "type": "WEEKLY | MONTHLY | YEARLY",
  "autoRenew": "boolean (optional)"
}

Seat Booking Request

{
  "seatNumber": "string (required)",
  "hours": "integer (required, min 1, max 12)"
}

πŸ—„ Database Schema

The application uses a relational database with the following main entities:

  • Users - User accounts and credentials
  • Roles - User roles (USER, ADMIN)
  • Subscriptions - User subscription plans
  • Seats - Available seats in the library
  • Bookings - Seat booking records
  • Payments - Payment transaction records

ER Diagram


πŸ§ͺ Interactive API Documentation

Once the application is running, access the interactive Swagger UI documentation:

http://localhost:8080/swagger-ui.html

This provides:

  • Complete API reference
  • Request/response examples
  • Try-it-out functionality
  • Schema definitions

πŸ”’ Security Features

  • Password Encryption - BCrypt hashing for secure password storage
  • JWT Token Expiration - Configurable token lifetime
  • CORS Configuration - Controlled cross-origin requests
  • Input Validation - Bean validation for all inputs
  • SQL Injection Protection - JPA/Hibernate parameterized queries
  • Rate Limiting - Protection against abuse (configurable)

🐳 Docker Deployment

Build Docker Image

docker build -t ilibrary-backend .

Run Container

docker run -p 8080:8080 \
  -e SPRING_DATASOURCE_URL=jdbc:mysql://host.docker.internal:3306/ilibrary_db \
  -e SPRING_DATASOURCE_USERNAME=root \
  -e SPRING_DATASOURCE_PASSWORD=password \
  ilibrary-backend

Docker Compose

docker-compose up -d

πŸ“ Configuration

Key configuration properties in application.properties:

# Server Configuration
server.port=8080

# Database Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/ilibrary_db
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

# JWT Configuration
jwt.secret=${JWT_SECRET}
jwt.expiration=86400000

# Email Configuration
spring.mail.host=smtp.gmail.com
spring.mail.port=587

# Stripe Configuration
stripe.api.key=${STRIPE_API_KEY}

# File Upload
spring.servlet.multipart.max-file-size=10MB

πŸ§ͺ Testing

Run the test suite:

./mvnw test

Run with coverage:

./mvnw test jacoco:report

🀝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“„ License

This project is open source and available for educational purposes.


πŸ‘¨β€πŸ’» Author

Himanshu Raturi

LinkedIn GitHub


πŸ™ Acknowledgments

  • Spring Boot community for excellent documentation
  • Stripe for payment integration
  • All contributors and supporters of this project

πŸ“ž Support

For support, email raturihimanshu077@gmail.com or create an issue in this repository.


**If you found this project helpful, please consider giving it a ⭐! **

About

A Spring Boot backend for a private study-library system with user authentication, role-based access, subscription management, seat booking, real-time availability, QR-based check-in, and automated seat release. Built with MySQL, JWT, and JavaMail, and ready for deployment on AWS.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors