Skip to content

yusufziyrek/blogApp-RestAPI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

73 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

BlogApp-RestAPI Documentation

Overview:
BlogApp-RestAPI is a RESTful API that enables users to interact with blog posts, comments, and likes. It provides comprehensive CRUD operations for users, posts, comments, and likes, offering a fully-featured blog experience with secure authentication, role-based authorization, email verification, and caching for enhanced performance.


1. Features:

  • User Management:
    User registration, update, delete, and listing.
  • Post Management:
    Create, read, update, and delete blog posts.
  • Comments & Likes:
    Users can comment on and like posts.
  • JWT Authentication & Refresh Token Security:
    Secured endpoints with JWT-based authentication, refresh token rotation, device tracking, and role-based access control.
  • Advanced Token Management:
    Persistent refresh tokens with automatic cleanup, session limits, and secure logout functionality.
  • Email Verification:
    New users must verify their email addresses to activate their accounts. A verification link is sent upon registration.
  • Caching with Caffeine:
    Frequently accessed data (such as blog posts and comments) is cached using Caffeine Cache, reducing database load and improving response times.

2. Tech Stack:

  • Java 21 & Spring Boot:
    API development, dependency injection, and MVC architecture.
  • Spring Data JPA:
    Simplifies database interactions.
  • Maven:
    Project management and dependency tool.
  • Spring Security & JWT:
    Provides secure authentication and authorization.
  • Caffeine Cache:
    High-performance caching library integrated to cache frequently accessed endpoints.

Logging (SLF4J)

  • The project uses SLF4J with Logback (provided by Spring Boot) for application-wide logging. Many service classes include Lombok's @Slf4j annotation.
  • Adjust log levels in application.properties. Minimal examples:
    • logging.level.root=INFO
    • logging.level.com.yusufziyrek=DEBUG

Architecture

The project follows Clean Architecture in a Modular Monolith setup:

  • Domain-centric modules: auth/, user/, post/, comment/, like/ (+ shared/ for cross-cutting concerns)
  • Layers per module:
    • domain/ → Entities and domain logic
    • application/
      • usecases/ → Orchestrates business rules per action
      • ports/ → Interfaces (e.g., repositories) consumed by use cases
    • infrastructure/
      • web/ → REST controllers (adapters)
      • persistence/ → JPA adapters (port implementations)
      • config/ → Module wiring
  • Request flow: Controller → UseCase → Port → Adapter (JPA) → DB
  • CQRS-lite: Read/Write use cases are separated where meaningful

Cross-cutting concerns live under shared/ (Security/JWT, CORS/Cache config, exceptions, common DTOs).


3. Database Structure:

  • Users:
    Stores user details (ID, username, department, email, role, etc.).
  • Posts:
    Stores post details (ID, title, content, commentCount, likeCount, timestamps, etc.).
  • Comments:
    Stores comments related to posts (ID, userId, postId, likeCount, timestamps, etc.).
  • Likes:
    Stores likes on posts and comments (ID, userId, postId, commentId, timestamps, etc.).
  • JWT Tokens:
    Used for authentication and authorization.
  • Email Verification Tokens:
    Stores tokens used for verifying user email addresses.

4. API Endpoints:

Authentication & Security:

  • POST /api/v1/auth/register:
    Register a new user and immediately authenticate (returns access + refresh token).
  • POST /api/v1/auth/login:
    Authenticate with email or username + password (returns access + refresh token).
  • POST /api/v1/auth/refresh:
    Issue a new access token using a valid (non‑revoked) refresh token.

User Management:

  • GET /api/v1/users (ADMIN):
    Paginated list of users.
  • GET /api/v1/users/me:
    Current authenticated user profile.
  • PUT /api/v1/users/me:
    Update own profile data.
  • GET /api/v1/users/{id} (ADMIN or owner):
    Fetch user by ID.
  • PUT /api/v1/users/{id} (ADMIN or owner):
    Update user by ID.

Post Management:

  • GET /api/v1/posts:
    Paginated list of posts.
  • GET /api/v1/posts/me:
    Posts created by the authenticated user.
  • GET /api/v1/posts/{id}:
    Post details.
  • POST /api/v1/posts:
    Create a post (auth required).
  • PUT /api/v1/posts/{id}:
    Update a post (owner only).
  • DELETE /api/v1/posts/{id}:
    Delete a post (owner only).

Nested Comments (per Post):

  • GET /api/v1/posts/{postId}/comments:
    Paginated comments for a post.
  • POST /api/v1/posts/{postId}/comments:
    Add comment to post (auth required).

Individual Comment Management:

  • GET /api/v1/comments/{id}:
    Comment details.
  • PUT /api/v1/comments/{id}:
    Update comment (owner only).
  • DELETE /api/v1/comments/{id}:
    Delete comment (owner only).

Post Likes (Nested):

  • POST /api/v1/posts/{postId}/likes:
    Like a post (auth required).
  • DELETE /api/v1/posts/{postId}/likes:
    Unlike a post (auth required).
  • GET /api/v1/posts/{postId}/likes:
    Paginated likes for a post.
  • GET /api/v1/posts/{postId}/likes/count:
    Total like count for a post.

Comment Likes (Nested):

  • POST /api/v1/comments/{commentId}/likes:
    Like a comment (auth required).
  • DELETE /api/v1/comments/{commentId}/likes:
    Unlike a comment (auth required).
  • GET /api/v1/comments/{commentId}/likes:
    Paginated likes for a comment.

