diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml new file mode 100644 index 0000000..921d84f --- /dev/null +++ b/.github/workflows/build.yaml @@ -0,0 +1,89 @@ +name: Build and Package Service +on: + push: + branches: + - 'main' + - 'devOps' + - 'dev' + pull_request: + branches: + - 'main' + - 'devOps' + - 'dev' + +permissions: + contents: read + packages: write + +jobs: + build-test: + name: Install and Build (Tests Skipped) + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + cache: maven + + - name: Cache Maven packages + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + + - name: Build with Maven (Skip Tests) + run: mvn -B clean package -DskipTests --file notification-service/pom.xml + + - name: Upload Build Artifact (JAR) + uses: actions/upload-artifact@v4 + with: + name: notification-service-jar + path: notification-service/target/*.jar + + build-and-push-docker: + name: Build & Push Docker Image + if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/devOps' || github.ref == 'refs/heads/dev' + runs-on: ubuntu-latest + needs: build-test + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Download JAR Artifact + uses: actions/download-artifact@v4 + with: + name: notification-service-jar + path: notification-service/target/ + + - name: Docker meta + id: meta + uses: docker/metadata-action@v5 + with: + images: ghcr.io/techtorque-2025/notification_service + tags: | + type=sha,prefix= + type=raw,value=latest,enable={{is_default_branch}} + + - name: Log in to GHCR + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push Docker image + uses: docker/build-push-action@v5 + with: + context: . + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml new file mode 100644 index 0000000..2ae00b9 --- /dev/null +++ b/.github/workflows/deploy.yaml @@ -0,0 +1,58 @@ +name: Deploy Notification Service to Kubernetes + +on: + workflow_run: + workflows: ["Build and Package Service"] + types: + - completed + branches: + - 'main' + - 'devOps' + +jobs: + deploy: + name: Deploy Notification Service to Kubernetes + if: ${{ github.event.workflow_run.conclusion == 'success' }} + runs-on: ubuntu-latest + + steps: + - name: Get Commit SHA + id: get_sha + run: | + echo "sha=$(echo ${{ github.event.workflow_run.head_sha }} | cut -c1-7)" >> $GITHUB_OUTPUT + + - name: Checkout K8s Config Repo + uses: actions/checkout@v4 + with: + repository: 'TechTorque-2025/k8s-config' + token: ${{ secrets.REPO_ACCESS_TOKEN }} + path: 'config-repo' + ref: 'main' + + - name: Install kubectl + uses: azure/setup-kubectl@v3 + + - name: Install yq + run: | + sudo wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/bin/yq + sudo chmod +x /usr/bin/yq + + - name: Set Kubernetes context + uses: azure/k8s-set-context@v4 + with: + kubeconfig: ${{ secrets.KUBE_CONFIG_DATA }} + + - name: Update image tag in YAML + run: | + yq -i '(select(.kind == "Deployment") | .spec.template.spec.containers[0].image) = "ghcr.io/techtorque-2025/notification_service:${{ steps.get_sha.outputs.sha }}"' config-repo/k8s/services/notificationservice-deployment.yaml + + - name: Display file contents before apply + run: | + echo "--- Displaying k8s/services/notificationservice-deployment.yaml ---" + cat config-repo/k8s/services/notificationservice-deployment.yaml + echo "------------------------------------------------------------" + + - name: Deploy to Kubernetes + run: | + kubectl apply -f config-repo/k8s/services/notificationservice-deployment.yaml + kubectl rollout status deployment/notificationservice-deployment diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d153288 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,34 @@ +# Dockerfile for notification-service + +# --- Build Stage --- +# Use the official Maven image which contains the Java JDK +FROM maven:3.8-eclipse-temurin-17 AS build + +# Set the working directory +WORKDIR /app + +# Copy the pom.xml and download dependencies +COPY notification-service/pom.xml . +RUN mvn -B dependency:go-offline + +# Copy the rest of the source code and build the application +# Note: We copy the pom.xml *first* to leverage Docker layer caching. +COPY notification-service/src ./src +RUN mvn -B clean package -DskipTests + +# --- Run Stage --- +# Use a minimal JRE image for the final container +FROM eclipse-temurin:17-jre-jammy + +# Set a working directory +WORKDIR /app + +# Copy the built JAR from the 'build' stage +# The wildcard is used in case the version number is in the JAR name +COPY --from=build /app/target/*.jar app.jar + +# Expose the port your application runs on +EXPOSE 8088 + +# The command to run your application +ENTRYPOINT ["java", "-jar", "app.jar"] diff --git a/EMAIL_CONFIGURATION.md b/EMAIL_CONFIGURATION.md new file mode 100644 index 0000000..1e9ca25 --- /dev/null +++ b/EMAIL_CONFIGURATION.md @@ -0,0 +1,177 @@ +# Email Configuration Guide for Notification Service + +## Development Mode (Default) + +By default, the service runs with the **dev profile** which **disables email health checks**. This prevents authentication failures during local development. + +### Running in Development Mode + +```bash +# Using Maven +mvn spring-boot:run + +# Using IDE - the dev profile is active by default +# Just run NotificationServiceApplication.java +``` + +**Note:** Email sending will be attempted but won't fail the health check if credentials are invalid. + +--- + +## Testing Email Functionality + +If you want to test actual email sending during development, you need valid Gmail credentials with an App Password. + +### Step 1: Generate Gmail App Password + +1. Go to your Google Account: https://myaccount.google.com/ +2. Navigate to **Security** +3. Enable **2-Step Verification** (if not already enabled) +4. Go to **App Passwords**: https://myaccount.google.com/apppasswords +5. Generate a new app password for "Mail" +6. Copy the 16-character password + +### Step 2: Set Environment Variables + +```bash +# Linux/Mac +export EMAIL_USERNAME="your-email@gmail.com" +export EMAIL_PASSWORD="your-16-char-app-password" + +# Windows (PowerShell) +$env:EMAIL_USERNAME="your-email@gmail.com" +$env:EMAIL_PASSWORD="your-16-char-app-password" +``` + +### Step 3: Enable Mail Health Check (Optional) + +In `application-dev.properties`, change: +```properties +management.health.mail.enabled=true +``` + +### Step 4: Run the Service + +```bash +mvn spring-boot:run +``` + +--- + +## Production Mode + +For production deployments, use the **prod profile** with proper credentials: + +```bash +# Set all required environment variables +export SPRING_PROFILE=prod +export DB_URL=jdbc:postgresql://prod-host:5432/notification_db +export DB_USERNAME=prod_user +export DB_PASSWORD=prod_password +export EMAIL_USERNAME=noreply@techtorque.com +export EMAIL_PASSWORD=production-app-password + +# Run the application +java -jar notification-service.jar --spring.profiles.active=prod +``` + +**Production profile automatically:** +- Enables mail health checks +- Uses environment variables for sensitive data +- Reduces logging verbosity +- Sets JPA to validate-only mode + +--- + +## Troubleshooting + +### Issue: "Username and Password not accepted" + +**Cause:** Invalid Gmail credentials or regular password used instead of App Password. + +**Solutions:** +1. Generate an App Password (see above) +2. Disable mail health check: `management.health.mail.enabled=false` +3. Use dev profile (mail health check disabled by default) + +### Issue: "535-5.7.8 BadCredentials" + +**Cause:** Gmail blocking login attempt. + +**Solutions:** +1. Ensure 2-Step Verification is enabled +2. Use an App Password, not your regular password +3. Check if "Less secure app access" is required (deprecated by Google) + +### Issue: Email sending works but health check fails + +**Cause:** Transient connection issues or rate limiting. + +**Solution:** Disable health check in development: +```properties +management.health.mail.enabled=false +``` + +--- + +## Configuration Summary + +| Profile | Mail Health Check | Use Case | +|---------|------------------|----------| +| **dev** (default) | Disabled | Local development without email | +| **prod** | Enabled | Production with valid credentials | + +--- + +## Quick Commands + +```bash +# Development (no email credentials needed) +mvn spring-boot:run + +# Development with email testing +export EMAIL_USERNAME="your@gmail.com" +export EMAIL_PASSWORD="app-password" +mvn spring-boot:run + +# Production +export SPRING_PROFILE=prod +export EMAIL_USERNAME="prod@techtorque.com" +export EMAIL_PASSWORD="prod-password" +java -jar notification-service.jar +``` + +--- + +## Security Notes + +⚠️ **Never commit email credentials to version control!** + +- Always use environment variables +- Add `.env` files to `.gitignore` +- Use secret management in production (AWS Secrets Manager, Azure Key Vault, etc.) +- Rotate credentials regularly + +--- + +## Alternative: Using MailHog for Development + +For local email testing without real credentials: + +```bash +# Start MailHog +docker run -d -p 1025:1025 -p 8025:8025 mailhog/mailhog + +# Update application-dev.properties +spring.mail.host=localhost +spring.mail.port=1025 +spring.mail.username= +spring.mail.password= +spring.mail.properties.mail.smtp.auth=false +spring.mail.properties.mail.smtp.starttls.enable=false +management.health.mail.enabled=false + +# Access web UI at http://localhost:8025 +``` + +This captures all emails locally without sending them to real addresses. diff --git a/EMAIL_FIX_SUMMARY.md b/EMAIL_FIX_SUMMARY.md new file mode 100644 index 0000000..b0c6a52 --- /dev/null +++ b/EMAIL_FIX_SUMMARY.md @@ -0,0 +1,166 @@ +# Email Configuration Quick Reference + +## ✅ SOLUTION IMPLEMENTED + +The notification service has been configured to **disable email health checks during development**, eliminating the authentication warning you encountered. + +--- + +## What Was Done + +### 1. **Disabled Mail Health Check** (Primary Solution) +Added to `application.properties`: +```properties +management.health.mail.enabled=false +``` + +This prevents Spring Boot Actuator from attempting to connect to Gmail SMTP during health checks. + +### 2. **Created Development Profile** +Created `application-dev.properties` with mail health check disabled by default. + +### 3. **Created Production Profile** +Created `application-prod.properties` that enables health checks and uses environment variables. + +--- + +## Running the Service + +### Development Mode (No Email Credentials Needed) +```bash +cd Notification_Service/notification-service +mvn spring-boot:run +``` + +✅ **No more email warnings!** The service will start cleanly. + +### With Real Email Testing +```bash +export EMAIL_USERNAME="your-email@gmail.com" +export EMAIL_PASSWORD="your-app-password" # Gmail App Password +mvn spring-boot:run +``` + +### Production Mode +```bash +export SPRING_PROFILE=prod +export EMAIL_USERNAME="prod@techtorque.com" +export EMAIL_PASSWORD="prod-password" +java -jar notification-service.jar +``` + +--- + +## Understanding the Warning + +The warning you saw: +``` +jakarta.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted +``` + +**Cause:** Spring Boot Actuator's health endpoint was trying to verify SMTP connection with placeholder credentials. + +**Impact:** +- ⚠️ Warning in logs +- ✅ Service still starts successfully +- ✅ All endpoints work normally +- ❌ Only email sending would fail (if attempted) + +--- + +## Configuration Files Created + +| File | Purpose | +|------|---------| +| `application.properties` | Base config with mail health disabled | +| `application-dev.properties` | Development profile (no real email needed) | +| `application-prod.properties` | Production profile (real credentials required) | +| `EMAIL_CONFIGURATION.md` | Detailed setup guide | +| `test_email_config.sh` | Verification script | + +--- + +## Testing Your Setup + +Run the verification script: +```bash +cd Notification_Service +./test_email_config.sh +``` + +Expected output: +``` +✓ Mail health check is DISABLED in application.properties +✓ Development profile exists +✓ Production profile exists +``` + +--- + +## Common Scenarios + +### Scenario 1: Local Development (Current) +**Status:** ✅ Configured +**Action:** None needed - just run `mvn spring-boot:run` +**Email:** Won't send (no valid credentials) +**Health Check:** Disabled (no warnings) + +### Scenario 2: Testing Email Functionality +**Status:** Need valid Gmail App Password +**Action:** Set EMAIL_USERNAME and EMAIL_PASSWORD env vars +**Email:** Will send to real addresses +**Health Check:** Keep disabled to avoid startup delays + +### Scenario 3: Production Deployment +**Status:** Use prod profile +**Action:** Set all env vars, use `--spring.profiles.active=prod` +**Email:** Fully functional with monitoring +**Health Check:** Enabled for monitoring + +--- + +## Quick Troubleshooting + +| Issue | Solution | +|-------|----------| +| Email warning on startup | ✅ Already fixed - health check disabled | +| Need to test email | Set EMAIL_USERNAME/PASSWORD env vars | +| Want to mock emails | Use MailHog (see EMAIL_CONFIGURATION.md) | +| Production setup | Use prod profile + env vars | + +--- + +## Next Steps + +Your notification service is now properly configured for development! + +**To resume work:** +```bash +cd Notification_Service/notification-service +mvn spring-boot:run +``` + +**To test endpoints:** +```bash +# Health check (should be UP without mail health) +curl http://localhost:8088/actuator/health + +# API docs +open http://localhost:8088/swagger-ui/index.html +``` + +--- + +## Files Modified + +- ✏️ `application.properties` - Added `management.health.mail.enabled=false` +- ➕ `application-dev.properties` - New development profile +- ➕ `application-prod.properties` - New production profile +- ➕ `EMAIL_CONFIGURATION.md` - Detailed guide +- ➕ `test_email_config.sh` - Verification script + +--- + +**Status:** ✅ **Email configuration issue RESOLVED** + +The service will now start without email authentication warnings during development. diff --git a/notification-service/.gitattributes b/notification-service/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/notification-service/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/notification-service/.gitignore b/notification-service/.gitignore new file mode 100644 index 0000000..667aaef --- /dev/null +++ b/notification-service/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/notification-service/.mvn/wrapper/maven-wrapper.properties b/notification-service/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..c0bcafe --- /dev/null +++ b/notification-service/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip diff --git a/notification-service/Dockerfile b/notification-service/Dockerfile new file mode 100644 index 0000000..16b70a1 --- /dev/null +++ b/notification-service/Dockerfile @@ -0,0 +1,19 @@ +# Build stage +FROM maven:3.9-eclipse-temurin-17-alpine AS build +WORKDIR /app +COPY pom.xml . +COPY src ./src +RUN mvn clean package -DskipTests + +# Run stage +FROM eclipse-temurin:17-jre-alpine +WORKDIR /app +COPY --from=build /app/target/*.jar app.jar + +# Create non-root user +RUN addgroup -S spring && adduser -S spring -G spring +USER spring:spring + +EXPOSE 8088 + +ENTRYPOINT ["java", "-jar", "app.jar"] diff --git a/notification-service/mvnw b/notification-service/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/notification-service/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/notification-service/mvnw.cmd b/notification-service/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/notification-service/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/notification-service/pom.xml b/notification-service/pom.xml new file mode 100644 index 0000000..99d0067 --- /dev/null +++ b/notification-service/pom.xml @@ -0,0 +1,121 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.7 + + + com.techtorque + notification-service + 0.0.1-SNAPSHOT + notification-service + Notification Service for TechTorque - handles user notifications, email alerts, and push subscriptions + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-mail + + + org.springframework.boot + spring-boot-starter-actuator + + + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 2.8.4 + + + + com.h2database + h2 + test + + + org.postgresql + postgresql + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/notification-service/src/main/java/com/techtorque/notification_service/NotificationServiceApplication.java b/notification-service/src/main/java/com/techtorque/notification_service/NotificationServiceApplication.java new file mode 100644 index 0000000..40f5c05 --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/NotificationServiceApplication.java @@ -0,0 +1,16 @@ +package com.techtorque.notification_service; + +import com.techtorque.notification_service.config.NotificationProperties; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; + +@SpringBootApplication +@EnableConfigurationProperties(NotificationProperties.class) +public class NotificationServiceApplication { + + public static void main(String[] args) { + SpringApplication.run(NotificationServiceApplication.class, args); + } + +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/config/GatewayHeaderFilter.java b/notification-service/src/main/java/com/techtorque/notification_service/config/GatewayHeaderFilter.java new file mode 100644 index 0000000..2994259 --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/config/GatewayHeaderFilter.java @@ -0,0 +1,61 @@ +package com.techtorque.notification_service.config; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.web.filter.OncePerRequestFilter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +@Slf4j +public class GatewayHeaderFilter extends OncePerRequestFilter { + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + + String userId = request.getHeader("X-User-Subject"); + String rolesHeader = request.getHeader("X-User-Roles"); + + log.debug("Processing request - Path: {}, User-Subject: {}, User-Roles: {}", + request.getRequestURI(), userId, rolesHeader); + + if (userId != null && !userId.isEmpty()) { + List authorities = rolesHeader == null ? Collections.emptyList() : + Arrays.stream(rolesHeader.split(",")) + .map(role -> { + String roleUpper = role.trim().toUpperCase(); + // Treat SUPER_ADMIN as ADMIN for authorization purposes + if ("SUPER_ADMIN".equals(roleUpper)) { + // Add both SUPER_ADMIN and ADMIN roles + return Arrays.asList( + new SimpleGrantedAuthority("ROLE_SUPER_ADMIN"), + new SimpleGrantedAuthority("ROLE_ADMIN") + ); + } + return Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + roleUpper)); + }) + .flatMap(List::stream) + .collect(Collectors.toList()); + + log.debug("Authenticated user: {} with authorities: {}", userId, authorities); + + UsernamePasswordAuthenticationToken authentication = + new UsernamePasswordAuthenticationToken(userId, null, authorities); + + SecurityContextHolder.getContext().setAuthentication(authentication); + } else { + log.warn("No X-User-Subject header found in request to {}", request.getRequestURI()); + } + + filterChain.doFilter(request, response); + } +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/config/NotificationProperties.java b/notification-service/src/main/java/com/techtorque/notification_service/config/NotificationProperties.java new file mode 100644 index 0000000..367c37c --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/config/NotificationProperties.java @@ -0,0 +1,75 @@ +package com.techtorque.notification_service.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * Binds properties under the prefix `notification` (e.g. notification.email.from). + */ +@Component +@ConfigurationProperties(prefix = "notification") +public class NotificationProperties { + + /** maps to notification.email.from */ + private Email email = new Email(); + + /** maps to notification.retention.days */ + private Retention retention = new Retention(); + + public Email getEmail() { + return email; + } + + public void setEmail(Email email) { + this.email = email; + } + + public Retention getRetention() { + return retention; + } + + public void setRetention(Retention retention) { + this.retention = retention; + } + + public static class Email { + /** maps to notification.email.from */ + private String from; + + public String getFrom() { + return from; + } + + public void setFrom(String from) { + this.from = from; + } + + @Override + public String toString() { + return "Email{from='" + from + "'}"; + } + } + + public static class Retention { + /** maps to notification.retention.days */ + private int days = 30; + + public int getDays() { + return days; + } + + public void setDays(int days) { + this.days = days; + } + + @Override + public String toString() { + return "Retention{days=" + days + "}"; + } + } + + @Override + public String toString() { + return "NotificationProperties{" + "email=" + email + ", retention=" + retention + '}'; + } +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/config/OpenApiConfig.java b/notification-service/src/main/java/com/techtorque/notification_service/config/OpenApiConfig.java new file mode 100644 index 0000000..c4ac00a --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/config/OpenApiConfig.java @@ -0,0 +1,78 @@ +package com.techtorque.notification_service.config; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Contact; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.info.License; +import io.swagger.v3.oas.models.security.SecurityRequirement; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.servers.Server; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.List; + +/** + * OpenAPI/Swagger configuration for Notification Service + * + * Configures API documentation with: + * - Service information and contact details + * - Security schemes (Bearer JWT via API Gateway) + * - Server URLs for different environments + * + * Access Swagger UI at: http://localhost:8088/swagger-ui/index.html + * Access API docs JSON at: http://localhost:8088/v3/api-docs + */ +@Configuration +public class OpenApiConfig { + + @Bean + public OpenAPI customOpenAPI() { + return new OpenAPI() + .info(new Info() + .title("TechTorque Notification Service API") + .version("1.0.0") + .description( + "REST API for notification and email management. " + + "This service handles user notifications, email alerts, and subscription management.\n\n" + + "**Key Features:**\n" + + "- Send and receive notifications\n" + + "- Email notification delivery\n" + + "- Subscription management for notification preferences\n" + + "- Mark notifications as read/unread\n" + + "- Query notification history\n\n" + + "**Authentication:**\n" + + "All endpoints require JWT authentication via the API Gateway. " + + "The gateway validates the JWT and injects user context via headers." + ) + .contact(new Contact() + .name("TechTorque Development Team") + .email("dev@techtorque.com") + .url("https://techtorque.com")) + .license(new License() + .name("Proprietary") + .url("https://techtorque.com/license")) + ) + .servers(List.of( + new Server() + .url("http://localhost:8088") + .description("Local development server"), + new Server() + .url("http://localhost:8080/api/v1") + .description("Local API Gateway"), + new Server() + .url("https://api.techtorque.com/v1") + .description("Production API Gateway") + )) + .addSecurityItem(new SecurityRequirement().addList("bearerAuth")) + .components(new io.swagger.v3.oas.models.Components() + .addSecuritySchemes("bearerAuth", new SecurityScheme() + .name("bearerAuth") + .type(SecurityScheme.Type.HTTP) + .scheme("bearer") + .bearerFormat("JWT") + .description("JWT token obtained from authentication service (validated by API Gateway)") + ) + ); + } +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/config/SecurityConfig.java b/notification-service/src/main/java/com/techtorque/notification_service/config/SecurityConfig.java new file mode 100644 index 0000000..ff37730 --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/config/SecurityConfig.java @@ -0,0 +1,58 @@ +package com.techtorque.notification_service.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +@Configuration +@EnableWebSecurity +@EnableMethodSecurity(prePostEnabled = true) +public class SecurityConfig { + + // A more comprehensive whitelist for Swagger/OpenAPI, actuator, and public endpoints + private static final String[] PUBLIC_WHITELIST = { + "/v3/api-docs/**", + "/swagger-ui/**", + "/swagger-ui.html", + "/swagger-resources/**", + "/webjars/**", + "/api-docs/**", + "/actuator/**", + "/health", + "/favicon.ico", + "/error" + }; + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http + // Disable CSRF protection for stateless APIs + .csrf(csrf -> csrf.disable()) + + // Set session management to STATELESS + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + + // Explicitly disable form login and HTTP Basic authentication + .formLogin(formLogin -> formLogin.disable()) + .httpBasic(httpBasic -> httpBasic.disable()) + + // Set up authorization rules + .authorizeHttpRequests(authz -> authz + // Permit all requests to the public endpoints + .requestMatchers(PUBLIC_WHITELIST).permitAll() + + // All other requests must be authenticated + .anyRequest().authenticated() + ) + + // Add our custom filter to read headers from the Gateway + .addFilterBefore(new GatewayHeaderFilter(), UsernamePasswordAuthenticationFilter.class); + + return http.build(); + } +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/controller/NotificationController.java b/notification-service/src/main/java/com/techtorque/notification_service/controller/NotificationController.java new file mode 100644 index 0000000..e789726 --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/controller/NotificationController.java @@ -0,0 +1,107 @@ +package com.techtorque.notification_service.controller; + +import com.techtorque.notification_service.dto.request.MarkAsReadRequest; +import com.techtorque.notification_service.dto.request.SubscribeRequest; +import com.techtorque.notification_service.dto.request.UnsubscribeRequest; +import com.techtorque.notification_service.dto.response.ApiResponse; +import com.techtorque.notification_service.dto.response.NotificationResponse; +import com.techtorque.notification_service.dto.response.SubscriptionResponse; +import com.techtorque.notification_service.entity.Subscription; +import com.techtorque.notification_service.service.NotificationService; +import com.techtorque.notification_service.service.SubscriptionService; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/notifications") +@RequiredArgsConstructor +@Slf4j +public class NotificationController { + + private final NotificationService notificationService; + private final SubscriptionService subscriptionService; + + @GetMapping + public ResponseEntity> getNotifications( + @RequestParam(required = false) Boolean unread, + HttpServletRequest request) { + + String userId = extractUserIdFromGateway(request); + log.info("Getting notifications for user: {}, unreadOnly: {}", userId, unread); + + List notifications = notificationService.getUserNotifications(userId, unread); + return ResponseEntity.ok(notifications); + } + + @PatchMapping("/{notificationId}") + public ResponseEntity markAsRead( + @PathVariable String notificationId, + @Valid @RequestBody MarkAsReadRequest request, + HttpServletRequest httpRequest) { + + String userId = extractUserIdFromGateway(httpRequest); + log.info("Marking notification {} as read for user: {}", notificationId, userId); + + NotificationResponse response = notificationService.markAsRead(notificationId, userId, request.getRead()); + return ResponseEntity.ok(ApiResponse.success("Notification updated", response)); + } + + @DeleteMapping("/{notificationId}") + public ResponseEntity deleteNotification( + @PathVariable String notificationId, + HttpServletRequest request) { + + String userId = extractUserIdFromGateway(request); + log.info("Deleting notification {} for user: {}", notificationId, userId); + + notificationService.deleteNotification(notificationId, userId); + return ResponseEntity.ok(ApiResponse.success("Notification deleted")); + } + + @PostMapping("/subscribe") + public ResponseEntity subscribe( + @Valid @RequestBody SubscribeRequest request, + HttpServletRequest httpRequest) { + + String userId = extractUserIdFromGateway(httpRequest); + log.info("User {} subscribing to push notifications", userId); + + Subscription.Platform platform = Subscription.Platform.valueOf(request.getPlatform()); + SubscriptionResponse response = subscriptionService.subscribe(userId, request.getToken(), platform); + + return ResponseEntity.ok(response); + } + + @DeleteMapping("/subscribe") + public ResponseEntity unsubscribe( + @Valid @RequestBody UnsubscribeRequest request, + HttpServletRequest httpRequest) { + + String userId = extractUserIdFromGateway(httpRequest); + log.info("User {} unsubscribing from push notifications", userId); + + subscriptionService.unsubscribe(userId, request.getToken()); + return ResponseEntity.ok(ApiResponse.success("Unsubscribed successfully")); + } + + @GetMapping("/count/unread") + public ResponseEntity getUnreadCount(HttpServletRequest request) { + String userId = extractUserIdFromGateway(request); + Long count = notificationService.getUnreadCount(userId); + return ResponseEntity.ok(ApiResponse.success("Unread count retrieved", count)); + } + + private String extractUserIdFromGateway(HttpServletRequest request) { + String userId = request.getHeader("X-User-Subject"); + if (userId == null || userId.isEmpty()) { + throw new RuntimeException("User ID not found in request headers. Request must come through API Gateway."); + } + return userId; + } +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/dto/request/MarkAsReadRequest.java b/notification-service/src/main/java/com/techtorque/notification_service/dto/request/MarkAsReadRequest.java new file mode 100644 index 0000000..4db0649 --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/dto/request/MarkAsReadRequest.java @@ -0,0 +1,18 @@ +package com.techtorque.notification_service.dto.request; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class MarkAsReadRequest { + + @NotNull(message = "Read status is required") + private Boolean read; +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/dto/request/SubscribeRequest.java b/notification-service/src/main/java/com/techtorque/notification_service/dto/request/SubscribeRequest.java new file mode 100644 index 0000000..0807d63 --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/dto/request/SubscribeRequest.java @@ -0,0 +1,23 @@ +package com.techtorque.notification_service.dto.request; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class SubscribeRequest { + + @NotBlank(message = "Token is required") + private String token; + + @NotNull(message = "Platform is required") + @Pattern(regexp = "WEB|IOS|ANDROID", message = "Platform must be WEB, IOS, or ANDROID") + private String platform; +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/dto/request/UnsubscribeRequest.java b/notification-service/src/main/java/com/techtorque/notification_service/dto/request/UnsubscribeRequest.java new file mode 100644 index 0000000..88204ae --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/dto/request/UnsubscribeRequest.java @@ -0,0 +1,17 @@ +package com.techtorque.notification_service.dto.request; + +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class UnsubscribeRequest { + + @NotBlank(message = "Token is required") + private String token; +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/dto/response/ApiResponse.java b/notification-service/src/main/java/com/techtorque/notification_service/dto/response/ApiResponse.java new file mode 100644 index 0000000..fdfbbb7 --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/dto/response/ApiResponse.java @@ -0,0 +1,29 @@ +package com.techtorque.notification_service.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class ApiResponse { + + private String message; + private Object data; + + public static ApiResponse success(String message) { + return ApiResponse.builder() + .message(message) + .build(); + } + + public static ApiResponse success(String message, Object data) { + return ApiResponse.builder() + .message(message) + .data(data) + .build(); + } +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/dto/response/NotificationResponse.java b/notification-service/src/main/java/com/techtorque/notification_service/dto/response/NotificationResponse.java new file mode 100644 index 0000000..76de28b --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/dto/response/NotificationResponse.java @@ -0,0 +1,26 @@ +package com.techtorque.notification_service.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class NotificationResponse { + + private String notificationId; + private String type; + private String message; + private String details; + private Boolean read; + private String relatedEntityId; + private String relatedEntityType; + private LocalDateTime createdAt; + private LocalDateTime readAt; + private LocalDateTime expiresAt; +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/dto/response/SubscriptionResponse.java b/notification-service/src/main/java/com/techtorque/notification_service/dto/response/SubscriptionResponse.java new file mode 100644 index 0000000..6b88317 --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/dto/response/SubscriptionResponse.java @@ -0,0 +1,16 @@ +package com.techtorque.notification_service.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class SubscriptionResponse { + + private String subscriptionId; + private String message; +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/entity/Notification.java b/notification-service/src/main/java/com/techtorque/notification_service/entity/Notification.java new file mode 100644 index 0000000..b9831bf --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/entity/Notification.java @@ -0,0 +1,77 @@ +package com.techtorque.notification_service.entity; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.hibernate.annotations.CreationTimestamp; + +import java.time.LocalDateTime; + +@Entity +@Table(name = "notifications") +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class Notification { + + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private String notificationId; + + @Column(nullable = false) + private String userId; + + @Column(nullable = false) + @Enumerated(EnumType.STRING) + private NotificationType type; + + @Column(nullable = false, length = 500) + private String message; + + @Column(length = 1000) + private String details; + + @Column(nullable = false) + @Builder.Default + private Boolean read = false; + + @Column(nullable = false) + @Builder.Default + private Boolean deleted = false; + + @Column(name = "related_entity_id") + private String relatedEntityId; + + @Column(name = "related_entity_type") + private String relatedEntityType; + + @CreationTimestamp + @Column(nullable = false, updatable = false) + private LocalDateTime createdAt; + + @Column + private LocalDateTime readAt; + + @Column + private LocalDateTime expiresAt; + + public enum NotificationType { + INFO, + SUCCESS, + WARNING, + ERROR, + APPOINTMENT_REMINDER, + APPOINTMENT_CONFIRMED, + APPOINTMENT_CANCELLED, + SERVICE_STARTED, + SERVICE_IN_PROGRESS, + SERVICE_COMPLETED, + PAYMENT_RECEIVED, + PAYMENT_PENDING, + INVOICE_GENERATED, + SYSTEM_ALERT + } +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/entity/Subscription.java b/notification-service/src/main/java/com/techtorque/notification_service/entity/Subscription.java new file mode 100644 index 0000000..a3d5d73 --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/entity/Subscription.java @@ -0,0 +1,57 @@ +package com.techtorque.notification_service.entity; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.hibernate.annotations.CreationTimestamp; +import org.hibernate.annotations.UpdateTimestamp; + +import java.time.LocalDateTime; + +@Entity +@Table(name = "subscriptions", uniqueConstraints = { + @UniqueConstraint(columnNames = {"user_id", "token"}) +}) +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class Subscription { + + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private String subscriptionId; + + @Column(name = "user_id", nullable = false) + private String userId; + + @Column(nullable = false, length = 1000) + private String token; + + @Column(nullable = false) + @Enumerated(EnumType.STRING) + private Platform platform; + + @Column(nullable = false) + @Builder.Default + private Boolean active = true; + + @CreationTimestamp + @Column(nullable = false, updatable = false) + private LocalDateTime createdAt; + + @UpdateTimestamp + @Column(nullable = false) + private LocalDateTime updatedAt; + + @Column + private LocalDateTime lastUsedAt; + + public enum Platform { + WEB, + IOS, + ANDROID + } +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/repository/NotificationRepository.java b/notification-service/src/main/java/com/techtorque/notification_service/repository/NotificationRepository.java new file mode 100644 index 0000000..ef3aa80 --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/repository/NotificationRepository.java @@ -0,0 +1,29 @@ +package com.techtorque.notification_service.repository; + +import com.techtorque.notification_service.entity.Notification; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.time.LocalDateTime; +import java.util.List; + +@Repository +public interface NotificationRepository extends JpaRepository { + + List findByUserIdAndDeletedFalseOrderByCreatedAtDesc(String userId); + + List findByUserIdAndReadAndDeletedFalseOrderByCreatedAtDesc(String userId, Boolean read); + + @Query("SELECT n FROM Notification n WHERE n.userId = :userId AND n.deleted = false AND n.read = false ORDER BY n.createdAt DESC") + List findUnreadNotificationsByUserId(@Param("userId") String userId); + + @Query("SELECT COUNT(n) FROM Notification n WHERE n.userId = :userId AND n.deleted = false AND n.read = false") + Long countUnreadByUserId(@Param("userId") String userId); + + @Query("SELECT n FROM Notification n WHERE n.expiresAt < :now AND n.deleted = false") + List findExpiredNotifications(@Param("now") LocalDateTime now); + + List findByRelatedEntityIdAndRelatedEntityType(String entityId, String entityType); +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/repository/SubscriptionRepository.java b/notification-service/src/main/java/com/techtorque/notification_service/repository/SubscriptionRepository.java new file mode 100644 index 0000000..5b8c1d1 --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/repository/SubscriptionRepository.java @@ -0,0 +1,22 @@ +package com.techtorque.notification_service.repository; + +import com.techtorque.notification_service.entity.Subscription; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface SubscriptionRepository extends JpaRepository { + + List findByUserIdAndActiveTrue(String userId); + + Optional findByUserIdAndToken(String userId, String token); + + Optional findByToken(String token); + + boolean existsByUserIdAndToken(String userId, String token); + + List findByActiveTrueOrderByCreatedAtDesc(); +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/seeder/DataSeeder.java b/notification-service/src/main/java/com/techtorque/notification_service/seeder/DataSeeder.java new file mode 100644 index 0000000..2df3bd8 --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/seeder/DataSeeder.java @@ -0,0 +1,142 @@ +package com.techtorque.notification_service.seeder; + +import com.techtorque.notification_service.entity.Notification; +import com.techtorque.notification_service.entity.Subscription; +import com.techtorque.notification_service.repository.NotificationRepository; +import com.techtorque.notification_service.repository.SubscriptionRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.CommandLineRunner; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +@Component +@Profile("!test") +@RequiredArgsConstructor +@Slf4j +public class DataSeeder implements CommandLineRunner { + + private final NotificationRepository notificationRepository; + private final SubscriptionRepository subscriptionRepository; + + @Override + public void run(String... args) { + log.info("Starting DataSeeder for Notification Service..."); + + if (notificationRepository.count() == 0) { + seedNotifications(); + } else { + log.info("Notifications already seeded. Skipping..."); + } + + if (subscriptionRepository.count() == 0) { + seedSubscriptions(); + } else { + log.info("Subscriptions already seeded. Skipping..."); + } + + log.info("DataSeeder completed successfully!"); + } + + private void seedNotifications() { + log.info("Seeding notifications..."); + + String testUserId1 = UUID.randomUUID().toString(); + String testUserId2 = UUID.randomUUID().toString(); + + List notifications = Arrays.asList( + Notification.builder() + .userId(testUserId1) + .type(Notification.NotificationType.APPOINTMENT_CONFIRMED) + .message("Your appointment has been confirmed") + .details("Appointment scheduled for tomorrow at 10:00 AM") + .read(false) + .deleted(false) + .expiresAt(LocalDateTime.now().plusDays(30)) + .build(), + + Notification.builder() + .userId(testUserId1) + .type(Notification.NotificationType.SERVICE_COMPLETED) + .message("Your service has been completed") + .details("Oil change and tire rotation completed successfully") + .read(true) + .deleted(false) + .readAt(LocalDateTime.now().minusHours(2)) + .expiresAt(LocalDateTime.now().plusDays(30)) + .build(), + + Notification.builder() + .userId(testUserId1) + .type(Notification.NotificationType.INVOICE_GENERATED) + .message("Invoice generated for your service") + .details("Total amount: $150.00. Payment due in 7 days.") + .read(false) + .deleted(false) + .expiresAt(LocalDateTime.now().plusDays(30)) + .build(), + + Notification.builder() + .userId(testUserId2) + .type(Notification.NotificationType.APPOINTMENT_REMINDER) + .message("Appointment reminder") + .details("Your appointment is in 1 hour") + .read(false) + .deleted(false) + .expiresAt(LocalDateTime.now().plusDays(1)) + .build(), + + Notification.builder() + .userId(testUserId2) + .type(Notification.NotificationType.PAYMENT_RECEIVED) + .message("Payment received") + .details("We've received your payment of $200.00") + .read(true) + .deleted(false) + .readAt(LocalDateTime.now().minusDays(1)) + .expiresAt(LocalDateTime.now().plusDays(30)) + .build() + ); + + notificationRepository.saveAll(notifications); + log.info("Seeded {} notifications", notifications.size()); + } + + private void seedSubscriptions() { + log.info("Seeding subscriptions..."); + + String testUserId1 = UUID.randomUUID().toString(); + String testUserId2 = UUID.randomUUID().toString(); + + List subscriptions = Arrays.asList( + Subscription.builder() + .userId(testUserId1) + .token("web_push_token_" + UUID.randomUUID()) + .platform(Subscription.Platform.WEB) + .active(true) + .build(), + + Subscription.builder() + .userId(testUserId1) + .token("ios_device_token_" + UUID.randomUUID()) + .platform(Subscription.Platform.IOS) + .active(true) + .build(), + + Subscription.builder() + .userId(testUserId2) + .token("android_device_token_" + UUID.randomUUID()) + .platform(Subscription.Platform.ANDROID) + .active(true) + .build() + ); + + subscriptionRepository.saveAll(subscriptions); + log.info("Seeded {} subscriptions", subscriptions.size()); + } +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/service/NotificationService.java b/notification-service/src/main/java/com/techtorque/notification_service/service/NotificationService.java new file mode 100644 index 0000000..9ad995c --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/service/NotificationService.java @@ -0,0 +1,21 @@ +package com.techtorque.notification_service.service; + +import com.techtorque.notification_service.dto.response.NotificationResponse; +import com.techtorque.notification_service.entity.Notification; + +import java.util.List; + +public interface NotificationService { + + List getUserNotifications(String userId, Boolean unreadOnly); + + NotificationResponse markAsRead(String notificationId, String userId, Boolean read); + + void deleteNotification(String notificationId, String userId); + + NotificationResponse createNotification(String userId, Notification.NotificationType type, String message, String details); + + Long getUnreadCount(String userId); + + void deleteExpiredNotifications(); +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/service/SubscriptionService.java b/notification-service/src/main/java/com/techtorque/notification_service/service/SubscriptionService.java new file mode 100644 index 0000000..d1fe806 --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/service/SubscriptionService.java @@ -0,0 +1,13 @@ +package com.techtorque.notification_service.service; + +import com.techtorque.notification_service.dto.response.SubscriptionResponse; +import com.techtorque.notification_service.entity.Subscription; + +public interface SubscriptionService { + + SubscriptionResponse subscribe(String userId, String token, Subscription.Platform platform); + + void unsubscribe(String userId, String token); + + boolean isSubscribed(String userId, String token); +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/service/impl/NotificationServiceImpl.java b/notification-service/src/main/java/com/techtorque/notification_service/service/impl/NotificationServiceImpl.java new file mode 100644 index 0000000..a0778ae --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/service/impl/NotificationServiceImpl.java @@ -0,0 +1,129 @@ +package com.techtorque.notification_service.service.impl; + +import com.techtorque.notification_service.dto.response.NotificationResponse; +import com.techtorque.notification_service.entity.Notification; +import com.techtorque.notification_service.repository.NotificationRepository; +import com.techtorque.notification_service.service.NotificationService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +@Slf4j +public class NotificationServiceImpl implements NotificationService { + + private final NotificationRepository notificationRepository; + + @Override + @Transactional(readOnly = true) + public List getUserNotifications(String userId, Boolean unreadOnly) { + log.info("Fetching notifications for user: {}, unreadOnly: {}", userId, unreadOnly); + + List notifications; + if (unreadOnly != null && unreadOnly) { + notifications = notificationRepository.findByUserIdAndReadAndDeletedFalseOrderByCreatedAtDesc(userId, false); + } else { + notifications = notificationRepository.findByUserIdAndDeletedFalseOrderByCreatedAtDesc(userId); + } + + return notifications.stream() + .map(this::convertToResponse) + .collect(Collectors.toList()); + } + + @Override + @Transactional + public NotificationResponse markAsRead(String notificationId, String userId, Boolean read) { + log.info("Marking notification {} as read: {} for user: {}", notificationId, read, userId); + + Notification notification = notificationRepository.findById(notificationId) + .orElseThrow(() -> new RuntimeException("Notification not found")); + + if (!notification.getUserId().equals(userId)) { + throw new RuntimeException("Unauthorized access to notification"); + } + + notification.setRead(read); + if (read) { + notification.setReadAt(LocalDateTime.now()); + } else { + notification.setReadAt(null); + } + + Notification updated = notificationRepository.save(notification); + return convertToResponse(updated); + } + + @Override + @Transactional + public void deleteNotification(String notificationId, String userId) { + log.info("Deleting notification {} for user: {}", notificationId, userId); + + Notification notification = notificationRepository.findById(notificationId) + .orElseThrow(() -> new RuntimeException("Notification not found")); + + if (!notification.getUserId().equals(userId)) { + throw new RuntimeException("Unauthorized access to notification"); + } + + notification.setDeleted(true); + notificationRepository.save(notification); + } + + @Override + @Transactional + public NotificationResponse createNotification(String userId, Notification.NotificationType type, + String message, String details) { + log.info("Creating notification for user: {}, type: {}", userId, type); + + Notification notification = Notification.builder() + .userId(userId) + .type(type) + .message(message) + .details(details) + .read(false) + .deleted(false) + .expiresAt(LocalDateTime.now().plusDays(30)) + .build(); + + Notification saved = notificationRepository.save(notification); + return convertToResponse(saved); + } + + @Override + @Transactional(readOnly = true) + public Long getUnreadCount(String userId) { + return notificationRepository.countUnreadByUserId(userId); + } + + @Override + @Transactional + public void deleteExpiredNotifications() { + log.info("Deleting expired notifications"); + List expired = notificationRepository.findExpiredNotifications(LocalDateTime.now()); + expired.forEach(n -> n.setDeleted(true)); + notificationRepository.saveAll(expired); + log.info("Deleted {} expired notifications", expired.size()); + } + + private NotificationResponse convertToResponse(Notification notification) { + return NotificationResponse.builder() + .notificationId(notification.getNotificationId()) + .type(notification.getType().name()) + .message(notification.getMessage()) + .details(notification.getDetails()) + .read(notification.getRead()) + .relatedEntityId(notification.getRelatedEntityId()) + .relatedEntityType(notification.getRelatedEntityType()) + .createdAt(notification.getCreatedAt()) + .readAt(notification.getReadAt()) + .expiresAt(notification.getExpiresAt()) + .build(); + } +} diff --git a/notification-service/src/main/java/com/techtorque/notification_service/service/impl/SubscriptionServiceImpl.java b/notification-service/src/main/java/com/techtorque/notification_service/service/impl/SubscriptionServiceImpl.java new file mode 100644 index 0000000..dc4d3af --- /dev/null +++ b/notification-service/src/main/java/com/techtorque/notification_service/service/impl/SubscriptionServiceImpl.java @@ -0,0 +1,76 @@ +package com.techtorque.notification_service.service.impl; + +import com.techtorque.notification_service.dto.response.SubscriptionResponse; +import com.techtorque.notification_service.entity.Subscription; +import com.techtorque.notification_service.repository.SubscriptionRepository; +import com.techtorque.notification_service.service.SubscriptionService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; + +@Service +@RequiredArgsConstructor +@Slf4j +public class SubscriptionServiceImpl implements SubscriptionService { + + private final SubscriptionRepository subscriptionRepository; + + @Override + @Transactional + public SubscriptionResponse subscribe(String userId, String token, Subscription.Platform platform) { + log.info("Subscribing user {} to push notifications on platform: {}", userId, platform); + + // Check if subscription already exists + if (subscriptionRepository.existsByUserIdAndToken(userId, token)) { + Subscription existing = subscriptionRepository.findByUserIdAndToken(userId, token) + .orElseThrow(() -> new RuntimeException("Subscription not found")); + + if (!existing.getActive()) { + existing.setActive(true); + existing.setUpdatedAt(LocalDateTime.now()); + subscriptionRepository.save(existing); + } + + return SubscriptionResponse.builder() + .subscriptionId(existing.getSubscriptionId()) + .message("Already subscribed") + .build(); + } + + // Create new subscription + Subscription subscription = Subscription.builder() + .userId(userId) + .token(token) + .platform(platform) + .active(true) + .build(); + + Subscription saved = subscriptionRepository.save(subscription); + + return SubscriptionResponse.builder() + .subscriptionId(saved.getSubscriptionId()) + .message("Successfully subscribed") + .build(); + } + + @Override + @Transactional + public void unsubscribe(String userId, String token) { + log.info("Unsubscribing user {} from push notifications", userId); + + Subscription subscription = subscriptionRepository.findByUserIdAndToken(userId, token) + .orElseThrow(() -> new RuntimeException("Subscription not found")); + + subscription.setActive(false); + subscriptionRepository.save(subscription); + } + + @Override + @Transactional(readOnly = true) + public boolean isSubscribed(String userId, String token) { + return subscriptionRepository.existsByUserIdAndToken(userId, token); + } +} diff --git a/notification-service/src/main/resources/application-dev.properties b/notification-service/src/main/resources/application-dev.properties new file mode 100644 index 0000000..f85b34f --- /dev/null +++ b/notification-service/src/main/resources/application-dev.properties @@ -0,0 +1,28 @@ +# Development Profile Configuration +# Use this profile for local development: mvn spring-boot:run -Dspring-boot.run.profiles=dev + +# Database Configuration +spring.datasource.url=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:techtorque_notification} +spring.datasource.username=${DB_USER:techtorque} +spring.datasource.password=${DB_PASS:techtorque123} + +# Email Configuration - Mock/Disabled for Development +spring.mail.host=smtp.gmail.com +spring.mail.port=587 +spring.mail.username=dev@techtorque.com +spring.mail.password=dev-password +# Disable actual email sending in dev +spring.mail.properties.mail.smtp.auth=false +spring.mail.properties.mail.smtp.starttls.enable=false + +# Disable Mail Health Check +management.health.mail.enabled=false + +# Notification Configuration +notification.email.from=dev-noreply@techtorque.com +notification.retention.days=30 + +# Enhanced Logging for Development +logging.level.com.techtorque.notification_service=DEBUG +logging.level.org.springframework.security=DEBUG +logging.level.org.springframework.mail=DEBUG diff --git a/notification-service/src/main/resources/application-prod.properties b/notification-service/src/main/resources/application-prod.properties new file mode 100644 index 0000000..346e3a2 --- /dev/null +++ b/notification-service/src/main/resources/application-prod.properties @@ -0,0 +1,31 @@ +# Production Profile Configuration +# Use this profile for production: java -jar notification-service.jar --spring.profiles.active=prod + +# Database Configuration (use environment variables in production) +spring.datasource.url=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:techtorque_notification} +spring.datasource.username=${DB_USER:techtorque} +spring.datasource.password=${DB_PASS:techtorque123} + +# JPA Configuration +spring.jpa.hibernate.ddl-auto=validate +spring.jpa.show-sql=false + +# Email Configuration - Real credentials required +spring.mail.host=${MAIL_HOST:smtp.gmail.com} +spring.mail.port=${MAIL_PORT:587} +spring.mail.username=${EMAIL_USERNAME} +spring.mail.password=${EMAIL_PASSWORD} +spring.mail.properties.mail.smtp.auth=true +spring.mail.properties.mail.smtp.starttls.enable=true +spring.mail.properties.mail.smtp.starttls.required=true + +# Enable Mail Health Check +management.health.mail.enabled=true + +# Notification Configuration +notification.email.from=${EMAIL_USERNAME} +notification.retention.days=30 + +# Reduced Logging for Production +logging.level.com.techtorque.notification_service=INFO +logging.level.org.springframework.security=WARN diff --git a/notification-service/src/main/resources/application.properties b/notification-service/src/main/resources/application.properties new file mode 100644 index 0000000..e9f6c60 --- /dev/null +++ b/notification-service/src/main/resources/application.properties @@ -0,0 +1,41 @@ +# Application Configuration +spring.application.name=notification-service +server.port=8088 + +# Active Profile (change to 'prod' for production) +spring.profiles.active=${SPRING_PROFILE:dev} + +# Database Configuration +spring.datasource.url=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:techtorque_notification} +spring.datasource.username=${DB_USER:techtorque} +spring.datasource.password=${DB_PASS:techtorque123} +spring.datasource.driver-class-name=org.postgresql.Driver + +# JPA Configuration +spring.jpa.hibernate.ddl-auto=update +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect + +# Email Configuration +spring.mail.host=smtp.gmail.com +spring.mail.port=587 +spring.mail.username=${EMAIL_USERNAME:your-email@gmail.com} +spring.mail.password=${EMAIL_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 + +# Notification Configuration +notification.email.from=${EMAIL_USERNAME:noreply@techtorque.com} +notification.retention.days=30 + +# Actuator Configuration +management.endpoints.web.exposure.include=health,info,metrics +management.endpoint.health.show-details=always +# Disable mail health check during development (enable in production with valid credentials) +management.health.mail.enabled=false + +# Logging +logging.level.com.techtorque.notification_service=DEBUG +logging.level.org.springframework.security=DEBUG diff --git a/notification-service/src/test/java/com/techtorque/notification_service/NotificationServiceApplicationTests.java b/notification-service/src/test/java/com/techtorque/notification_service/NotificationServiceApplicationTests.java new file mode 100644 index 0000000..c4e681d --- /dev/null +++ b/notification-service/src/test/java/com/techtorque/notification_service/NotificationServiceApplicationTests.java @@ -0,0 +1,15 @@ +package com.techtorque.notification_service; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +@SpringBootTest +@ActiveProfiles("test") +class NotificationServiceApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/notification-service/src/test/resources/application-test.properties b/notification-service/src/test/resources/application-test.properties new file mode 100644 index 0000000..44a73a6 --- /dev/null +++ b/notification-service/src/test/resources/application-test.properties @@ -0,0 +1,24 @@ +# Test Configuration +spring.application.name=notification-service-test + +# H2 Test Database +spring.datasource.url=jdbc:h2:mem:testdb;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DEFAULT_NULL_ORDERING=HIGH +spring.datasource.username=sa +spring.datasource.password= +spring.datasource.driver-class-name=org.h2.Driver + +# JPA Test Configuration +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.show-sql=false +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect + +# Disable Email for Tests +spring.mail.host=localhost +spring.mail.port=25 +notification.email.from=test@techtorque.com + +# Disable Actuator for Tests +management.endpoints.enabled-by-default=false + +# Logging +logging.level.com.techtorque.notification_service=INFO diff --git a/test_email_config.sh b/test_email_config.sh new file mode 100755 index 0000000..56c8630 --- /dev/null +++ b/test_email_config.sh @@ -0,0 +1,48 @@ +#!/bin/bash + +# Test Notification Service Email Configuration +# This script verifies that the mail health check is properly disabled + +echo "==========================================" +echo "Testing Notification Service Configuration" +echo "==========================================" +echo "" + +cd /home/randitha/Desktop/IT/UoM/TechTorque-2025/Notification_Service/notification-service + +echo "✓ Checking if mail health check is disabled..." +if grep -q "management.health.mail.enabled" src/main/resources/application.properties; then + HEALTH_STATUS=$(grep "management.health.mail.enabled" src/main/resources/application.properties | grep -o "false\|true") + if [ "$HEALTH_STATUS" = "false" ]; then + echo " ✓ Mail health check is DISABLED in application.properties" + else + echo " ✗ Mail health check is enabled (should be disabled for dev)" + fi +else + echo " ⚠ Mail health check setting not found" +fi + +echo "" +echo "✓ Checking profile configuration..." +if [ -f "src/main/resources/application-dev.properties" ]; then + echo " ✓ Development profile exists (application-dev.properties)" +fi + +if [ -f "src/main/resources/application-prod.properties" ]; then + echo " ✓ Production profile exists (application-prod.properties)" +fi + +echo "" +echo "==========================================" +echo "Configuration Test Summary" +echo "==========================================" +echo "✓ Mail health check: DISABLED (development mode)" +echo "✓ This prevents email authentication warnings" +echo "✓ Service will start without SMTP credential errors" +echo "" +echo "To enable email in production:" +echo " 1. Set EMAIL_USERNAME and EMAIL_PASSWORD env variables" +echo " 2. Use --spring.profiles.active=prod" +echo " 3. See EMAIL_CONFIGURATION.md for details" +echo "" +echo "=========================================="