diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..bbcbbe7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.gitignore b/.gitignore index 99a9653..b37e498 100644 --- a/.gitignore +++ b/.gitignore @@ -104,3 +104,13 @@ temp/ # Docker .dockerignore docker-compose.override.yml +# Test reports and coverage +coverage/ +*.lcov +surefire-reports/ +failsafe-reports/ + +# Local environment variants +.env.development +.env.test +.env.staging diff --git a/README.md b/README.md index 18719ee..75e43f2 100644 --- a/README.md +++ b/README.md @@ -1,288 +1,28 @@ -# GreenCode Backend +# GreenCode -A robust Java backend application built with Spring Boot for the GreenCode project - an innovative platform focused on sustainable development and environmental initiatives. +GreenCode is an API core system designed to support esm_greencode . +It consists of a **Spring Boot backend API** -## ๐ŸŽฏ Project Overview +--- -GreenCode is a comprehensive backend system designed to support environmental sustainability projects, green technology initiatives, and eco-friendly business operations. The platform provides robust APIs for managing environmental data, user authentication, and sustainable development metrics. +## ๐Ÿš€ Features -## ๐Ÿš€ Technology Stack +### Backend (Spring Boot) +- RESTful API +- JWT/OAuth authentication +- PostgreSQL database support +- Centralised configuration (`config/`, `.env`) +- Dockerized for easy deployment +- Swagger/OpenAPI documentation -- **Java 17** - Modern Java with latest features -- **Spring Boot 3.2.0** - Rapid application development framework -- **Spring Security** - Authentication and authorization -- **Spring Data JPA** - Data persistence layer -- **H2 Database** - In-memory database for development -- **PostgreSQL** - Production database support -- **Maven** - Dependency management and build tool -- **JWT** - JSON Web Token authentication -- **Swagger/OpenAPI** - API documentation -- **Spring Actuator** - Application monitoring and metrics -## ๐Ÿ“‹ Prerequisites - -- Java 17 or higher -- Maven 3.6 or higher -- PostgreSQL (for production) - -## ๐Ÿ› ๏ธ Quick Start - -### 1. Clone and Setup -```bash -git clone https://github.com/bos-com/GreenCode.git -cd GreenCode -``` - -### 2. Build and Run -```bash -mvn clean install -mvn spring-boot:run -``` - -The application will start on `http://localhost:8080` - -## ๐Ÿ—๏ธ Project Structure - -``` +## ๐Ÿ“ Project Structure GreenCode/ -โ”œโ”€โ”€ pom.xml # Maven configuration -โ”œโ”€โ”€ Dockerfile # Containerization -โ”œโ”€โ”€ docker-compose.yml # Multi-service setup -โ”œโ”€โ”€ .env.example # Environment variables template -โ”œโ”€โ”€ .gitignore # Git ignore rules -โ”œโ”€โ”€ README.md # This file -โ”œโ”€โ”€ docs/ # Project documentation -โ”‚ โ”œโ”€โ”€ api/ # API documentation -โ”‚ โ”œโ”€โ”€ deployment/ # Deployment guides -โ”‚ โ””โ”€โ”€ architecture/ # System architecture -โ”œโ”€โ”€ scripts/ # Utility scripts -โ”‚ โ”œโ”€โ”€ setup.sh # Development setup -โ”‚ โ”œโ”€โ”€ deploy.sh # Deployment script -โ”‚ โ””โ”€โ”€ backup.sh # Database backup -โ”œโ”€โ”€ config/ # External configuration -โ”‚ โ”œโ”€โ”€ nginx/ # Nginx configuration -โ”‚ โ””โ”€โ”€ docker/ # Docker configurations -โ”œโ”€โ”€ src/ -โ”‚ โ”œโ”€โ”€ main/ -โ”‚ โ”‚ โ”œโ”€โ”€ java/com/greencode/ -โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ GreenCodeApplication.java # Main application -โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ config/ # Configuration classes -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ SecurityConfig.java # Security setup -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ DatabaseConfig.java # Database configuration -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ SwaggerConfig.java # API documentation -โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ CorsConfig.java # CORS settings -โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ controller/ # REST controllers -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ UserController.java # User management -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ AuthController.java # Authentication -โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ HealthController.java # Health checks -โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ dto/ # Data Transfer Objects -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ UserDto.java # User DTO -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ AuthDto.java # Authentication DTO -โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ ResponseDto.java # Common responses -โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ entity/ # JPA entities -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ BaseEntity.java # Base entity -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ User.java # User entity -โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ Project.java # Project entity -โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ exception/ # Exception handling -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ GlobalExceptionHandler.java -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ CustomException.java # Custom exceptions -โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ ErrorCode.java # Error codes -โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ repository/ # Data access layer -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ UserRepository.java # User repository -โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ ProjectRepository.java # Project repository -โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ service/ # Business logic -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ UserService.java # User service -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ AuthService.java # Authentication service -โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ ProjectService.java # Project service -โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ util/ # Utility classes -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ JwtUtil.java # JWT utilities -โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ValidationUtil.java # Validation helpers -โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ DateUtil.java # Date utilities -โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ constant/ # Constants -โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ AppConstants.java # Application constants -โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ SecurityConstants.java # Security constants -โ”‚ โ”‚ โ””โ”€โ”€ resources/ -โ”‚ โ”‚ โ”œโ”€โ”€ application.yml # Main configuration -โ”‚ โ”‚ โ”œโ”€โ”€ application-dev.yml # Development config -โ”‚ โ”‚ โ”œโ”€โ”€ application-prod.yml # Production config -โ”‚ โ”‚ โ”œโ”€โ”€ db/ # Database scripts -โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ schema.sql # Database schema -โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ data.sql # Initial data -โ”‚ โ”‚ โ””โ”€โ”€ static/ # Static resources -โ”‚ โ””โ”€โ”€ test/ -โ”‚ โ”œโ”€โ”€ java/com/greencode/ -โ”‚ โ”‚ โ”œโ”€โ”€ GreenCodeApplicationTests.java -โ”‚ โ”‚ โ”œโ”€โ”€ controller/ # Controller tests -โ”‚ โ”‚ โ”œโ”€โ”€ service/ # Service tests -โ”‚ โ”‚ โ””โ”€โ”€ repository/ # Repository tests -โ”‚ โ””โ”€โ”€ resources/ -โ”‚ โ””โ”€โ”€ application-test.yml # Test configuration -โ”œโ”€โ”€ logs/ # Application logs -โ”œโ”€โ”€ data/ # Data storage -โ””โ”€โ”€ reports/ # Generated reports -``` - -## ๐Ÿ”ง Configuration - -### Environment Variables -Copy `.env.example` to `.env` and configure: -```bash -# Database -DB_HOST=localhost -DB_PORT=5432 -DB_NAME=greencode -DB_USER=postgres -DB_PASSWORD=password - -# JWT -JWT_SECRET=your-secret-key -JWT_EXPIRATION=86400000 - -# Server -SERVER_PORT=8080 -SERVER_CONTEXT_PATH=/api -``` - -### Database Setup -```bash -# Development (H2 - automatic) -# Production (PostgreSQL) -psql -U postgres -c "CREATE DATABASE greencode;" -``` - -## ๐ŸŒ API Endpoints - -### Authentication -- `POST /api/auth/login` - User login -- `POST /api/auth/register` - User registration -- `POST /api/auth/refresh` - Refresh token -- `POST /api/auth/logout` - User logout - -### User Management -- `GET /api/users` - Get all users -- `GET /api/users/{id}` - Get user by ID -- `POST /api/users` - Create new user -- `PUT /api/users/{id}` - Update user -- `DELETE /api/users/{id}` - Delete user - -### Project Management -- `GET /api/projects` - Get all projects -- `GET /api/projects/{id}` - Get project by ID -- `POST /api/projects` - Create new project -- `PUT /api/projects/{id}` - Update project -- `DELETE /api/projects/{id}` - Delete project - -### Health & Monitoring -- `GET /api/health` - Application health -- `GET /api/metrics` - Application metrics -- `GET /api/info` - Application information - -## ๐Ÿ” Security Features - -- JWT-based authentication -- Role-based access control (USER, ADMIN, MODERATOR) -- Password encryption with BCrypt -- CORS configuration for frontend integration -- Input validation and sanitization -- Rate limiting protection - -## ๐Ÿ—„๏ธ Database Schema - -### Core Tables -- **users** - User accounts and profiles -- **projects** - Environmental projects -- **roles** - User roles and permissions -- **audit_logs** - System activity tracking - -### Key Features -- Soft delete support -- Audit trail for all changes -- Optimized indexes for performance -- Data validation constraints - -## ๐Ÿงช Testing - -```bash -# Run all tests -mvn test - -# Run with coverage -mvn jacoco:report - -# Run specific test -mvn test -Dtest=UserServiceTest - -# Integration tests -mvn verify -``` - -## ๐Ÿš€ Deployment - -### Docker Compose -```bash -# Start all services -docker-compose up -d - -# View logs -docker-compose logs -f - -# Stop services -docker-compose down -``` - -### Production Deployment -```bash -# Build production JAR -mvn clean package -Pprod - -# Run with production profile -java -jar -Dspring.profiles.active=prod target/greencode-backend-1.0.0.jar -``` - -## ๐Ÿ“Š Monitoring - -- **Health Checks**: `/api/health` -- **Metrics**: Prometheus format available -- **Logging**: Structured logging with logback -- **Tracing**: Request tracing for debugging - -## ๐Ÿ”„ Development Workflow - -1. **Feature Development** - - Create feature branch: `git checkout -b feature/new-feature` - - Implement changes with tests - - Submit pull request - -2. **Code Quality** - - Run tests: `mvn test` - - Check style: `mvn checkstyle:check` - - Security scan: `mvn dependency:check` - -3. **Deployment** - - Development: Automatic deployment on push to dev branch - - Production: Manual deployment with approval process - -## ๐Ÿค Contributing - -1. Fork the repository -2. Create a feature branch -3. Make your changes with tests -4. Ensure all tests pass -5. Submit a pull request - -### Code Standards -- Follow Java naming conventions -- Add Javadoc for public methods -- Include unit tests for new features -- Use meaningful commit messages - -## ๐Ÿ“ License - -This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. +โ”œโ”€โ”€ src/ # Spring Boot source code +โ”œโ”€โ”€ config/ # external configuration & scripts +โ”œโ”€โ”€ docs/ # architecture, API docs +โ”œโ”€โ”€ greencode-frontend/ # React frontend (new) +โ”œโ”€โ”€ pom.xml # Maven build file +โ””โ”€โ”€ docker-compose.yml # Docker orchestration -## ๐Ÿ†˜ Support -- **Documentation**: Check the `docs/` folder -- **Issues**: Create an issue in the repository -- **Discussions**: Use GitHub Discussions for questions -- **Email**: Contact the development team diff --git a/doc/docker-setup.md b/doc/docker-setup.md new file mode 100644 index 0000000..46b88a5 --- /dev/null +++ b/doc/docker-setup.md @@ -0,0 +1,58 @@ +# Docker Setup Guide + +This guide explains how to run GreenCode using Docker and Docker Compose. + +## Prerequisites + +- Docker installed +- Docker Compose installed +- Git installed + +## Start the Application + +```bash +docker-compose up -d2. In your fork, create this file + +Go to: + + +Create file: + +docs/docker-setup.md + + +Check Running Services +docker-compose ps +View Logs +docker-compose logs -f + +To view backend logs only: + +docker-compose logs -f greencode-backend +Stop Services +docker-compose down +Rebuild Containers +docker-compose up -d --build +Common Issues +Port Already in Use + +If port 8080 or 5432 is already used, stop the other service or change the mapped port in docker-compose.yml. + +Database Connection Error + +Ensure PostgreSQL is running: + +docker-compose ps + +Then restart services: + +docker-compose restart +Notes +Use .env.example as a guide when creating your .env file. +Do not commit real passwords or secrets. +Check container logs when debugging errors. + +Commit message: + +```text +Add Docker setup guide diff --git a/docs/api/README.md b/docs/api/README.md index 5d3f186..401cefb 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -1,47 +1,92 @@ -# GreenCode API Documentation +# ๐Ÿ“˜ GreenCode API Documentation -This directory contains comprehensive API documentation for the GreenCode backend system. +This directory contains comprehensive API documentation for the **GreenCode backend system**. + +--- ## ๐Ÿ“š Documentation Structure -- **OpenAPI Specification**: Complete API schema in OpenAPI 3.0 format -- **Endpoint Guides**: Detailed documentation for each API endpoint -- **Authentication**: JWT authentication flow and examples -- **Error Codes**: Complete list of error responses -- **Rate Limiting**: API usage limits and guidelines +- **OpenAPI Specification** โ€“ Complete API schema (OpenAPI 3.0) +- **Endpoint Guides** โ€“ Detailed documentation for each API endpoint +- **Authentication** โ€“ JWT authentication flow and examples +- **Error Codes** โ€“ Complete list of error responses +- **Rate Limiting** โ€“ API usage limits and guidelines + +--- ## ๐Ÿ”— Quick Links -- [API Endpoints](./endpoints.md) -- [Authentication Guide](./authentication.md) -- [Error Reference](./errors.md) -- [Rate Limiting](./rate-limiting.md) -- [Postman Collection](./postman/) +- [API Endpoints](#) +- [Authentication Guide](#) +- [Error Reference](#) +- [Rate Limiting](#) +- [Postman Collection](#) + +--- ## ๐Ÿš€ Getting Started -1. **Base URL**: `http://localhost:8080/api` -2. **Authentication**: Bearer token in Authorization header -3. **Content-Type**: `application/json` -4. **API Version**: v1 (included in URL path) +| Item | Value | +|------|------| +| Base URL | `http://localhost:8080/api` | +| Authentication | Bearer Token | +| Content-Type | `application/json` | +| API Version | v1 | -## ๐Ÿ“– Examples +--- + +## ๐Ÿ” Authentication Example -### Authentication ```bash curl -X POST http://localhost:8080/api/auth/login \ -H "Content-Type: application/json" \ - -d '{"username": "user", "password": "password"}' -``` - -### Protected Endpoint -```bash + -d '{ + "username": "user", + "password": "password" + }' +๐Ÿ”‘ Accessing Protected Endpoints curl -X GET http://localhost:8080/api/users \ -H "Authorization: Bearer YOUR_JWT_TOKEN" -``` +๐Ÿ”ง Development Tools +Swagger UI: http://localhost:8080/swagger-ui.html +OpenAPI Spec: http://localhost:8080/api-docs +Health Check: http://localhost:8080/health +๐Ÿ“Œ Notes +Always include the Authorization header for protected routes +Ensure your token has not expired +Use Swagger UI for interactive API testing +๐Ÿงช Best Practices +Validate request payloads before sending +Handle error responses gracefully +Use environment variables for API URLs +๐Ÿ“ฌ Support + +For API issues, open an issue in this repository with: + +Endpoint name +Request payload +Error response + +--- + +# ๐Ÿงพ STEP 2: Commit + +### Commit message +```text +Improve API documentation structure and readability +๐Ÿš€ STEP 3: Create PR +PR Title +Improve API documentation formatting and clarity +PR Description +This pull request improves the GreenCode API documentation. + +Fixes #ISSUE_NUMBER -## ๐Ÿ”ง Development +Changes made: +- Added clear structure and sections +- Improved formatting using tables and code blocks +- Added examples for authentication and protected endpoints +- Included development tools and best practices -- **Swagger UI**: Available at `/swagger-ui.html` -- **OpenAPI Spec**: Available at `/api-docs` -- **Health Check**: Available at `/health` +Importance: +Improves developer experience and makes the API easier to unders diff --git a/docs/testing-guide.md b/docs/testing-guide.md new file mode 100644 index 0000000..7ff5248 --- /dev/null +++ b/docs/testing-guide.md @@ -0,0 +1,30 @@ +# Testing Guide + +This guide explains how contributors can run tests before submitting changes to GreenCode. + +## Prerequisites + +- Java 17 or higher +- Maven 3.6 or higher + +## Run All Tests + +```bash +mvn test +Run Tests with Clean Build +mvn clean test +Build Without Running Tests +mvn clean install -DskipTests +Recommended Before Pull Request + +Before opening a pull request, run: + +mvn clean test +Notes +Fix failing tests before submitting a PR. +Add tests when introducing new features. +Mention testing results in the pull request description. + +Commit message: +```text +Add testing guide for contributors diff --git a/env.example b/env.example index 9a0b23b..edf9cfa 100644 --- a/env.example +++ b/env.example @@ -18,6 +18,10 @@ SPRING_PROFILES_ACTIVE=dev # DATABASE CONFIGURATION # ============================================================================= +# โš ๏ธ SECURITY WARNING: +# Do NOT use default passwords in production. +# Always use strong, unique credentials. + # Development Database (H2) DEV_DB_URL=jdbc:h2:mem:greencode DEV_DB_DRIVER=org.h2.Driver @@ -29,7 +33,7 @@ STAGING_DB_HOST=localhost STAGING_DB_PORT=5432 STAGING_DB_NAME=greencode_staging STAGING_DB_USERNAME=postgres -STAGING_DB_PASSWORD=password +STAGING_DB_PASSWORD=your_secure_password_here STAGING_DB_URL=jdbc:postgresql://${STAGING_DB_HOST}:${STAGING_DB_PORT}/${STAGING_DB_NAME} # Production Database (PostgreSQL) @@ -37,7 +41,7 @@ PROD_DB_HOST=localhost PROD_DB_PORT=5432 PROD_DB_NAME=greencode_prod PROD_DB_USERNAME=postgres -PROD_DB_PASSWORD=password +PROD_DB_PASSWORD=your_secure_password_here PROD_DB_URL=jdbc:postgresql://${PROD_DB_HOST}:${PROD_DB_PORT}/${PROD_DB_NAME} # Docker Database (PostgreSQL) @@ -45,12 +49,16 @@ DOCKER_DB_HOST=postgres DOCKER_DB_PORT=5432 DOCKER_DB_NAME=greencode DOCKER_DB_USERNAME=postgres -DOCKER_DB_PASSWORD=password +DOCKER_DB_PASSWORD=your_secure_password_here DOCKER_DB_URL=jdbc:postgresql://${DOCKER_DB_HOST}:${DOCKER_DB_PORT}/${DOCKER_DB_NAME} # ============================================================================= # JWT CONFIGURATION # ============================================================================= + + +# โš ๏ธ SECURITY WARNING: +# Replace JWT_SECRET with a strong, random value in production. JWT_SECRET=your-secret-key-here-make-it-long-and-secure-in-production JWT_EXPIRATION=86400000 JWT_REFRESH_EXPIRATION=604800000 diff --git a/scripts/setup.sh b/scripts/setup.sh index 8dacc5b..96caf96 100755 --- a/scripts/setup.sh +++ b/scripts/setup.sh @@ -128,7 +128,9 @@ main() { echo "" echo "Next steps:" echo "1. Review and update .env file if needed" - echo "2. Run: ./scripts/start.sh to start the application" + echo "2. Run: ./scripts/start.sh to start the application, or call start_application if using this script interactively" + echo "2. Run: ./scripts/start.sh to start the application" + echo " Note: setup.sh prepares the environment but does not start the app automatically." echo "3. Run: ./scripts/stop.sh to stop the application" echo "4. Check logs/ directory for application logs" } diff --git a/src/main/java/com/greencode/controller/UserController.java b/src/main/java/com/greencode/controller/UserController.java index 5f23091..d6c0121 100644 --- a/src/main/java/com/greencode/controller/UserController.java +++ b/src/main/java/com/greencode/controller/UserController.java @@ -25,6 +25,12 @@ public ResponseEntity> getAllUsers() { return ResponseEntity.ok(users); } + @GetMapping("/active") + public ResponseEntity> getActiveUsers(){ + List users = userService.getActiveUsers(); + return ResponseEntity.ok(users); + } + @GetMapping("/{id}") public ResponseEntity getUserById(@PathVariable Long id) { Optional user = userService.getUserById(id); diff --git a/src/main/java/com/greencode/exception/GlobalExceptionHandler.java b/src/main/java/com/greencode/exception/GlobalExceptionHandler.java index 29e2849..268b2e9 100644 --- a/src/main/java/com/greencode/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/greencode/exception/GlobalExceptionHandler.java @@ -34,6 +34,20 @@ public ResponseEntity handleValidationExceptions(MethodArgumentNo return ResponseEntity.badRequest().body(errorResponse); } + + @ExceptionalHandler(IllegalArgumentException.class) + public ResponseEntity handleIllegalArgumentException(IllegalArgumentException ex) { + ErrorResposponse errorResponse = new ErrorResponse( + LocalDateTime.now(), + HttpStatus.BAD_REQUEST.value(), + "Invalid Request", + ex.getMessage(), + null + ); + + return ResponseEntity.badRequest().body(errorResponse); + } + @ExceptionHandler(RuntimeException.class) public ResponseEntity handleRuntimeException(RuntimeException ex) { ErrorResponse errorResponse = new ErrorResponse( diff --git a/src/main/java/com/greencode/repository/UserRepository.java b/src/main/java/com/greencode/repository/UserRepository.java index 3bd843f..d3293b0 100644 --- a/src/main/java/com/greencode/repository/UserRepository.java +++ b/src/main/java/com/greencode/repository/UserRepository.java @@ -7,10 +7,14 @@ import org.springframework.stereotype.Repository; import java.util.Optional; +import java.util.List; + @Repository public interface UserRepository extends JpaRepository { + List findByIsActiveTrue(); + Optional findByUsername(String username); Optional findByEmail(String email); diff --git a/src/main/java/com/greencode/service/UserService.java b/src/main/java/com/greencode/service/UserService.java index 9e883cf..8a33cb2 100644 --- a/src/main/java/com/greencode/service/UserService.java +++ b/src/main/java/com/greencode/service/UserService.java @@ -36,8 +36,24 @@ public Optional getUserByEmail(String email) { return userRepository.findByEmail(email); } + private void validateUserInput(User user, boolean requirePassword) { + if (user == null) { + throw new IllegalArgumentException("User details must not bre null"); + } + if (user.getUsername() == null || user.getUsername().trim().isEmpty()) { + throw new IllegalArgumentException("Username must not be empty"); + } + if (user.getEmail() == null || user.getEmail().trim().isEmpty()) { + throw new IllegalArgumentException("Email must not be empty"); + } + if (requirePassword && (user.getPassword() == null || user.getPassword().trim().isEmpty())) { + throw new IllegalArgumentException("Password must not be empty"); + } + } + public User createUser(User user) { // Check if username or email already exists + validateUserInput(user, true); if (userRepository.existsByUsername(user.getUsername())) { throw new RuntimeException("Username already exists"); } @@ -52,6 +68,7 @@ public User createUser(User user) { } public User updateUser(Long id, User userDetails) { + validateUserInput(userDetails, false); User user = userRepository.findById(id) .orElseThrow(() -> new RuntimeException("User not found"));