Applied REST Conventions:

Nested Resources (comments & likes under posts / comments)
Ownership Enforcement (update/delete restricted)
Stateless Auth (JWT in Authorization header)
Consistent Plural Nouns & Hierarchical URLs


5. JWT Authentication & Refresh Token Security

  • JWT-Based Authentication:
    Each request to a protected endpoint requires a valid JWT token. Users receive both access and refresh tokens upon successful login/registration:

    Authorization: Bearer <ACCESS_TOKEN>
  • Refresh Token Mechanism:

    • Persistent Storage: Refresh tokens are stored in database with expiration tracking
    • Device Tracking: Each refresh token includes device info and IP address for security
    • Token Rotation: New refresh token generated on each refresh request
    • Automatic Cleanup: Expired tokens are automatically cleaned up via scheduled tasks
    • Session Limits: Maximum 5 active refresh tokens per user (configurable)
  • Security Features:

    • Token Revocation: Logout revokes refresh tokens immediately
    • Role-Based Access: Spring Security integration with method-level permissions
    • Expiration Handling: Separate expiration times for access (1h) and refresh tokens (30 days)
    • Device Management: Track and limit active sessions per user
  • Email Verification Flow:

    1. User Registration: User registers via POST /api/v1/auth/register.
    2. Verification Link: An email is sent with a verification link.
    3. Account Activation: User activates their account by visiting GET /api/v1/auth/verify?token=<TOKEN>.
    4. Authentication: Once verified, the user can log in and receive a JWT token.

6. Caching with Caffeine Cache

To improve performance and reduce database load, BlogApp-RestAPI integrates Caffeine Cache:

  • Purpose:
    Frequently accessed data—such as blog posts, comments, and likes—is cached to speed up read operations.
  • Usage:
    Caching is applied on service methods (typically on GET operations) to store the results for a specified duration. Cache invalidation is triggered on data modifications (POST, PUT, DELETE) to prevent stale data.
  • Benefits:
    • Reduced Database Load: Minimizes repetitive database queries for frequently requested data.
    • Faster Response Times: Delivers cached results quickly, enhancing overall application performance.
    • Scalability: Supports high traffic by reducing expensive database operations.

7. Project Setup & Execution

  1. Clone the Repository:
    git clone https://github.com/yusufziyrek/blogApp-RestAPI.git
  2. Navigate to the Project Directory:
    cd blogApp-RestAPI
  3. Run the Application Using Maven:
    mvn spring-boot:run
  4. Configure JWT, Email, and Cache Settings:
    In your application.properties, set up the following:
    # JWT Configuration
    jwt.secret-key=YourSecureSecretKey
    jwt.expiration-time=3600000  # Access token: 1 hour
    jwt.refresh-token.expiration-ms=86400000  # Refresh token: 24 hours
    
    # Refresh Token Settings
    jwt.refresh.max-tokens-per-user=5  # Max active sessions per user
    jwt.refresh.cleanup.enabled=true  # Auto cleanup expired tokens
    
    # Email Configuration (using Gmail SMTP with TLS)
    spring.mail.host=smtp.gmail.com
    spring.mail.port=587
    spring.mail.username[email protected]
    spring.mail.password=your_app_password
    spring.mail.properties.mail.smtp.auth=true
    spring.mail.properties.mail.smtp.starttls.enable=true
    spring.mail.properties.mail.smtp.starttls.required=true
  5. Test Endpoints:
    • Authentication:
      # Register new user
      curl -X POST http://localhost:8080/api/v1/auth/register \
           -H "Content-Type: application/json" \
           -d '{"firstname":"John","lastname":"Doe","username":"johndoe","email":"[email protected]","password":"password123","department":"IT","age":25}'
      
      # Login
      curl -X POST http://localhost:8080/api/v1/auth/login \
           -H "Content-Type: application/json" \
           -d '{"email":"[email protected]","password":"password123"}'
      
      # Refresh token
      curl -X POST http://localhost:8080/api/v1/auth/refresh \
           -H "Content-Type: application/json" \
           -d '{"refreshToken":"your_refresh_token_here"}'
      
      # Logout
      curl -X POST http://localhost:8080/api/v1/auth/logout \
           -H "Content-Type: application/json" \
           -d '{"refreshToken":"your_refresh_token_here"}'
    • Email Verification:
      Check your inbox for a verification link and open it in a browser (e.g., GET /auth/verify?token=<TOKEN>).
  6. Database Configuration:
    Update the relevant properties in application.properties (or application.yml) to point to your preferred database (MySQL, PostgreSQL, etc.).

8. Future Improvements:

  • OAuth2 Support: Enable social login via Google and GitHub.
  • 2FA (Two-Factor Authentication): Enhance security with OTP-based login.
  • Device Management: Web interface for users to manage their active sessions.
  • Advanced Token Analytics: Track token usage patterns and suspicious activities.
  • Admin Panel: Provide a web interface for managing users, posts, and comments.
  • Advanced Cache Strategies: Explore more sophisticated caching strategies and cache eviction policies as the project scales.

For more information, check the GitHub repository.


Preview

  • Auth operations

    image
    image
    image
    image
    image

  • Post operations

    image
    image

  • Comment operations

    image

  • Like operations

    image
    image


Exceptions

image
image
image
image


Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

Author

Acknowledgments

  • Spring Boot team for the excellent framework
  • Open source community for the tools and libraries used in this project

Java Spring Boot Build Status

Releases

No releases published

Packages

No packages published

Languages