An open API service indexing awesome lists of open source software.

https://github.com/stackthecode/messaging-app

Real Time messaging app with different features developed on Spring Boot (Cortex)
https://github.com/stackthecode/messaging-app

java jwt messaging spring-boot websocket

Last synced: 3 months ago
JSON representation

Real Time messaging app with different features developed on Spring Boot (Cortex)

Awesome Lists containing this project

README

          

# βš™οΈ The backend implements a real-time chat system using Spring Boot + WebSockets (STOMP) + REST APIs + JPA.
Messages can include text or files, support read/unread status, and are persisted in the database.

This is the **backend** for a real-time chat application.
It’s built with **Spring Boot** and provides secure APIs and WebSocket connections for instant communication. The backend takes care of authentication, message delivery, and storing chat history so the frontend (React + TailwindCSS) can focus on the user experience.

---

## ✨ What this backend does
- Handles **real-time messaging** through WebSockets with <200ms latency
- Provides **REST APIs** for authentication, user management, and sessions
- Uses **JWT tokens** for secure login and multi-device access
- Stores messages and sessions in a **PostgreSQL database**
- Scales to support thousands of concurrent users
- Works seamlessly with the React frontend (separate repo)

---

## πŸ›  Tech Stack
- **Spring Boot** (REST + WebSocket)
- **PostgreSQL** for persistence
- **JWT** for authentication
- **Maven** for dependency management
- **Docker** for containerization
- **Render / AWS** for deployment

---

## 1. Message Entity
Represents a chat message stored in the database.

Fields

- id β†’ Primary key (auto-generated).

- sender β†’ User who sends the message.

- recipient β†’ User who receives the message (nullable for public messages).

- content β†’ Text content of the message.

- fileName β†’ Optional file name if a file is attached.

- timestamp β†’ Time the message was sent.

- messageType β†’ Enum (TEXT, IMAGE, FILE, etc.).

- isRead β†’ Whether recipient has read the message.

---

## 2. MessageController
Provides both REST endpoints and WebSocket endpoints for chat.

| Method | Endpoint | Description |
| -------- | ------------------------------------------- | ----------------------------------------- |
| `GET` | `/api/messages/history/{userId}/{user2Id}` | Get chat history between two users. |
| `DELETE` | `/api/messages/history/{user1Id}/{user2Id}` | Clear chat history between two users. |
| `DELETE` | `/api/messages/{messageId}` | Delete a single message (only by sender). |

# WebSocket Endpoints

- /app/chat.send β†’ Send message (STOMP).

- /app/chat.typing β†’ Send typing indicator.

## WebSocket Subscriptions

/user/{userId}/queue/messages β†’ Private user queue for receiving messages.

/user/{userId}/queue/typing β†’ Private queue for typing status.

/topic/chat β†’ Public chat broadcast.

/topic/delete β†’ Notify clients when a message is deleted.

---

## 3. MessageService

Business logic for handling chat.

Key Methods:

- saveMessage(Message msg) β†’ Saves a new message to DB.

- deleteMessage(Long messageId, Long userId) β†’ Deletes a message if current user is sender.

- clearChatHistory(Long user1Id, Long user2Id) β†’ Deletes all messages between two users.

- userCanAccessMessage(Long messageId, Long userId) β†’ Verifies if user can access a message.

---

## 4. Messaging Flow
Sending a Message

User sends message via WebSocket β†’ /app/chat.send.

MessageController builds a Message object and persists it.

Saved message is mapped into a MessageDTO (with generated ID).

Message is delivered to:

Recipient’s private queue β†’ /user/{recipientId}/queue/messages.

Sender’s own queue β†’ /user/{senderId}/queue/messages.

.....................................................................................

Receiving Messages

Clients subscribe to /user/{id}/queue/messages to receive private messages.

Clients subscribe to /topic/chat for public messages.

.....................................................................................

Typing Indicator

Client sends typing status via /app/chat.typing.

Recipient receives it on /user/{recipientId}/queue/typing.

.....................................................................................

Deleting a Message

Sender issues DELETE : /api/messages/{messageId}.

MessageService verifies ownership.

If deleted β†’ backend broadcasts /topic/delete with {id: messageId} so UIs can remove it in real-time.

---

## 5. User Entity
Represents a chat message stored in the database.

Fields:

- id β†’ Primary key (auto-generated).

- username β†’ Unique username for login and display.

- email β†’ Unique email address.

- password β†’ Hashed password (nullable for OAuth users).

- role β†’ Role of the user (e.g., USER, ADMIN).

- googleId β†’ Optional field for Google OAuth authentication.

- createdAt β†’ Date when the user was registered.

- updatedAt β†’ Date of the last profile update.

---
## 5. User Controller

| Method | Endpoint | Description |
| -------- | --------------------------------------- | -------------------------------------------- |
| `GET` | `/api/users/{id}` | Get user by ID. |
| `GET` | `/api/users/username/{username}` | Get user by username. |
| `GET` | `/api/users/email/{email}` | Get user by email. |
| `GET` | `/api/users/search?username={username}` | Search users by username (case-insensitive). |
| `POST` | `/api/users/register` | Register a new user. |
| `POST` | `/api/users/oauth/google` | Register/Login user via Google OAuth. |
| `PUT` | `/api/users/{id}` | Update user details. |
| `DELETE` | `/api/users/{id}` | Delete user account. |

---
## 6. User Service

# Contains the business logic for user management.

Key Methods

- loadUserByUsername(String username) β†’ Loads a user for authentication (used by Spring Security).

- getUserIdByUsername(String username) β†’ Retrieves user ID by username.

- registerUser(User user) β†’ Registers a new user with validation.

- findByEmail(String email) β†’ Finds user by email.

- findByUsername(String username) β†’ Finds user by username.

- findByGoogleId(String googleId) β†’ Finds user registered via Google.

- updateUser(Long id, User user) β†’ Updates existing user details.

- deleteUser(Long id) β†’ Deletes a user account.

---

## πŸš€ Getting Started

Clone the repo and build the project:

```bash
git clone https://github.com/your-username/realtime-chat-backend.git
cd realtime-chat-backend
./mvnw clean install