Skip to content

yakov152005/social-network-server

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

82 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🌐 Social Network - Server Side

🎯 Production Version
Click here to access the live production version

πŸ–₯️ Client Repository
Click here to go client side


🧠 Backend Architecture

The backend of Social Network is developed using Java & Spring Boot, offering a secure, scalable, and optimized REST API.

The architecture follows a layered and object-oriented design (OOP), ensuring clear separation of concerns and maintainable code.
πŸ“Œ Entities β†’ Repositories β†’ Services β†’ Controllers β†’ DTOs β†’ Responses

This backend leverages both OOP principles and declarative programming paradigms, using Java Streams, annotations (e.g., @Service,@Compoment,@Get/Post/RequestBody-Mapping,@Caching,@Bean,@Configuration, @Transactional, @Scheduled, @RestController, @andmore), and functional-style programming to write clean, reusable, and readable code.

This backend provides authentication, caching, real-time updates, email & SMS verification, and scheduled jobs for maintenance.
It is fully Dockerized and deployed with CI/CD using GitHub Actions and Render.


πŸ— Tech Stack

πŸ›  Backend Framework: Spring Boot, Java
πŸ”’ Security: Spring Security, JWT (JSON Web Tokens), Password Hashing (SHA-256 + Salt)
πŸ“‘ Real-Time Updates: SSE (Server-Sent Events)
πŸ“¦ Database: MySQL (optimized queries & indexes using JPA)
πŸ“¨ Email & SMS Verification: Twilio, Mailgun & Custom api
πŸ“Έ Cloud Storage: Cloudinary for media uploads
⚑ Caching: Spring Boot Caching for optimized performance
πŸ—„ Scheduled Jobs: CRON Job (session tracking, expired token cleanup, remove stories after 24 hours ago, sends an email to users who have not logged in for over a month)
πŸ“‹ Environment Configuration: Dotenv for local & AppConfig managing variables for production.
🐳 Containerization & Deployment: Docker + Render + GitHub Actions (CI/CD)


πŸ”„ System Flow

1️⃣ Frontend to Backend Communication

  • The client (React) sends requests using Axios to RESTful API endpoints.
  • Backend controllers handle the request, then delegate to services.
  • Services process the business logic and interact with repositories.
  • Repositories execute JPA queries on the MySQL database.
  • Caching optimizes responses, and SSE provides real-time updates.
  • All operations are containerized in Docker for scalable deployment.

2️⃣ Authentication & Security

  • User Registration:

    • Strong password validation & uniqueness check (email/phone).
    • If valid, an email is sent with account details.
    • Password is hashed & salted (SHA-256) before storage.
  • Login Process:

    • User enters credentials β†’ JWT is generated.
    • 2FA SMS verification is sent to the phone.
    • On success, session starts & user gains access.
  • Password Reset:

    • User requests reset β†’ Receives email with a unique token.
    • User enters token & new password β†’ New hashed & salted password is saved.
    • Confirmation email is sent.

3️⃣ Data Storage & Optimization

  • MySQL database with efficient JPA queries and indexes.
  • User content (posts, comments, media) stored with Cloudinary integration.
  • Spring Boot Caching improves response times and reduces redundant queries.

4️⃣ Real-Time Notifications & Messaging

  • SSE (Server-Sent Events) used for real-time notifications/messages/comments/stories/online friends.
  • Users get instant alerts for likes, follows, and comments.

5️⃣ Automated Jobs & Expiration Handling

  • CRON Jobs run monthly to check for inactive users & send reminders.
  • CRON Jobs run 24 hours ago to remove stories after 24 hours ago.
  • Token expiration handling ensures security by removing stale sessions.

6️⃣ Deployment & Scaling

  • Dockerized environment ensures consistency across deployments.
  • CI/CD pipeline (GitHub Actions) automates deployment to Render.
  • Environment variables managed securely with AppConfig and .env files.

πŸ“‚ Project Structure

Social-Network-Server/
β”œβ”€β”€ πŸ“‚ .github
β”‚     β”œβ”€β”€ workflow
β”‚         β”œβ”€β”€ deploy.yml # CI/CD GitHub Actions for auto-deployment
β”œβ”€β”€ πŸ“‚ src/main/java/org.server.socialnetworkserver
β”‚    β”œβ”€β”€ πŸ“‚ config          # Security, JWT, Caching & Environment Management
β”‚    β”œβ”€β”€ πŸ“‚ controllers     # API endpoints for handling requests
β”‚    β”œβ”€β”€ πŸ“‚ dtos            # Data transfer objects for request/response
β”‚    β”œβ”€β”€ πŸ“‚ entities        # Database entities (User, Post, Comment, etc.)
β”‚    β”œβ”€β”€ πŸ“‚ jobs            # Scheduled tasks (CronJobs)
β”‚    β”œβ”€β”€ πŸ“‚ repositories    # JPA repositories for database interaction
β”‚    β”œβ”€β”€ πŸ“‚ responses       # Custom API responses
β”‚    β”œβ”€β”€ πŸ“‚ services        # Business logic layer
β”‚    β”œβ”€β”€ πŸ“‚ test            # Unit & integration tests
β”‚    β”œβ”€β”€ πŸ“‚ utils           # Helper functions, JWT token & password generators & utilities & Api sms/email/gpt
β”‚    └── SocialNetworkServerApplication  # Main application with enabled annotations  
β”œβ”€β”€ πŸ“‚ resources             # Application properties settings  
β”‚    
β”œβ”€β”€ Dockerfile              # Docker container setup  
β”œβ”€β”€ .env                    # Environment variable template for local use  
β”œβ”€β”€ pom.xml                 # Mvn dependencies
└── README.md               # Project documentation  

Entity-Relationship Diagram (ERD)

ERD


πŸ”„ Installation & Setup

# Clone repository
git clone https://github.com/your-repo/social-network-server.git
cd social-network-server

# Build and run with Maven
mvn clean install
mvn spring-boot:run

#DotEnv Example
DB_URL_LOCAL=yourLocalDb
DB_HOST_LOCAL=yourHost
DB_USERNAME_LOCAL=yourUsername
DB_PASSWORD_LOCAL=yourPassword
DB_NAME_LOCAL=yourDBname
SMS_TOKEN=You Need SMS Token or Cancel it
SENDER_EMAIL=yourMail
SENDER_PASSWORD=yourPassAppMail
URL_CLIENT_PC=http://localhost:3000
URL_TEST=http://localhost:8080/social-network/slow-endpoint

# Running with Docker
docker build -t social-network-server .
docker run -p 8080:8080 social-network-server

πŸ“‘ API Communication

User Registration (Secure)

@PostMapping("/add-user")
public ValidationResponse addUser(@RequestBody User user) {
    return userService.addUser(user);
}

Login with 2FA SMS Verification

 @PostMapping("/login-user")
public LoginResponse loginUser(@RequestBody Map<String, String> loginDetails) {
    return userService.loginUser(loginDetails);
}

@PostMapping("/verify-code")
public Map<String, String> verifyCode(@RequestBody Map<String, String> verificationDetails) {
    return userService.verifyCode(verificationDetails);
}

Password Reset Request

 @GetMapping("/reset-password/{email}&{username}")
public BasicResponse resetPasswordForThisUser(@PathVariable String email, @PathVariable String username) {
    return userService.resetPasswordForThisUser(email,username);
}

@PostMapping("/confirm-reset-password")
public BasicResponse confirmResetPassword(@RequestParam String token){
    return userService.confirmPasswordReset(token);
}

πŸ” Security Features

βœ… JWT Authentication with Expiration Handling
βœ… Two-Factor Authentication (2FA) via SMS
βœ… Password Hashing (SHA-256 + Salt)
βœ… Rate Limiting to Prevent Abuse
βœ… Spring Boot Caching for Optimized Performance
βœ… CORS & Helmet for API Security


πŸ“‘ Real-Time Features

πŸ“‘ SSE for Instant Updates

  • Notifications for likes, comments, follows, messages, online friends, stories.
  • Real-time updates without excessive polling.

πŸ“’ Automated Email & SMS Alerts

  • Registration confirmation via email.
  • Password reset email with unique token.

πŸ“… Automated Jobs (CRON Jobs)

πŸ•’ Runs once per month

  • Sends reminder emails to inactive users.

πŸ•’ Runs once per 24 hours

  • Checks for expired stories more than 24 hours have passed and removes them.

πŸ•’ Runs once per day

  • Checks for expired authentication tokens and removes them.

πŸ›  Deployment & CI/CD

πŸš€ Dockerized for scalable deployment
πŸ”„ CI/CD with GitHub Actions
🌍 Hosted on Render (auto-deployment on commit)


🀝 Contribute

Pull Requests welcome!

Built with ❀️ by a passionate full-stack dev – from backend logic to UI animations, everything is handcrafted for performance and beauty.


πŸ”— Explore

πŸš€ Enjoy the Social Network Experience! 🌍