diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml new file mode 100644 index 0000000..ca05840 --- /dev/null +++ b/.github/workflows/ci-cd.yml @@ -0,0 +1,14 @@ +name: Use Template Java CI/CD + +on: + push: + branches: [ "main", "dev" ] + pull_request: + branches: [ "**" ] + +jobs: + call-ci: + uses: Podzilla/templates/.github/workflows/ci.yml@main + with: + branch: 'refs/heads/main' # <<< Passes the branch name dynamically + secrets: inherit \ No newline at end of file diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml new file mode 100644 index 0000000..c9ed1da --- /dev/null +++ b/.github/workflows/linter.yml @@ -0,0 +1,12 @@ +name: Use Template Linter + +on: + pull_request: + branches: [ "**" ] + +jobs: + call-linter: + uses: Podzilla/templates/.github/workflows/super-linter.yml@main + with: + branch: 'dev' + secrets: inherit \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/.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/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..ccc55e4 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,46 @@ +services: + backend: + image: openjdk:25-ea-4-jdk-oraclelinux9 + ports: + - "8080:8080" + env_file: + - secret.env + depends_on: + - auth_db + environment: + - SPRING_DATASOURCE_URL=jdbc:postgresql://auth_db:5432/authDB + volumes: + - ./target:/app + - ./logs:/logs + command: [ "java", "-jar", "/app/auth-0.0.1-SNAPSHOT.jar" ] + + auth_db: + image: postgres:latest + environment: + POSTGRES_PASSWORD: 1234 + POSTGRES_USER: postgres + POSTGRES_DB: authDB + ports: + - "5432:5432" + + loki: + image: grafana/loki:latest + ports: + - "3100:3100" + command: -config.file=/etc/loki/local-config.yaml + + promtail: + image: grafana/promtail:latest + volumes: + - ./promtail-config.yml:/etc/promtail/promtail-config.yaml + - ./logs:/logs + command: -config.file=/etc/promtail/promtail-config.yaml + depends_on: + - loki + + grafana: + image: grafana/grafana:latest + ports: + - "3000:3000" + depends_on: + - loki diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..19529dd --- /dev/null +++ b/mvnw @@ -0,0 +1,259 @@ +#!/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.2 +# +# 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:]' +} + +# 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 <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.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${0##*/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 +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..249bdf3 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,149 @@ +<# : 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.2 +@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) { "/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_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::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 +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -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/pom.xml b/pom.xml new file mode 100644 index 0000000..d6c6bf7 --- /dev/null +++ b/pom.xml @@ -0,0 +1,155 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.5 + + + com.podzilla + auth + 0.0.1-SNAPSHOT + auth + This is the authentication service for Podzilla + + + + + + + + + + + + + + + 23 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + org.postgresql + postgresql + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 2.8.5 + + + net.logstash.logback + logstash-logback-encoder + 7.4 + + + org.springframework.boot + spring-boot-starter-jdbc + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-devtools + runtime + + + jakarta.servlet + jakarta.servlet-api + 6.1.0 + provided + + + jakarta.validation + jakarta.validation-api + 3.0.2 + + + + + + io.jsonwebtoken + jjwt-impl + 0.12.6 + runtime + + + io.jsonwebtoken + jjwt-api + 0.12.6 + + + io.jsonwebtoken + jjwt-jackson + 0.12.6 + runtime + + + com.h2database + h2 + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/promtail-config.yml b/promtail-config.yml new file mode 100644 index 0000000..5503c33 --- /dev/null +++ b/promtail-config.yml @@ -0,0 +1,18 @@ +server: + http_listen_port: 9080 + grpc_listen_port: 0 + +positions: + filename: /tmp/positions.yaml + +clients: + - url: http://loki:3100/loki/api/v1/push + +scrape_configs: + - job_name: spring-boot + static_configs: + - targets: + - localhost + labels: + job: spring-boot + __path__: ./logs/*.log diff --git a/src/main/java/com/podzilla/auth/AuthApplication.java b/src/main/java/com/podzilla/auth/AuthApplication.java new file mode 100644 index 0000000..cb6eb42 --- /dev/null +++ b/src/main/java/com/podzilla/auth/AuthApplication.java @@ -0,0 +1,13 @@ +package com.podzilla.auth; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AuthApplication { + + public static void main(final String[] args) { + SpringApplication.run(AuthApplication.class, args); + } + +} diff --git a/src/main/java/com/podzilla/auth/controller/AdminController.java b/src/main/java/com/podzilla/auth/controller/AdminController.java new file mode 100644 index 0000000..2f91bff --- /dev/null +++ b/src/main/java/com/podzilla/auth/controller/AdminController.java @@ -0,0 +1,26 @@ +package com.podzilla.auth.controller; + +import com.podzilla.auth.model.User; +import com.podzilla.auth.service.AdminService; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/admin") +public class AdminController { + + private final AdminService adminService; + + public AdminController(final AdminService adminService) { + this.adminService = adminService; + } + + @GetMapping("/users") + public List getUsers() { + return adminService.getUsers(); + } + +} diff --git a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java new file mode 100644 index 0000000..7f23f24 --- /dev/null +++ b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java @@ -0,0 +1,93 @@ +package com.podzilla.auth.controller; + +import com.podzilla.auth.dto.LoginRequest; +import com.podzilla.auth.dto.SignupRequest; +import com.podzilla.auth.service.AuthenticationService; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/auth") +public class AuthenticationController { + + private final AuthenticationService authenticationService; + + private final SecurityContextLogoutHandler logoutHandler = + new SecurityContextLogoutHandler(); + + private static final Logger LOGGER = + LoggerFactory.getLogger(AuthenticationController.class); + + @Autowired + public AuthenticationController( + final AuthenticationService authenticationService) { + this.authenticationService = authenticationService; + } + + @PostMapping("/login") + public ResponseEntity login( + @RequestBody final LoginRequest loginRequest, + final HttpServletResponse response) { + try { + String email = authenticationService.login(loginRequest, response); + LOGGER.info("User {} logged in", email); + return new ResponseEntity<>( + "User " + email + " logged in successfully", + HttpStatus.OK); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + return new ResponseEntity<>(e.getMessage(), + HttpStatus.UNAUTHORIZED); + } + } + + @PostMapping("/register") + public ResponseEntity registerUser( + @RequestBody final SignupRequest signupRequest, + final HttpServletRequest request) { + try { + authenticationService.registerAccount(signupRequest); + LOGGER.info("User {} registered", signupRequest.getEmail()); + return new ResponseEntity<>("Account registered.", + HttpStatus.CREATED); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + return new ResponseEntity<>(e.getMessage(), + HttpStatus.UNAUTHORIZED); + } + } + + @PostMapping("/logout") + public ResponseEntity logoutUser(final HttpServletResponse response) { + authenticationService.logoutUser(response); + return new ResponseEntity<>("You've been signed out!", HttpStatus.OK); + } + + @PostMapping("/refresh-token") + public ResponseEntity refreshToken( + final HttpServletRequest request, + final HttpServletResponse response) { + try { + String email = authenticationService.refreshToken( + request, response); + LOGGER.info("User {} refreshed token", email); + return new ResponseEntity<>( + "User " + email + " refreshed token successfully", + HttpStatus.OK); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + return new ResponseEntity<>(e.getMessage(), + HttpStatus.UNAUTHORIZED); + } + } +} diff --git a/src/main/java/com/podzilla/auth/controller/ResourceController.java b/src/main/java/com/podzilla/auth/controller/ResourceController.java new file mode 100644 index 0000000..62c464a --- /dev/null +++ b/src/main/java/com/podzilla/auth/controller/ResourceController.java @@ -0,0 +1,23 @@ +package com.podzilla.auth.controller; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ResourceController { + + @GetMapping("/secret_resource") + public ResponseEntity secret() { + return new ResponseEntity<>( + "You are viewing my secret", HttpStatus.OK); + } + + @GetMapping("/public_resource") + public ResponseEntity noSecret() { + // assuming no existing user + + return new ResponseEntity<>("You are in public area", HttpStatus.OK); + } +} diff --git a/src/main/java/com/podzilla/auth/dto/LoginRequest.java b/src/main/java/com/podzilla/auth/dto/LoginRequest.java new file mode 100644 index 0000000..dce141e --- /dev/null +++ b/src/main/java/com/podzilla/auth/dto/LoginRequest.java @@ -0,0 +1,9 @@ +package com.podzilla.auth.dto; + +import lombok.Data; + +@Data +public class LoginRequest { + private String email; + private String password; +} diff --git a/src/main/java/com/podzilla/auth/dto/SignupRequest.java b/src/main/java/com/podzilla/auth/dto/SignupRequest.java new file mode 100644 index 0000000..5749166 --- /dev/null +++ b/src/main/java/com/podzilla/auth/dto/SignupRequest.java @@ -0,0 +1,10 @@ +package com.podzilla.auth.dto; + +import lombok.Data; + +@Data +public class SignupRequest { + private String name; + private String email; + private String password; +} diff --git a/src/main/java/com/podzilla/auth/model/ERole.java b/src/main/java/com/podzilla/auth/model/ERole.java new file mode 100644 index 0000000..e877932 --- /dev/null +++ b/src/main/java/com/podzilla/auth/model/ERole.java @@ -0,0 +1,6 @@ +package com.podzilla.auth.model; + +public enum ERole { + ROLE_USER, + ROLE_ADMIN +} diff --git a/src/main/java/com/podzilla/auth/model/RefreshToken.java b/src/main/java/com/podzilla/auth/model/RefreshToken.java new file mode 100644 index 0000000..7f7da62 --- /dev/null +++ b/src/main/java/com/podzilla/auth/model/RefreshToken.java @@ -0,0 +1,44 @@ +package com.podzilla.auth.model; + +import jakarta.persistence.Entity; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.Id; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Column; +import jakarta.persistence.Table; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "refresh_tokens") +@Getter +@Setter +@NoArgsConstructor +@EntityListeners(AuditingEntityListener.class) +public class RefreshToken { + + @Id + @GeneratedValue(strategy = GenerationType.UUID) + @Column(updatable = false, nullable = false) + private UUID id; + + @ManyToOne(optional = false) + @JoinColumn(name = "user_id") + private User user; + + @Column(nullable = false, updatable = false) + @CreatedDate + private Instant createdAt; + + @Column(nullable = false) + private Instant expiresAt; +} diff --git a/src/main/java/com/podzilla/auth/model/Role.java b/src/main/java/com/podzilla/auth/model/Role.java new file mode 100644 index 0000000..4a52c5d --- /dev/null +++ b/src/main/java/com/podzilla/auth/model/Role.java @@ -0,0 +1,29 @@ +package com.podzilla.auth.model; + +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +import lombok.Data; +import lombok.NoArgsConstructor; + +@Entity +@Data +@NoArgsConstructor +@Table(name = "roles") +public class Role { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Enumerated(EnumType.STRING) + private ERole erole = ERole.ROLE_USER; + + public Role(final ERole erole) { + this.erole = erole; + } +} diff --git a/src/main/java/com/podzilla/auth/model/User.java b/src/main/java/com/podzilla/auth/model/User.java new file mode 100644 index 0000000..c412bc6 --- /dev/null +++ b/src/main/java/com/podzilla/auth/model/User.java @@ -0,0 +1,64 @@ +package com.podzilla.auth.model; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import jakarta.persistence.FetchType; + +import java.util.HashSet; +import java.util.Set; + +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "users") +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class User { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @NotBlank(message = "Name is required") + private String name; + + @NotBlank(message = "Email is required") + @Email + @Column(unique = true) + private String email; + + @NotBlank(message = "Password is required") + private String password; + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "users_roles", + joinColumns = @JoinColumn(name = "user_id"), + inverseJoinColumns = @JoinColumn(name = "role_id")) + private Set roles = new HashSet<>(); + + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, + orphanRemoval = true) + private Set refreshTokens = new HashSet<>(); + + public User(final String name, final String email, + final String password) { + this.name = name; + this.email = email; + this.password = password; + } +} diff --git a/src/main/java/com/podzilla/auth/repository/RefreshTokenRepository.java b/src/main/java/com/podzilla/auth/repository/RefreshTokenRepository.java new file mode 100644 index 0000000..89494fc --- /dev/null +++ b/src/main/java/com/podzilla/auth/repository/RefreshTokenRepository.java @@ -0,0 +1,17 @@ +package com.podzilla.auth.repository; + +import com.podzilla.auth.model.RefreshToken; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; + +@Repository +public interface RefreshTokenRepository extends + JpaRepository { + Optional findByIdAndExpiresAtAfter(UUID id, Instant date); + Optional findByUserIdAndExpiresAtAfter(Long userId, + Instant date); +} diff --git a/src/main/java/com/podzilla/auth/repository/RoleRepository.java b/src/main/java/com/podzilla/auth/repository/RoleRepository.java new file mode 100644 index 0000000..5a09f21 --- /dev/null +++ b/src/main/java/com/podzilla/auth/repository/RoleRepository.java @@ -0,0 +1,13 @@ +package com.podzilla.auth.repository; + +import com.podzilla.auth.model.ERole; +import com.podzilla.auth.model.Role; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface RoleRepository extends JpaRepository { + Optional findByErole(ERole eRole); +} diff --git a/src/main/java/com/podzilla/auth/repository/UserRepository.java b/src/main/java/com/podzilla/auth/repository/UserRepository.java new file mode 100644 index 0000000..93626e6 --- /dev/null +++ b/src/main/java/com/podzilla/auth/repository/UserRepository.java @@ -0,0 +1,13 @@ +package com.podzilla.auth.repository; + +import com.podzilla.auth.model.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface UserRepository extends JpaRepository { + Optional findByEmail(String email); + Boolean existsByEmail(String email); +} diff --git a/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java b/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java new file mode 100644 index 0000000..34d1297 --- /dev/null +++ b/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java @@ -0,0 +1,71 @@ +package com.podzilla.auth.security; + +import com.podzilla.auth.service.CustomUserDetailsService; +import com.podzilla.auth.service.TokenService; +import io.micrometer.common.lang.NonNullApi; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@NonNullApi +@Component +public class JWTAuthenticationFilter extends OncePerRequestFilter { + private final TokenService tokenService; + private final CustomUserDetailsService customUserDetailsService; + + public JWTAuthenticationFilter( + final TokenService tokenService, + final CustomUserDetailsService customUserDetailsService) { + this.tokenService = tokenService; + this.customUserDetailsService = customUserDetailsService; + } + + private static final Logger LOGGER = + LoggerFactory.getLogger(JWTAuthenticationFilter.class); + + @Override + protected void doFilterInternal(final HttpServletRequest request, + final HttpServletResponse response, + final FilterChain filterChain) + throws ServletException, IOException { + + try { + String jwt = tokenService.getAccessTokenFromCookie(request); + tokenService.validateAccessToken(jwt); + String userEmail = tokenService.extractEmail(); + + UserDetails userDetails = + customUserDetailsService.loadUserByUsername(userEmail); + + UsernamePasswordAuthenticationToken authToken = + new UsernamePasswordAuthenticationToken( + userDetails, + null, + userDetails.getAuthorities()); + authToken.setDetails( + new WebAuthenticationDetailsSource().buildDetails(request)); + + SecurityContext context = + SecurityContextHolder.createEmptyContext(); + context.setAuthentication(authToken); + SecurityContextHolder.setContext(context); + + + } catch (Exception e) { + LOGGER.error("Invalid JWT token: {}", e.getMessage()); + } + filterChain.doFilter(request, response); + } +} diff --git a/src/main/java/com/podzilla/auth/security/RestAuthenticationEntryPoint.java b/src/main/java/com/podzilla/auth/security/RestAuthenticationEntryPoint.java new file mode 100644 index 0000000..2351372 --- /dev/null +++ b/src/main/java/com/podzilla/auth/security/RestAuthenticationEntryPoint.java @@ -0,0 +1,22 @@ +package com.podzilla.auth.security; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +@Component +public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { + + @Override + public void commence(final HttpServletRequest request, + final HttpServletResponse response, + final AuthenticationException authException) + throws IOException { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, + "Authentication Failed"); + } +} diff --git a/src/main/java/com/podzilla/auth/security/SecurityConfig.java b/src/main/java/com/podzilla/auth/security/SecurityConfig.java new file mode 100644 index 0000000..11e868e --- /dev/null +++ b/src/main/java/com/podzilla/auth/security/SecurityConfig.java @@ -0,0 +1,77 @@ +package com.podzilla.auth.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig { + + private final JWTAuthenticationFilter jwtAuthenticationFilter; + + public SecurityConfig( + final JWTAuthenticationFilter jwtAuthenticationFilter) { + this.jwtAuthenticationFilter = jwtAuthenticationFilter; + } + + @Bean + SecurityFilterChain securityFilterChain(final HttpSecurity http) + throws Exception { + + http + .csrf(AbstractHttpConfigurer::disable) + .addFilterBefore(jwtAuthenticationFilter, + UsernamePasswordAuthenticationFilter.class) + .exceptionHandling(exceptionHandling -> + exceptionHandling + .authenticationEntryPoint( + new RestAuthenticationEntryPoint()) + ) + .authorizeHttpRequests((auth) -> + auth.requestMatchers( + HttpMethod.GET, "public_resource") + .permitAll() + .requestMatchers("/auth/**").permitAll() + .requestMatchers("/admin/**") + .hasRole("ADMIN") + .anyRequest().authenticated() + + ) + .sessionManagement(s -> s + .sessionCreationPolicy( + SessionCreationPolicy.STATELESS) + ); + + return http.build(); + } + + @Bean + public AuthenticationManager authenticationManager( + final UserDetailsService userDetailsService, + final PasswordEncoder passwordEncoder) { + DaoAuthenticationProvider authenticationProvider = + new DaoAuthenticationProvider(); + authenticationProvider.setUserDetailsService(userDetailsService); + authenticationProvider.setPasswordEncoder(passwordEncoder); + + return new ProviderManager(authenticationProvider); + } + + @Bean + public static PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/src/main/java/com/podzilla/auth/service/AdminService.java b/src/main/java/com/podzilla/auth/service/AdminService.java new file mode 100644 index 0000000..b84b214 --- /dev/null +++ b/src/main/java/com/podzilla/auth/service/AdminService.java @@ -0,0 +1,21 @@ +package com.podzilla.auth.service; + +import com.podzilla.auth.model.User; +import com.podzilla.auth.repository.UserRepository; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class AdminService { + + private final UserRepository userRepository; + + public AdminService(final UserRepository userRepository) { + this.userRepository = userRepository; + } + + public List getUsers() { + return userRepository.findAll(); + } +} diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java new file mode 100644 index 0000000..db361b5 --- /dev/null +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -0,0 +1,98 @@ +package com.podzilla.auth.service; + +import com.podzilla.auth.dto.LoginRequest; +import com.podzilla.auth.dto.SignupRequest; +import com.podzilla.auth.model.ERole; +import com.podzilla.auth.model.Role; +import com.podzilla.auth.model.User; +import com.podzilla.auth.repository.RoleRepository; +import com.podzilla.auth.repository.UserRepository; +import jakarta.persistence.EntityExistsException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +import java.util.Collections; + + +@Service +public class AuthenticationService { + + private final AuthenticationManager authenticationManager; + private final PasswordEncoder passwordEncoder; + private final UserRepository userRepository; + private final TokenService tokenService; + private final RoleRepository roleRepository; + + public AuthenticationService( + final AuthenticationManager authenticationManager, + final PasswordEncoder passwordEncoder, + final UserRepository userRepository, + final TokenService tokenService, + final RoleRepository roleRepository) { + this.authenticationManager = authenticationManager; + this.passwordEncoder = passwordEncoder; + this.userRepository = userRepository; + this.tokenService = tokenService; + this.roleRepository = roleRepository; + } + + public String login(final LoginRequest loginRequest, + final HttpServletResponse response) { + + Authentication authenticationRequest = + UsernamePasswordAuthenticationToken. + unauthenticated( + loginRequest.getEmail(), + loginRequest.getPassword()); + Authentication authenticationResponse = + this.authenticationManager.authenticate(authenticationRequest); + + SecurityContextHolder.getContext(). + setAuthentication(authenticationResponse); + tokenService.generateAccessToken(loginRequest.getEmail(), response); + tokenService.generateRefreshToken(loginRequest.getEmail(), response); + UserDetails userDetails = + (UserDetails) authenticationResponse.getPrincipal(); + + return userDetails.getUsername(); + } + + public void registerAccount(final SignupRequest signupRequest) { + if (userRepository.existsByEmail(signupRequest.getEmail())) { + throw new EntityExistsException("Email already used"); + } + + User account = new User( + signupRequest.getName(), + signupRequest.getEmail(), + passwordEncoder.encode(signupRequest.getPassword())); + Role role = roleRepository.findByErole(ERole.ROLE_USER).orElse(null); + account.setRoles(Collections.singleton(role)); + userRepository.save(account); + } + + public void logoutUser(final HttpServletResponse response) { + tokenService.removeAccessTokenFromCookie(response); + tokenService.removeRefreshTokenFromCookie(response); + } + + public String refreshToken(final HttpServletRequest request, + final HttpServletResponse response) { + String refreshToken = tokenService.getRefreshTokenFromCookie(request); + try { + String email = + tokenService.renewRefreshToken(refreshToken, response); + tokenService.generateAccessToken(email, response); + return email; + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("Invalid refresh token"); + } + } +} diff --git a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java new file mode 100644 index 0000000..5e6da6e --- /dev/null +++ b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java @@ -0,0 +1,47 @@ +package com.podzilla.auth.service; + +import com.podzilla.auth.model.User; +import com.podzilla.auth.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import java.util.Set; +import java.util.stream.Collectors; + +@Service +public class CustomUserDetailsService implements UserDetailsService { + + private final UserRepository userRepository; + + @Autowired + public CustomUserDetailsService(final UserRepository userRepository) { + this.userRepository = userRepository; + } + + @Override + public UserDetails loadUserByUsername(final String email) + throws UsernameNotFoundException { + User user = userRepository.findByEmail(email) + .orElseThrow(() -> + new UsernameNotFoundException( + email + " not found.")); + + Set authorities = user + .getRoles() + .stream() + .map((role) -> new SimpleGrantedAuthority( + role.getErole().name())) + .collect(Collectors.toSet()); + + return new org.springframework.security.core.userdetails.User( + user.getEmail(), + user.getPassword(), + authorities + ); + } +} diff --git a/src/main/java/com/podzilla/auth/service/TokenService.java b/src/main/java/com/podzilla/auth/service/TokenService.java new file mode 100644 index 0000000..9fb564c --- /dev/null +++ b/src/main/java/com/podzilla/auth/service/TokenService.java @@ -0,0 +1,189 @@ +package com.podzilla.auth.service; + +import com.podzilla.auth.model.RefreshToken; +import com.podzilla.auth.model.User; +import com.podzilla.auth.repository.RefreshTokenRepository; +import com.podzilla.auth.repository.UserRepository; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.JwtException; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import jakarta.persistence.EntityExistsException; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.validation.ValidationException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.web.util.WebUtils; + +import javax.crypto.SecretKey; +import java.time.Instant; +import java.time.temporal.TemporalAmount; +import java.util.Date; +import java.util.UUID; + +@Service +public class TokenService { + + // set in .env + @Value("${jwt.token.secret}") + private String secret; + + @Value("${jwt.token.expires}") + private Long jwtExpiresMinutes; + + private Claims claims; + + private static final Integer ACCESS_TOKEN_EXPIRATION_TIME = 60 * 1000; + private static final Integer ACCESS_TOKEN_COOKIE_EXPIRATION_TIME = 60 * 30; + private static final TemporalAmount REFRESH_TOKEN_EXPIRATION_TIME = + java.time.Duration.ofDays(10); + private static final Integer REFRESH_TOKEN_COOKIE_EXPIRATION_TIME = + 60 * 60 * 24 * 10; + private static final String REFRESH_TOKEN_COOKIE_PATH = + "/api/auth/refresh-token"; + private static final String ACCESS_TOKEN_COOKIE_PATH = "/"; + + private final UserRepository userRepository; + private final RefreshTokenRepository refreshTokenRepository; + + public TokenService(final UserRepository userRepository, + final RefreshTokenRepository refreshTokenRepository) { + this.userRepository = userRepository; + this.refreshTokenRepository = refreshTokenRepository; + } + + public void generateAccessToken(final String email, + final HttpServletResponse response) { + String jwt = Jwts.builder() + .subject(email) + .issuedAt(new Date(System.currentTimeMillis())) + .expiration(new Date(System.currentTimeMillis() + + jwtExpiresMinutes * ACCESS_TOKEN_EXPIRATION_TIME)) + .signWith(getSignInKey()) + .compact(); + + Cookie cookie = new Cookie("accessToken", jwt); + cookie.setHttpOnly(true); + cookie.setSecure(true); + cookie.setPath(ACCESS_TOKEN_COOKIE_PATH); + cookie.setMaxAge(ACCESS_TOKEN_COOKIE_EXPIRATION_TIME); + response.addCookie(cookie); + } + + public void generateRefreshToken(final String email, + final HttpServletResponse response) { + User user = userRepository.findByEmail(email) + .orElseThrow(() -> new EntityExistsException("User not found")); + RefreshToken userRefreshToken = + refreshTokenRepository.findByUserIdAndExpiresAtAfter( + user.getId(), Instant.now()).orElse(null); + + if (userRefreshToken == null) { + userRefreshToken = new RefreshToken(); + userRefreshToken.setUser(user); + userRefreshToken.setCreatedAt(Instant.now()); + userRefreshToken.setExpiresAt(Instant.now().plus( + REFRESH_TOKEN_EXPIRATION_TIME)); + refreshTokenRepository.save(userRefreshToken); + } + + String refreshTokenString = userRefreshToken.getId().toString(); + addRefreshTokenToCookie(refreshTokenString, response); + } + + public String renewRefreshToken(final String refreshToken, + final HttpServletResponse response) { + RefreshToken token = + refreshTokenRepository + .findByIdAndExpiresAtAfter( + UUID.fromString(refreshToken), Instant.now()) + .orElseThrow(() -> + new ValidationException( + "Invalid refresh token")); + + token.setExpiresAt(Instant.now()); + refreshTokenRepository.save(token); + + RefreshToken newRefreshToken = new RefreshToken(); + newRefreshToken.setUser(token.getUser()); + newRefreshToken.setCreatedAt(Instant.now()); + newRefreshToken.setExpiresAt(Instant.now().plus( + REFRESH_TOKEN_EXPIRATION_TIME)); + refreshTokenRepository.save(newRefreshToken); + + String newRefreshTokenString = newRefreshToken.getId().toString(); + addRefreshTokenToCookie(newRefreshTokenString, response); + + return token.getUser().getEmail(); + } + + private void addRefreshTokenToCookie(final String refreshToken, + final HttpServletResponse response) { + Cookie cookie = new Cookie("refreshToken", refreshToken); + cookie.setHttpOnly(true); + cookie.setSecure(true); + cookie.setPath(REFRESH_TOKEN_COOKIE_PATH); + cookie.setMaxAge(REFRESH_TOKEN_COOKIE_EXPIRATION_TIME); + response.addCookie(cookie); + } + + public String getAccessTokenFromCookie(final HttpServletRequest request) { + Cookie cookie = WebUtils.getCookie(request, "accessToken"); + if (cookie != null) { + return cookie.getValue(); + } + return null; + + } + + public String getRefreshTokenFromCookie(final HttpServletRequest request) { + Cookie cookie = WebUtils.getCookie(request, "refreshToken"); + if (cookie != null) { + return cookie.getValue(); + } + return null; + } + + public void validateAccessToken(final String token) throws JwtException { + try { + claims = Jwts.parser() + .verifyWith(getSignInKey()) + .build() + .parseSignedClaims(token) + .getPayload(); + + + } catch (JwtException e) { + throw new JwtException(e.getMessage()); + } + } + + public void removeAccessTokenFromCookie( + final HttpServletResponse response) { + Cookie cookie = new Cookie("accessToken", null); + cookie.setPath(ACCESS_TOKEN_COOKIE_PATH); + + response.addCookie(cookie); + } + + public void removeRefreshTokenFromCookie( + final HttpServletResponse response) { + Cookie cookie = new Cookie("refreshToken", null); + cookie.setPath(REFRESH_TOKEN_COOKIE_PATH); + + response.addCookie(cookie); + } + + private SecretKey getSignInKey() { + byte[] keyBytes = Decoders.BASE64.decode(this.secret); + return Keys.hmacShaKeyFor(keyBytes); + } + + public String extractEmail() { + return claims.getSubject(); + } + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..e9d1807 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,27 @@ +spring.application.name=auth + +logging.file.name=./logs/app.log +logging.level.root=info +logging.level.com.podzilla.auth=debug + +spring.datasource.url=jdbc:postgresql://localhost:5432/authDB +spring.datasource.username=postgres +spring.datasource.password=1234 +spring.datasource.driver-class-name=org.postgresql.Driver + +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.generate-ddl=true +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +spring.jpa.properties.hibernate.use_sql_comments=true + +server.servlet.context-path=/api + +logging.level.org.springframework.security=DEBUG + + +#jwt.token.secret + +jwt.token.secret=${SECRET_KEY} +jwt.token.expires=30 \ No newline at end of file diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..39be967 --- /dev/null +++ b/src/main/resources/logback-spring.xml @@ -0,0 +1,15 @@ + + + + logs/app.log + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/java/com/podzilla/auth/AuthApplicationTests.java b/src/test/java/com/podzilla/auth/AuthApplicationTests.java new file mode 100644 index 0000000..b09061f --- /dev/null +++ b/src/test/java/com/podzilla/auth/AuthApplicationTests.java @@ -0,0 +1,13 @@ +package com.podzilla.auth; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class AuthApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties new file mode 100644 index 0000000..6ac6fdd --- /dev/null +++ b/src/test/resources/application.properties @@ -0,0 +1,10 @@ +spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=h2 +spring.datasource.password=1234 +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.jpa.hibernate.ddl-auto=create-drop +logging.level.org.hibernate.SQL=debug + +jwt.token.secret=${SECRET_KEY:12345678901234567890123456789012} +jwt.token.expires=30 \ No newline at end of file