镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

# 📓 Journal App - Multi-User RESTful API with Spring Boot & MongoDB Welcome to the **Journal App**! This is a professional-grade, multi-user journaling platform built with **Spring Boot 3 **, **MongoDB**, and **Spring Security**. This document serves as a comprehensive guide to understanding the project architecture, the logic behind the code, and how to use or extend the API. --- ## 🏗️ 1. Architecture & Core Layers (The "What & Why") This project follows the standard **N-Tier Architecture**, which separates concerns so that the code is easier to maintain and test. 1. **Entity Layer (`com.yush.journalApp.entity`)**: - Defines our data models (`User`, `JournalEntry`). - These classes map directly to MongoDB collections. 2. **Repository Layer (`com.yush.journalApp.repository`)**: - Interfaces that extend `MongoRepository`. - This provides out-of-the-box CRUD operations (Create, Read, Update, Delete) without writing complex MongoDB queries. 3. **Service Layer (`com.yush.journalApp.service`)**: - **The Brain**: This is where business logic lives. - Example: `JournalEntryService` handles the `@Transactional` logic, ensuring that when an entry is saved, it is also linked to a User, or both operations fail (Atomicity). 4. **Controller Layer (`com.yush.journalApp.controller`)**: - **The Gateway**: Handles incoming HTTP requests and returns HTTP responses. - Uses `ResponseEntity` to provide meaningful status codes (e.g., `201 Created`, `404 Not Found`). --- ## 🔐 2. Security & Authentication (JWT Deep Dive) We use **Stateless Authentication** with **JSON Web Tokens (JWT)**. ### **How it works:** 1. **Login**: User sends credentials to `/public/login`. 2. **Token Generation**: `JwtUtil` generates a signed token containing the `username`. 3. **Storage**: The client (Frontend) saves this token (usually in `localStorage`). 4. **Authorization**: For every subsequent request to `/journal/**`, the client sends the token in the `Authorization` header: `Bearer `. 5. **Validation**: `JwtFilter` intercepts the request, extracts the token, validates it with `JwtUtil`, and sets the user in Spring's Security Context. > **Why Stateless?** The server doesn't need to remember who is logged in (no Sessions). The token itself carries the identity, making the app scalable. --- ## 💾 3. Database & Transactions We use **MongoDB** as our primary database. - **Transactions**: In `JournalEntryService`, we use `@Transactional`. This ensures that if saving a journal entry succeeds but updating the user's entry list fails, the whole operation rolls back. - **Note**: To use Transactions in MongoDB, you must be using a **Replica Set** (common in MongoDB Atlas). --- ## 📋 4. API Endpoints Reference ### **Public Endpoints (No Auth Required)** | Method | Endpoint | Description | | :--- | :--- | :--- | | `POST` | `/public/signup` | Create a new account. | | `POST` | `/public/login` | Log in and receive a JWT token. | ### **Journal Endpoints (Requires JWT)** | Method | Endpoint | Description | | :--- | :--- | :--- | | `GET` | `/journal` | Get all entries for the logged-in user. | | `POST` | `/journal` | Create a new entry for the logged-in user. | | `GET` | `/journal/id/{id}` | Get a specific entry by ID. | | `PUT` | `/journal/id/{id}` | Update an entry by ID. | | `DELETE` | `/journal/id/{id}` | Delete an entry by ID. | ### **User Endpoints (Requires JWT)** | Method | Endpoint | Description | | :--- | :--- | :--- | | `PUT` | `/user` | Update the logged-in user's profile (Username/Password). | | `DELETE` | `/user` | Delete the logged-in user's account. | --- ## 🛠️ 5. Setup & Running Locally ### **1. Prerequisites** - **JDK 17** or higher (LTS). - **MongoDB** (Local or Atlas). ### **2. Configuration** Create `src/main/resources/application.properties`: ```properties # DB Config spring.data.mongodb.uri=mongodb://localhost:27017/journaldb spring.data.mongodb.database=journaldb # JWT Secret (Keep this safe!) # Generate a long random string jwt.secret=TaK+pBTHuSGAu9SjgD7aHwj66asf7as89d7as9d87as9d87as9d8d server.port=8080 ``` ### **3. Commands** ```bash # Build & Run 🚀 ./mvnw spring-boot:run # Access Swagger UI (API Docs) 📘 http://localhost:8080/swagger-ui.html ``` --- ## 🌐 6. Connecting to a Frontend (React/Angular/Vue) To connect this API to your frontend, follow these steps: ### **Example: Login Request (JS)** ```javascript const login = async (username, password) => { const response = await fetch('http://localhost:8080/public/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }); const token = await response.text(); // The API returns the JWT as a string localStorage.setItem('token', token); // Store it! }; ``` ### **Example: Authenticated Request (JS)** ```javascript const getJournals = async () => { const token = localStorage.getItem('token'); const response = await fetch('http://localhost:8080/journal', { headers: { 'Authorization': `Bearer ${token}` // Send the token! } }); const data = await response.json(); return data; }; ``` --- ## ✅ 7. Key Features Implemented - **Global Error Handling**: Any crash in the app returns a clean JSON error via `@ControllerAdvice`. - **Bean Validation**: Inputs like `userName` are validated before being saved to the DB. - **Role-Based Access**: Admins can see all users, while regular users can only manage their own data. --- *Developed by Ayush - Building secure and scalable Java applications..*

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages