initial
This commit is contained in:
+15
@@ -0,0 +1,15 @@
|
||||
target/
|
||||
*.class
|
||||
*.log
|
||||
|
||||
.idea/
|
||||
*.iml
|
||||
.vscode/
|
||||
.settings/
|
||||
.classpath
|
||||
.project
|
||||
|
||||
.DS_Store
|
||||
|
||||
.env
|
||||
.serena
|
||||
+3
@@ -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.16/apache-maven-3.9.16-bin.zip
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
# Build stage
|
||||
FROM maven:3.9-eclipse-temurin-21 AS build
|
||||
WORKDIR /app
|
||||
COPY pom.xml .
|
||||
RUN mvn -q dependency:go-offline
|
||||
COPY src ./src
|
||||
RUN mvn -q package -DskipTests
|
||||
|
||||
# Runtime stage
|
||||
FROM eclipse-temurin:21-jre-alpine
|
||||
WORKDIR /app
|
||||
RUN addgroup -S aplp && adduser -S aplp -G aplp
|
||||
USER aplp
|
||||
COPY --from=build /app/target/aplp-backend-*.jar app.jar
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["java", "-jar", "app.jar"]
|
||||
@@ -1 +1,35 @@
|
||||
# aplp.backend.spring
|
||||
|
||||
Backend cho **APLP — Adaptive Personal Learning Platform** (learner application `aplp-web`).
|
||||
|
||||
Java 21 · Spring Boot 3.5 · Modular Monolith · Clean Architecture 4 Layers · DDD-oriented · Vertical Slice.
|
||||
|
||||
## Status
|
||||
|
||||
**Phase 0 — Foundation: implemented.**
|
||||
|
||||
- Backend skeleton (modular monolith: `common`, `identity`, `learner`)
|
||||
- JWT authentication (register / login / logout / refresh)
|
||||
- Basic user + learner profile
|
||||
- Database foundation: PostgreSQL (docker-compose) + Flyway migrations
|
||||
- Env-based configuration, unified error handling, `X-Request-Id`, health/readiness
|
||||
- Integration tests (11, green)
|
||||
|
||||
## Quickstart
|
||||
|
||||
```bash
|
||||
docker compose up -d db
|
||||
./mvnw spring-boot:run
|
||||
curl http://localhost:8080/actuator/health
|
||||
```
|
||||
|
||||
Xem `docs/SETUP.md` để biết chi tiết.
|
||||
|
||||
## Documents
|
||||
|
||||
| Tài liệu | Mô tả |
|
||||
| --- | --- |
|
||||
| [docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md) | Kiến trúc backend: modular monolith, 4 layers |
|
||||
| [docs/MODULES.md](./docs/MODULES.md) | Danh sách business module theo phase |
|
||||
| [docs/CONVENTIONS.md](./docs/CONVENTIONS.md) | Coding & layer conventions |
|
||||
| [docs/SETUP.md](./docs/SETUP.md) | Hướng dẫn setup / chạy local |
|
||||
@@ -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-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
[ -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 "$@"
|
||||
@@ -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-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
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"
|
||||
@@ -0,0 +1,121 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.1.0</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>com.aplp</groupId>
|
||||
<artifactId>web</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>aplp-backend</name>
|
||||
<description>APLP — Adaptive Personal Learning Platform (backend)</description>
|
||||
|
||||
<properties>
|
||||
<java.version>21</java.version>
|
||||
<jjwt.version>0.12.6</jjwt.version>
|
||||
<springdoc.version>2.8.6</springdoc.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
<version>${springdoc.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-database-postgresql</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-api</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-impl</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.aplp.backend;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ConfigurationPropertiesScan
|
||||
public class AplpBackendApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(AplpBackendApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.aplp.backend.common.api;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public record ApiError(
|
||||
Instant timestamp,
|
||||
int status,
|
||||
String error,
|
||||
String code,
|
||||
String message,
|
||||
String traceId
|
||||
) {
|
||||
|
||||
public static ApiError of(int status, String error, String code, String message, String traceId) {
|
||||
return new ApiError(Instant.now(), status, error, code, message, traceId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.aplp.backend.common.api;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
public enum ErrorCode {
|
||||
|
||||
INVALID_ARGUMENT(HttpStatus.BAD_REQUEST),
|
||||
VALIDATION_FAILED(HttpStatus.BAD_REQUEST),
|
||||
MALFORMED_REQUEST(HttpStatus.BAD_REQUEST),
|
||||
UNAUTHENTICATED(HttpStatus.UNAUTHORIZED),
|
||||
INVALID_CREDENTIALS(HttpStatus.UNAUTHORIZED),
|
||||
INVALID_REFRESH_TOKEN(HttpStatus.UNAUTHORIZED),
|
||||
ACCESS_DENIED(HttpStatus.FORBIDDEN),
|
||||
EMAIL_ALREADY_EXISTS(HttpStatus.CONFLICT),
|
||||
USER_NOT_FOUND(HttpStatus.NOT_FOUND),
|
||||
LEARNER_NOT_FOUND(HttpStatus.NOT_FOUND),
|
||||
INTERNAL_ERROR(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
|
||||
private final HttpStatus httpStatus;
|
||||
|
||||
ErrorCode(HttpStatus httpStatus) {
|
||||
this.httpStatus = httpStatus;
|
||||
}
|
||||
|
||||
public HttpStatus httpStatus() {
|
||||
return httpStatus;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.aplp.backend.common.api;
|
||||
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.servlet.resource.NoResourceFoundException;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
|
||||
@ExceptionHandler(DomainException.class)
|
||||
public ResponseEntity<ApiError> handleDomainException(DomainException ex) {
|
||||
HttpStatus status = ex.code().httpStatus();
|
||||
return build(status, ex.code().name(), ex.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ApiError> handleValidation(MethodArgumentNotValidException ex) {
|
||||
Map<String, String> details = new LinkedHashMap<>();
|
||||
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
|
||||
details.putIfAbsent(error.getField(), error.getDefaultMessage());
|
||||
}
|
||||
ApiError error = ApiError.of(
|
||||
HttpStatus.BAD_REQUEST.value(),
|
||||
HttpStatus.BAD_REQUEST.getReasonPhrase(),
|
||||
ErrorCode.VALIDATION_FAILED.name(),
|
||||
"Validation failed",
|
||||
requestId());
|
||||
return ResponseEntity.badRequest().body(error);
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ResponseEntity<ApiError> handleUnreadable(HttpMessageNotReadableException ex) {
|
||||
return build(HttpStatus.BAD_REQUEST, ErrorCode.MALFORMED_REQUEST.name(), "Malformed request body");
|
||||
}
|
||||
|
||||
@ExceptionHandler(NoResourceFoundException.class)
|
||||
public ResponseEntity<ApiError> handleNoResource(NoResourceFoundException ex) {
|
||||
return build(HttpStatus.NOT_FOUND, "NOT_FOUND", "Resource not found");
|
||||
}
|
||||
|
||||
@ExceptionHandler(AuthenticationException.class)
|
||||
public ResponseEntity<ApiError> handleAuthentication(AuthenticationException ex) {
|
||||
return build(HttpStatus.UNAUTHORIZED, ErrorCode.UNAUTHENTICATED.name(), "Authentication required");
|
||||
}
|
||||
|
||||
@ExceptionHandler(AccessDeniedException.class)
|
||||
public ResponseEntity<ApiError> handleAccessDenied(AccessDeniedException ex) {
|
||||
return build(HttpStatus.FORBIDDEN, ErrorCode.ACCESS_DENIED.name(), "Access denied");
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ApiError> handleUnexpected(Exception ex, HttpServletRequest request) {
|
||||
log.error("Unhandled error on {} {}", request.getMethod(), request.getRequestURI(), ex);
|
||||
return build(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.INTERNAL_ERROR.name(), "Internal server error");
|
||||
}
|
||||
|
||||
private ResponseEntity<ApiError> build(HttpStatus status, String code, String message) {
|
||||
ApiError error = ApiError.of(
|
||||
status.value(),
|
||||
status.getReasonPhrase(),
|
||||
code,
|
||||
message,
|
||||
requestId());
|
||||
return ResponseEntity.status(status).body(error);
|
||||
}
|
||||
|
||||
private String requestId() {
|
||||
return MDC.get("requestId");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.aplp.backend.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.time.Clock;
|
||||
|
||||
@Configuration
|
||||
public class CommonConfig {
|
||||
|
||||
@Bean
|
||||
Clock clock() {
|
||||
return Clock.systemUTC();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.aplp.backend.common.config;
|
||||
|
||||
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
|
||||
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
|
||||
import io.swagger.v3.oas.annotations.info.Info;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityScheme;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@OpenAPIDefinition(
|
||||
info = @Info(title = "APLP Backend API", version = "0.1.0", description = "Adaptive Personal Learning Platform (backend)"),
|
||||
security = @SecurityRequirement(name = "bearerAuth")
|
||||
)
|
||||
@SecurityScheme(
|
||||
name = "bearer",
|
||||
type = SecuritySchemeType.HTTP,
|
||||
scheme = "bearer",
|
||||
bearerFormat = "JWT"
|
||||
)
|
||||
public class OpenApiConfig {
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.aplp.backend.common.error;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
|
||||
public class DomainException extends RuntimeException {
|
||||
|
||||
private final ErrorCode code;
|
||||
|
||||
public DomainException(ErrorCode code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public ErrorCode code() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
public record AuthenticatedUser(Long userId, String email, String displayName) {
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@ConfigurationProperties(prefix = "app.cors")
|
||||
public record CorsProperties(
|
||||
List<String> allowedOrigins
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
private final JwtTokenProvider tokenProvider;
|
||||
|
||||
public JwtAuthenticationFilter(JwtTokenProvider tokenProvider) {
|
||||
this.tokenProvider = tokenProvider;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
String token = resolveToken(request);
|
||||
if (token != null) {
|
||||
try {
|
||||
JwtClaims claims = tokenProvider.parse(token);
|
||||
Long userId = Long.valueOf(claims.subject());
|
||||
AuthenticatedUser principal = new AuthenticatedUser(userId, null, null);
|
||||
var authentication = new UsernamePasswordAuthenticationToken(
|
||||
principal,
|
||||
null,
|
||||
List.of(new SimpleGrantedAuthority("ROLE_USER")));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
} catch (RuntimeException ex) {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private String resolveToken(HttpServletRequest request) {
|
||||
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
|
||||
if (header != null && header.startsWith("Bearer ")) {
|
||||
return header.substring(7);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public record JwtClaims(String subject, Instant issuedAt, Instant expiration) {
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@ConfigurationProperties(prefix = "app.jwt")
|
||||
public record JwtProperties(
|
||||
String secret,
|
||||
Duration accessTokenTtl,
|
||||
Duration refreshTokenTtl
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.io.Decoders;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
public class JwtTokenProvider {
|
||||
|
||||
private final JwtProperties properties;
|
||||
private final SecretKey key;
|
||||
|
||||
public JwtTokenProvider(JwtProperties properties) {
|
||||
this.properties = properties;
|
||||
this.key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(properties.secret()));
|
||||
}
|
||||
|
||||
public String createAccessToken(AuthenticatedUser user) {
|
||||
Instant now = Instant.now();
|
||||
return Jwts.builder()
|
||||
.id(UUID.randomUUID().toString())
|
||||
.subject(user.userId().toString())
|
||||
.claim("email", user.email())
|
||||
.claim("displayName", user.displayName())
|
||||
.issuedAt(Date.from(now))
|
||||
.expiration(Date.from(now.plus(properties.accessTokenTtl())))
|
||||
.signWith(key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public String createRefreshToken(Long userId) {
|
||||
Instant now = Instant.now();
|
||||
return Jwts.builder()
|
||||
.id(UUID.randomUUID().toString())
|
||||
.subject(userId.toString())
|
||||
.issuedAt(Date.from(now))
|
||||
.expiration(Date.from(now.plus(properties.refreshTokenTtl())))
|
||||
.signWith(key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public JwtClaims parse(String token) throws JwtException {
|
||||
Claims claims = Jwts.parser()
|
||||
.verifyWith(key)
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
return new JwtClaims(claims.getSubject(), claims.getIssuedAt().toInstant(), claims.getExpiration().toInstant());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import org.springframework.boot.security.autoconfigure.web.servlet.PathRequest;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.Customizer;
|
||||
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.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
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;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
@EnableMethodSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
SecurityFilterChain securityFilterChain(HttpSecurity http,
|
||||
JwtAuthenticationFilter jwtAuthenticationFilter,
|
||||
SecurityErrorHandlers errorHandlers) throws Exception {
|
||||
http
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.cors(Customizer.withDefaults())
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers(HttpMethod.POST,
|
||||
"/api/v1/auth/register",
|
||||
"/api/v1/auth/login",
|
||||
"/api/v1/auth/refresh").permitAll()
|
||||
.requestMatchers("/actuator/health/**", "/actuator/info").permitAll()
|
||||
.requestMatchers("/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").permitAll()
|
||||
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
|
||||
.anyRequest().authenticated())
|
||||
.exceptionHandling(exceptions -> exceptions
|
||||
.authenticationEntryPoint(errorHandlers.authenticationEntryPoint())
|
||||
.accessDeniedHandler(errorHandlers.accessDeniedHandler()))
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
CorsConfigurationSource corsConfigurationSource(CorsProperties corsProperties) {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
configuration.setAllowedOrigins(corsProperties.allowedOrigins());
|
||||
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
|
||||
configuration.setAllowedHeaders(List.of("*"));
|
||||
configuration.setAllowCredentials(true);
|
||||
configuration.setMaxAge(3600L);
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", configuration);
|
||||
return source;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import com.aplp.backend.common.api.ApiError;
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.stereotype.Component;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
public class SecurityErrorHandlers {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public SecurityErrorHandlers(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public AuthenticationEntryPoint authenticationEntryPoint() {
|
||||
return (request, response, authException) ->
|
||||
write(response, HttpStatus.UNAUTHORIZED, ErrorCode.UNAUTHENTICATED.name(), "Authentication required");
|
||||
}
|
||||
|
||||
public AccessDeniedHandler accessDeniedHandler() {
|
||||
return (request, response, accessDeniedException) ->
|
||||
write(response, HttpStatus.FORBIDDEN, ErrorCode.ACCESS_DENIED.name(), "Access denied");
|
||||
}
|
||||
|
||||
private void write(HttpServletResponse response, HttpStatus status, String code, String message)
|
||||
throws IOException {
|
||||
ApiError body = ApiError.of(
|
||||
status.value(),
|
||||
status.getReasonPhrase(),
|
||||
code,
|
||||
message,
|
||||
MDC.get("requestId"));
|
||||
response.setStatus(status.value());
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.getWriter().write(objectMapper.writeValueAsString(body));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.aplp.backend.common.security;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
public final class SecurityUtils {
|
||||
|
||||
private SecurityUtils() {
|
||||
}
|
||||
|
||||
public static AuthenticatedUser currentUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication == null || !(authentication.getPrincipal() instanceof AuthenticatedUser user)) {
|
||||
throw new DomainException(ErrorCode.UNAUTHENTICATED, "Authentication required");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
public static Long currentUserId() {
|
||||
return currentUser().userId();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.aplp.backend.common.web;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class RequestIdFilter extends OncePerRequestFilter {
|
||||
|
||||
public static final String REQUEST_ID_HEADER = "X-Request-Id";
|
||||
public static final String REQUEST_ID_MDC_KEY = "requestId";
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
String requestId = request.getHeader(REQUEST_ID_HEADER);
|
||||
if (requestId == null || requestId.isBlank()) {
|
||||
requestId = UUID.randomUUID().toString();
|
||||
}
|
||||
MDC.put(REQUEST_ID_MDC_KEY, requestId);
|
||||
response.setHeader(REQUEST_ID_HEADER, requestId);
|
||||
try {
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
MDC.remove(REQUEST_ID_MDC_KEY);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.aplp.backend.identity.api;
|
||||
|
||||
import com.aplp.backend.identity.application.AuthService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.HttpStatus;
|
||||
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.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/auth")
|
||||
public class AuthController {
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
public AuthController(AuthService authService) {
|
||||
this.authService = authService;
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public AuthResponse register(@Valid @RequestBody RegisterRequest request) {
|
||||
return AuthResponse.from(authService.register(request.email(), request.password(), request.displayName()));
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public AuthResponse login(@Valid @RequestBody LoginRequest request) {
|
||||
return AuthResponse.from(authService.login(request.email(), request.password()));
|
||||
}
|
||||
|
||||
@PostMapping("/refresh")
|
||||
public AuthResponse refresh(@Valid @RequestBody RefreshTokenRequest request) {
|
||||
return AuthResponse.from(authService.refresh(request.refreshToken()));
|
||||
}
|
||||
|
||||
@PostMapping("/logout")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void logout(@Valid @RequestBody RefreshTokenRequest request) {
|
||||
authService.logout(request.refreshToken());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.aplp.backend.identity.api;
|
||||
|
||||
import com.aplp.backend.identity.application.AuthResult;
|
||||
|
||||
public record AuthResponse(
|
||||
String accessToken,
|
||||
String refreshToken,
|
||||
String tokenType,
|
||||
long expiresIn,
|
||||
UserDto user
|
||||
) {
|
||||
|
||||
public static AuthResponse from(AuthResult result) {
|
||||
return new AuthResponse(
|
||||
result.accessToken(),
|
||||
result.refreshToken(),
|
||||
"Bearer",
|
||||
result.expiresInSeconds(),
|
||||
new UserDto(
|
||||
result.user().userId(),
|
||||
result.user().email(),
|
||||
result.user().displayName()));
|
||||
}
|
||||
|
||||
public record UserDto(Long id, String email, String displayName) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.aplp.backend.identity.api;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record LoginRequest(
|
||||
@NotBlank @Email(message = "must be a valid email") String email,
|
||||
@NotBlank String password
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.aplp.backend.identity.api;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record RefreshTokenRequest(
|
||||
@NotBlank String refreshToken
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.aplp.backend.identity.api;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record RegisterRequest(
|
||||
@NotBlank @Email(message = "must be a valid email") @Size(max = 320) String email,
|
||||
@NotBlank @Size(min = 8, max = 128, message = "must be between 8 and 128 characters") String password,
|
||||
@NotBlank @Size(max = 100) String displayName
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.aplp.backend.identity.application;
|
||||
|
||||
import com.aplp.backend.common.security.AuthenticatedUser;
|
||||
|
||||
public record AuthResult(
|
||||
String accessToken,
|
||||
String refreshToken,
|
||||
long expiresInSeconds,
|
||||
AuthenticatedUser user
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.aplp.backend.identity.application;
|
||||
|
||||
import com.aplp.backend.common.security.AuthenticatedUser;
|
||||
import com.aplp.backend.common.security.JwtClaims;
|
||||
import com.aplp.backend.common.security.JwtProperties;
|
||||
import com.aplp.backend.common.security.JwtTokenProvider;
|
||||
import com.aplp.backend.identity.domain.EmailAlreadyExistsException;
|
||||
import com.aplp.backend.identity.domain.InvalidCredentialsException;
|
||||
import com.aplp.backend.identity.domain.RefreshToken;
|
||||
import com.aplp.backend.identity.domain.RefreshTokenInvalidException;
|
||||
import com.aplp.backend.identity.domain.RefreshTokenRepository;
|
||||
import com.aplp.backend.identity.domain.User;
|
||||
import com.aplp.backend.identity.domain.UserRepository;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
|
||||
@Service
|
||||
public class AuthService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final RefreshTokenRepository refreshTokenRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtTokenProvider tokenProvider;
|
||||
private final JwtProperties jwtProperties;
|
||||
private final LearnerProvisioner learnerProvisioner;
|
||||
private final Clock clock;
|
||||
|
||||
public AuthService(UserRepository userRepository,
|
||||
RefreshTokenRepository refreshTokenRepository,
|
||||
PasswordEncoder passwordEncoder,
|
||||
JwtTokenProvider tokenProvider,
|
||||
JwtProperties jwtProperties,
|
||||
LearnerProvisioner learnerProvisioner,
|
||||
Clock clock) {
|
||||
this.userRepository = userRepository;
|
||||
this.refreshTokenRepository = refreshTokenRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.tokenProvider = tokenProvider;
|
||||
this.jwtProperties = jwtProperties;
|
||||
this.learnerProvisioner = learnerProvisioner;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthResult register(String email, String rawPassword, String displayName) {
|
||||
Instant now = clock.instant();
|
||||
String normalizedEmail = email.trim().toLowerCase();
|
||||
if (userRepository.existsByEmail(normalizedEmail)) {
|
||||
throw new EmailAlreadyExistsException(normalizedEmail);
|
||||
}
|
||||
User user = User.register(normalizedEmail, passwordEncoder.encode(rawPassword), displayName, now);
|
||||
User saved = userRepository.save(user);
|
||||
learnerProvisioner.provision(saved.id(), displayName);
|
||||
return issueTokens(saved);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthResult login(String email, String rawPassword) {
|
||||
String normalizedEmail = email.trim().toLowerCase();
|
||||
User user = userRepository.findByEmail(normalizedEmail).orElseThrow(InvalidCredentialsException::new);
|
||||
if (!passwordEncoder.matches(rawPassword, user.passwordHash())) {
|
||||
throw new InvalidCredentialsException();
|
||||
}
|
||||
return issueTokens(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthResult refresh(String rawRefreshToken) {
|
||||
Instant now = clock.instant();
|
||||
RefreshToken stored = refreshTokenRepository.findByTokenHash(TokenHasher.sha256Hex(rawRefreshToken))
|
||||
.orElseThrow(RefreshTokenInvalidException::new);
|
||||
if (stored.isExpired(now) || stored.isRevoked()) {
|
||||
throw new RefreshTokenInvalidException();
|
||||
}
|
||||
JwtClaims claims;
|
||||
try {
|
||||
claims = tokenProvider.parse(rawRefreshToken);
|
||||
} catch (RuntimeException ex) {
|
||||
throw new RefreshTokenInvalidException();
|
||||
}
|
||||
User user = userRepository.findById(stored.userId())
|
||||
.filter(u -> u.id().toString().equals(claims.subject()))
|
||||
.orElseThrow(RefreshTokenInvalidException::new);
|
||||
|
||||
stored.revoke(now);
|
||||
refreshTokenRepository.save(stored);
|
||||
return issueTokens(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void logout(String rawRefreshToken) {
|
||||
Instant now = clock.instant();
|
||||
refreshTokenRepository.findByTokenHash(TokenHasher.sha256Hex(rawRefreshToken))
|
||||
.ifPresent(token -> {
|
||||
token.revoke(now);
|
||||
refreshTokenRepository.save(token);
|
||||
});
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void logoutAll(Long userId) {
|
||||
Instant now = clock.instant();
|
||||
for (RefreshToken token : refreshTokenRepository.findAllByUserId(userId)) {
|
||||
if (!token.isRevoked()) {
|
||||
token.revoke(now);
|
||||
refreshTokenRepository.save(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private AuthResult issueTokens(User user) {
|
||||
Instant now = clock.instant();
|
||||
AuthenticatedUser principal = new AuthenticatedUser(user.id(), user.email(), user.displayName());
|
||||
String accessToken = tokenProvider.createAccessToken(principal);
|
||||
String rawRefreshToken = tokenProvider.createRefreshToken(user.id());
|
||||
RefreshToken refresh = RefreshToken.issue(
|
||||
user.id(),
|
||||
TokenHasher.sha256Hex(rawRefreshToken),
|
||||
now.plus(jwtProperties.refreshTokenTtl()),
|
||||
now);
|
||||
refreshTokenRepository.save(refresh);
|
||||
return new AuthResult(accessToken, rawRefreshToken, jwtProperties.accessTokenTtl().toSeconds(), principal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.aplp.backend.identity.application;
|
||||
|
||||
public interface LearnerProvisioner {
|
||||
|
||||
void provision(Long userId, String displayName);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.aplp.backend.identity.application;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
|
||||
final class TokenHasher {
|
||||
|
||||
private TokenHasher() {
|
||||
}
|
||||
|
||||
static String sha256Hex(String value) {
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(digest);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 not available", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
|
||||
public class EmailAlreadyExistsException extends DomainException {
|
||||
|
||||
public EmailAlreadyExistsException(String email) {
|
||||
super(ErrorCode.EMAIL_ALREADY_EXISTS, "Email is already registered: " + email);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
|
||||
public class InvalidCredentialsException extends DomainException {
|
||||
|
||||
public InvalidCredentialsException() {
|
||||
super(ErrorCode.INVALID_CREDENTIALS, "Invalid email or password");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class RefreshToken {
|
||||
|
||||
private Long id;
|
||||
private final Long userId;
|
||||
private final String tokenHash;
|
||||
private final Instant expiresAt;
|
||||
private Instant revokedAt;
|
||||
private final Instant createdAt;
|
||||
|
||||
private RefreshToken(Long id, Long userId, String tokenHash, Instant expiresAt, Instant revokedAt, Instant createdAt) {
|
||||
this.id = id;
|
||||
this.userId = userId;
|
||||
this.tokenHash = tokenHash;
|
||||
this.expiresAt = expiresAt;
|
||||
this.revokedAt = revokedAt;
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public static RefreshToken issue(Long userId, String tokenHash, Instant expiresAt, Instant now) {
|
||||
return new RefreshToken(null, userId, tokenHash, expiresAt, null, now);
|
||||
}
|
||||
|
||||
public static RefreshToken reconstruct(Long id, Long userId, String tokenHash, Instant expiresAt,
|
||||
Instant revokedAt, Instant createdAt) {
|
||||
return new RefreshToken(id, userId, tokenHash, expiresAt, revokedAt, createdAt);
|
||||
}
|
||||
|
||||
public boolean isExpired(Instant now) {
|
||||
return now.isAfter(expiresAt);
|
||||
}
|
||||
|
||||
public boolean isRevoked() {
|
||||
return revokedAt != null;
|
||||
}
|
||||
|
||||
public void revoke(Instant now) {
|
||||
this.revokedAt = now;
|
||||
}
|
||||
|
||||
public Long id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Long userId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public String tokenHash() {
|
||||
return tokenHash;
|
||||
}
|
||||
|
||||
public Instant expiresAt() {
|
||||
return expiresAt;
|
||||
}
|
||||
|
||||
public Instant revokedAt() {
|
||||
return revokedAt;
|
||||
}
|
||||
|
||||
public Instant createdAt() {
|
||||
return createdAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
|
||||
public class RefreshTokenInvalidException extends DomainException {
|
||||
|
||||
public RefreshTokenInvalidException() {
|
||||
super(ErrorCode.INVALID_REFRESH_TOKEN, "Refresh token is invalid or expired");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface RefreshTokenRepository {
|
||||
|
||||
Optional<RefreshToken> findByTokenHash(String tokenHash);
|
||||
|
||||
List<RefreshToken> findAllByUserId(Long userId);
|
||||
|
||||
RefreshToken save(RefreshToken token);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class User {
|
||||
|
||||
private Long id;
|
||||
private final String email;
|
||||
private String passwordHash;
|
||||
private String displayName;
|
||||
private UserStatus status;
|
||||
private final Instant createdAt;
|
||||
private Instant updatedAt;
|
||||
|
||||
private User(Long id, String email, String passwordHash, String displayName,
|
||||
UserStatus status, Instant createdAt, Instant updatedAt) {
|
||||
this.id = id;
|
||||
this.email = email;
|
||||
this.passwordHash = passwordHash;
|
||||
this.displayName = displayName;
|
||||
this.status = status;
|
||||
this.createdAt = createdAt;
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
public static User register(String email, String passwordHash, String displayName, Instant now) {
|
||||
return new User(null, normalizeEmail(email), passwordHash, displayName, UserStatus.ACTIVE, now, now);
|
||||
}
|
||||
|
||||
public static User reconstruct(Long id, String email, String passwordHash, String displayName,
|
||||
UserStatus status, Instant createdAt, Instant updatedAt) {
|
||||
return new User(id, email, passwordHash, displayName, status, createdAt, updatedAt);
|
||||
}
|
||||
|
||||
public void updatePasswordHash(String newHash, Instant now) {
|
||||
this.passwordHash = newHash;
|
||||
this.updatedAt = now;
|
||||
}
|
||||
|
||||
public void updateDisplayName(String newDisplayName, Instant now) {
|
||||
this.displayName = newDisplayName;
|
||||
this.updatedAt = now;
|
||||
}
|
||||
|
||||
private static String normalizeEmail(String email) {
|
||||
return email.trim().toLowerCase();
|
||||
}
|
||||
|
||||
public Long id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String email() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public String passwordHash() {
|
||||
return passwordHash;
|
||||
}
|
||||
|
||||
public String displayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public UserStatus status() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public Instant createdAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public Instant updatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserRepository {
|
||||
|
||||
Optional<User> findByEmail(String email);
|
||||
|
||||
Optional<User> findById(Long id);
|
||||
|
||||
boolean existsByEmail(String email);
|
||||
|
||||
User save(User user);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
public enum UserStatus {
|
||||
ACTIVE,
|
||||
DISABLED
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Entity
|
||||
@Table(name = "refresh_token")
|
||||
public class RefreshTokenJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "token_hash", nullable = false, unique = true, length = 64)
|
||||
private String tokenHash;
|
||||
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private Instant expiresAt;
|
||||
|
||||
@Column(name = "revoked_at")
|
||||
private Instant revokedAt;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
protected RefreshTokenJpaEntity() {
|
||||
}
|
||||
|
||||
public RefreshTokenJpaEntity(Long id, Long userId, String tokenHash, Instant expiresAt,
|
||||
Instant revokedAt, Instant createdAt) {
|
||||
this.id = id;
|
||||
this.userId = userId;
|
||||
this.tokenHash = tokenHash;
|
||||
this.expiresAt = expiresAt;
|
||||
this.revokedAt = revokedAt;
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getTokenHash() {
|
||||
return tokenHash;
|
||||
}
|
||||
|
||||
public void setTokenHash(String tokenHash) {
|
||||
this.tokenHash = tokenHash;
|
||||
}
|
||||
|
||||
public Instant getExpiresAt() {
|
||||
return expiresAt;
|
||||
}
|
||||
|
||||
public void setExpiresAt(Instant expiresAt) {
|
||||
this.expiresAt = expiresAt;
|
||||
}
|
||||
|
||||
public Instant getRevokedAt() {
|
||||
return revokedAt;
|
||||
}
|
||||
|
||||
public void setRevokedAt(Instant revokedAt) {
|
||||
this.revokedAt = revokedAt;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface RefreshTokenJpaRepository extends JpaRepository<RefreshTokenJpaEntity, Long> {
|
||||
|
||||
Optional<RefreshTokenJpaEntity> findByTokenHash(String tokenHash);
|
||||
|
||||
List<RefreshTokenJpaEntity> findAllByUserId(Long userId);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import com.aplp.backend.identity.domain.RefreshToken;
|
||||
import com.aplp.backend.identity.domain.RefreshTokenRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class RefreshTokenRepositoryImpl implements RefreshTokenRepository {
|
||||
|
||||
private final RefreshTokenJpaRepository jpaRepository;
|
||||
|
||||
public RefreshTokenRepositoryImpl(RefreshTokenJpaRepository jpaRepository) {
|
||||
this.jpaRepository = jpaRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<RefreshToken> findByTokenHash(String tokenHash) {
|
||||
return jpaRepository.findByTokenHash(tokenHash).map(RefreshTokenRepositoryImpl::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RefreshToken> findAllByUserId(Long userId) {
|
||||
return jpaRepository.findAllByUserId(userId).stream()
|
||||
.map(RefreshTokenRepositoryImpl::toDomain)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public RefreshToken save(RefreshToken token) {
|
||||
RefreshTokenJpaEntity entity = toEntity(token);
|
||||
RefreshTokenJpaEntity saved = jpaRepository.save(entity);
|
||||
return toDomain(saved);
|
||||
}
|
||||
|
||||
private static RefreshTokenJpaEntity toEntity(RefreshToken token) {
|
||||
return new RefreshTokenJpaEntity(
|
||||
token.id(),
|
||||
token.userId(),
|
||||
token.tokenHash(),
|
||||
token.expiresAt(),
|
||||
token.revokedAt(),
|
||||
token.createdAt());
|
||||
}
|
||||
|
||||
private static RefreshToken toDomain(RefreshTokenJpaEntity entity) {
|
||||
return RefreshToken.reconstruct(
|
||||
entity.getId(),
|
||||
entity.getUserId(),
|
||||
entity.getTokenHash(),
|
||||
entity.getExpiresAt(),
|
||||
entity.getRevokedAt(),
|
||||
entity.getCreatedAt());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import com.aplp.backend.identity.domain.UserStatus;
|
||||
import jakarta.persistence.Column;
|
||||
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 java.time.Instant;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class UserJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 320)
|
||||
private String email;
|
||||
|
||||
@Column(name = "password_hash", nullable = false)
|
||||
private String passwordHash;
|
||||
|
||||
@Column(name = "display_name", nullable = false, length = 100)
|
||||
private String displayName;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 20)
|
||||
private UserStatus status;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
protected UserJpaEntity() {
|
||||
}
|
||||
|
||||
public UserJpaEntity(Long id, String email, String passwordHash, String displayName,
|
||||
UserStatus status, Instant createdAt, Instant updatedAt) {
|
||||
this.id = id;
|
||||
this.email = email;
|
||||
this.passwordHash = passwordHash;
|
||||
this.displayName = displayName;
|
||||
this.status = status;
|
||||
this.createdAt = createdAt;
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPasswordHash() {
|
||||
return passwordHash;
|
||||
}
|
||||
|
||||
public void setPasswordHash(String passwordHash) {
|
||||
this.passwordHash = passwordHash;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public void setDisplayName(String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public UserStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(UserStatus status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public Instant getUpdatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
|
||||
public void setUpdatedAt(Instant updatedAt) {
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface UserJpaRepository extends JpaRepository<UserJpaEntity, Long> {
|
||||
|
||||
boolean existsByEmail(String email);
|
||||
|
||||
java.util.Optional<UserJpaEntity> findByEmail(String email);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import com.aplp.backend.identity.domain.User;
|
||||
import com.aplp.backend.identity.domain.UserRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class UserRepositoryImpl implements UserRepository {
|
||||
|
||||
private final UserJpaRepository jpaRepository;
|
||||
|
||||
public UserRepositoryImpl(UserJpaRepository jpaRepository) {
|
||||
this.jpaRepository = jpaRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<User> findByEmail(String email) {
|
||||
return jpaRepository.findByEmail(email).map(UserRepositoryImpl::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<User> findById(Long id) {
|
||||
return jpaRepository.findById(id).map(UserRepositoryImpl::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean existsByEmail(String email) {
|
||||
return jpaRepository.existsByEmail(email);
|
||||
}
|
||||
|
||||
@Override
|
||||
public User save(User user) {
|
||||
UserJpaEntity entity = toEntity(user);
|
||||
UserJpaEntity saved = jpaRepository.save(entity);
|
||||
return toDomain(saved);
|
||||
}
|
||||
|
||||
private static UserJpaEntity toEntity(User user) {
|
||||
return new UserJpaEntity(
|
||||
user.id(),
|
||||
user.email(),
|
||||
user.passwordHash(),
|
||||
user.displayName(),
|
||||
user.status(),
|
||||
user.createdAt(),
|
||||
user.updatedAt());
|
||||
}
|
||||
|
||||
private static User toDomain(UserJpaEntity entity) {
|
||||
return User.reconstruct(
|
||||
entity.getId(),
|
||||
entity.getEmail(),
|
||||
entity.getPasswordHash(),
|
||||
entity.getDisplayName(),
|
||||
entity.getStatus(),
|
||||
entity.getCreatedAt(),
|
||||
entity.getUpdatedAt());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.aplp.backend.learner.api;
|
||||
|
||||
import com.aplp.backend.common.security.SecurityUtils;
|
||||
import com.aplp.backend.learner.application.LearnerService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/learners/me")
|
||||
public class LearnerController {
|
||||
|
||||
private final LearnerService learnerService;
|
||||
|
||||
public LearnerController(LearnerService learnerService) {
|
||||
this.learnerService = learnerService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public LearnerProfileResponse getMyProfile() {
|
||||
return LearnerProfileResponse.from(learnerService.getProfile(SecurityUtils.currentUserId()));
|
||||
}
|
||||
|
||||
@PatchMapping
|
||||
public LearnerProfileResponse updateMyProfile(@Valid @RequestBody UpdateLearnerProfileRequest request) {
|
||||
return LearnerProfileResponse.from(
|
||||
learnerService.updateDisplayName(SecurityUtils.currentUserId(), request.displayName()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.aplp.backend.learner.api;
|
||||
|
||||
import com.aplp.backend.learner.application.LearnerProfile;
|
||||
|
||||
public record LearnerProfileResponse(
|
||||
Long id,
|
||||
Long userId,
|
||||
String displayName
|
||||
) {
|
||||
|
||||
public static LearnerProfileResponse from(LearnerProfile profile) {
|
||||
return new LearnerProfileResponse(profile.id(), profile.userId(), profile.displayName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.aplp.backend.learner.api;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record UpdateLearnerProfileRequest(
|
||||
@NotBlank @Size(max = 100) String displayName
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.aplp.backend.learner.application;
|
||||
|
||||
public record LearnerProfile(
|
||||
Long id,
|
||||
Long userId,
|
||||
String displayName
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.aplp.backend.learner.application;
|
||||
|
||||
import com.aplp.backend.identity.application.LearnerProvisioner;
|
||||
import com.aplp.backend.learner.domain.Learner;
|
||||
import com.aplp.backend.learner.domain.LearnerRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Clock;
|
||||
|
||||
@Service
|
||||
public class LearnerProvisionerImpl implements LearnerProvisioner {
|
||||
|
||||
private final LearnerRepository learnerRepository;
|
||||
private final Clock clock;
|
||||
|
||||
public LearnerProvisionerImpl(LearnerRepository learnerRepository, Clock clock) {
|
||||
this.learnerRepository = learnerRepository;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void provision(Long userId, String displayName) {
|
||||
learnerRepository.save(Learner.create(userId, displayName, clock.instant()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.aplp.backend.learner.application;
|
||||
|
||||
import com.aplp.backend.learner.domain.Learner;
|
||||
import com.aplp.backend.learner.domain.LearnerNotFoundException;
|
||||
import com.aplp.backend.learner.domain.LearnerRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Clock;
|
||||
|
||||
@Service
|
||||
public class LearnerService {
|
||||
|
||||
private final LearnerRepository learnerRepository;
|
||||
private final Clock clock;
|
||||
|
||||
public LearnerService(LearnerRepository learnerRepository, Clock clock) {
|
||||
this.learnerRepository = learnerRepository;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public LearnerProfile getProfile(Long userId) {
|
||||
return learnerRepository.findByUserId(userId)
|
||||
.map(LearnerService::toProfile)
|
||||
.orElseThrow(LearnerNotFoundException::new);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public LearnerProfile updateDisplayName(Long userId, String displayName) {
|
||||
Learner learner = learnerRepository.findByUserId(userId).orElseThrow(LearnerNotFoundException::new);
|
||||
learner.updateDisplayName(displayName, clock.instant());
|
||||
return toProfile(learnerRepository.save(learner));
|
||||
}
|
||||
|
||||
private static LearnerProfile toProfile(Learner learner) {
|
||||
return new LearnerProfile(learner.id(), learner.userId(), learner.displayName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.aplp.backend.learner.domain;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class Learner {
|
||||
|
||||
private Long id;
|
||||
private final Long userId;
|
||||
private String displayName;
|
||||
private final Instant createdAt;
|
||||
private Instant updatedAt;
|
||||
|
||||
private Learner(Long id, Long userId, String displayName, Instant createdAt, Instant updatedAt) {
|
||||
this.id = id;
|
||||
this.userId = userId;
|
||||
this.displayName = displayName;
|
||||
this.createdAt = createdAt;
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
public static Learner create(Long userId, String displayName, Instant now) {
|
||||
return new Learner(null, userId, displayName, now, now);
|
||||
}
|
||||
|
||||
public static Learner reconstruct(Long id, Long userId, String displayName, Instant createdAt, Instant updatedAt) {
|
||||
return new Learner(id, userId, displayName, createdAt, updatedAt);
|
||||
}
|
||||
|
||||
public void updateDisplayName(String newDisplayName, Instant now) {
|
||||
this.displayName = newDisplayName;
|
||||
this.updatedAt = now;
|
||||
}
|
||||
|
||||
public Long id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Long userId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public String displayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public Instant createdAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public Instant updatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.aplp.backend.learner.domain;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
|
||||
public class LearnerNotFoundException extends DomainException {
|
||||
|
||||
public LearnerNotFoundException() {
|
||||
super(ErrorCode.LEARNER_NOT_FOUND, "Learner profile not found");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.aplp.backend.learner.domain;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface LearnerRepository {
|
||||
|
||||
Optional<Learner> findByUserId(Long userId);
|
||||
|
||||
Learner save(Learner learner);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.aplp.backend.learner.persistence;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Entity
|
||||
@Table(name = "learner")
|
||||
public class LearnerJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "user_id", nullable = false, unique = true)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "display_name", nullable = false, length = 100)
|
||||
private String displayName;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
protected LearnerJpaEntity() {
|
||||
}
|
||||
|
||||
public LearnerJpaEntity(Long id, Long userId, String displayName, Instant createdAt, Instant updatedAt) {
|
||||
this.id = id;
|
||||
this.userId = userId;
|
||||
this.displayName = displayName;
|
||||
this.createdAt = createdAt;
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public void setDisplayName(String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public Instant getUpdatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
|
||||
public void setUpdatedAt(Instant updatedAt) {
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.aplp.backend.learner.persistence;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface LearnerJpaRepository extends JpaRepository<LearnerJpaEntity, Long> {
|
||||
|
||||
Optional<LearnerJpaEntity> findByUserId(Long userId);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.aplp.backend.learner.persistence;
|
||||
|
||||
import com.aplp.backend.learner.domain.Learner;
|
||||
import com.aplp.backend.learner.domain.LearnerRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class LearnerRepositoryImpl implements LearnerRepository {
|
||||
|
||||
private final LearnerJpaRepository jpaRepository;
|
||||
|
||||
public LearnerRepositoryImpl(LearnerJpaRepository jpaRepository) {
|
||||
this.jpaRepository = jpaRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Learner> findByUserId(Long userId) {
|
||||
return jpaRepository.findByUserId(userId).map(LearnerRepositoryImpl::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Learner save(Learner learner) {
|
||||
LearnerJpaEntity entity = toEntity(learner);
|
||||
return toDomain(jpaRepository.save(entity));
|
||||
}
|
||||
|
||||
private static LearnerJpaEntity toEntity(Learner learner) {
|
||||
return new LearnerJpaEntity(
|
||||
learner.id(),
|
||||
learner.userId(),
|
||||
learner.displayName(),
|
||||
learner.createdAt(),
|
||||
learner.updatedAt());
|
||||
}
|
||||
|
||||
private static Learner toDomain(LearnerJpaEntity entity) {
|
||||
return Learner.reconstruct(
|
||||
entity.getId(),
|
||||
entity.getUserId(),
|
||||
entity.getDisplayName(),
|
||||
entity.getCreatedAt(),
|
||||
entity.getUpdatedAt());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: ${DB_URL:jdbc:postgresql://localhost:5432/aplp}
|
||||
username: ${DB_USERNAME:postgres}
|
||||
password: ${DB_PASSWORD:Pa55w0rd}
|
||||
hikari:
|
||||
maximum-pool-size: ${DB_POOL_SIZE:10}
|
||||
jpa:
|
||||
properties:
|
||||
hibernate:
|
||||
format_sql: true
|
||||
show-sql: ${JPA_SHOW_SQL:false}
|
||||
|
||||
logging:
|
||||
level:
|
||||
com.aplp.backend: DEBUG
|
||||
@@ -0,0 +1,11 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: ${DB_URL}
|
||||
username: ${DB_USERNAME}
|
||||
password: ${DB_PASSWORD}
|
||||
hikari:
|
||||
maximum-pool-size: ${DB_POOL_SIZE:20}
|
||||
|
||||
logging:
|
||||
level:
|
||||
com.aplp.backend: INFO
|
||||
@@ -0,0 +1,54 @@
|
||||
spring:
|
||||
application:
|
||||
name: aplp-backend
|
||||
profiles:
|
||||
default: dev
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
open-in-view: false
|
||||
flyway:
|
||||
enabled: true
|
||||
locations: classpath:db/migration
|
||||
jackson:
|
||||
default-property-inclusion: non_null
|
||||
|
||||
springdoc:
|
||||
swagger-ui:
|
||||
path: /swagger-ui.html
|
||||
operations-sorter: method
|
||||
|
||||
server:
|
||||
port: ${SERVER_PORT:8080}
|
||||
shutdown: graceful
|
||||
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
exposure:
|
||||
include: health,info,metrics
|
||||
endpoint:
|
||||
health:
|
||||
probes:
|
||||
enabled: true
|
||||
show-details: when_authorized
|
||||
show-components: when_authorized
|
||||
health:
|
||||
livenessstate:
|
||||
enabled: true
|
||||
readinessstate:
|
||||
enabled: true
|
||||
|
||||
logging:
|
||||
pattern:
|
||||
level: "%5p [%X{requestId:-}]"
|
||||
|
||||
app:
|
||||
jwt:
|
||||
# Dev-only default. MUST be overridden via JWT_SECRET in non-dev environments.
|
||||
secret: ${JWT_SECRET:Y29tbWl0LW5vdGhpbmctZGV2LXNlY3JldC1jaGFuZ2UtbWUtaW4tcHJvZHVjdGlvbi0xMjM0NTY3ODkw}
|
||||
access-token-ttl: ${JWT_ACCESS_TTL:15m}
|
||||
refresh-token-ttl: ${JWT_REFRESH_TTL:30d}
|
||||
cors:
|
||||
allowed-origins:
|
||||
- http://localhost:5173
|
||||
@@ -0,0 +1,34 @@
|
||||
CREATE TABLE users (
|
||||
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
email VARCHAR(320) NOT NULL,
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
display_name VARCHAR(100) NOT NULL,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT uq_users_email UNIQUE (email)
|
||||
);
|
||||
|
||||
CREATE TABLE refresh_token (
|
||||
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
token_hash VARCHAR(64) NOT NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
revoked_at TIMESTAMP WITH TIME ZONE,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_refresh_token_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
CONSTRAINT uq_refresh_token_hash UNIQUE (token_hash)
|
||||
);
|
||||
|
||||
CREATE TABLE learner (
|
||||
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
display_name VARCHAR(100) NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT uq_learner_user UNIQUE (user_id),
|
||||
CONSTRAINT fk_learner_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX idx_refresh_token_user_id ON refresh_token (user_id);
|
||||
CREATE INDEX idx_users_email ON users (email);
|
||||
@@ -0,0 +1,211 @@
|
||||
package com.aplp.backend;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@ActiveProfiles("test")
|
||||
class AuthFlowIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
private static final String EMAIL = "learner@aplp.dev";
|
||||
private static final String PASSWORD = "correct-horse-battery";
|
||||
|
||||
record TokenPair(String accessToken, String refreshToken) {
|
||||
}
|
||||
|
||||
@Test
|
||||
void fullAuthFlow() throws Exception {
|
||||
TokenPair registered = register(EMAIL, PASSWORD, "Learner One");
|
||||
viewMyProfile(registered.accessToken());
|
||||
|
||||
TokenPair loggedIn = login(EMAIL, PASSWORD);
|
||||
viewMyProfile(loggedIn.accessToken());
|
||||
|
||||
TokenPair refreshed = refresh(loggedIn.refreshToken());
|
||||
viewMyProfile(refreshed.accessToken());
|
||||
|
||||
logout(refreshed.accessToken(), refreshed.refreshToken());
|
||||
}
|
||||
|
||||
@Test
|
||||
void registrationSetsXRequestIdAndRejectsDuplicate() throws Exception {
|
||||
MvcResult first = mockMvc.perform(post("/api/v1/auth/register")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json("email", "dup@aplp.dev", "password", PASSWORD, "displayName", "Dup")))
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(header().exists("X-Request-Id"))
|
||||
.andReturn();
|
||||
assertThat(bodyOf(first).get("accessToken").asText()).isNotBlank();
|
||||
|
||||
mockMvc.perform(post("/api/v1/auth/register")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json("email", "dup@aplp.dev", "password", PASSWORD, "displayName", "Dup")))
|
||||
.andExpect(status().isConflict())
|
||||
.andExpect(jsonPath("$.code").value("EMAIL_ALREADY_EXISTS"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void protectedResourceRequiresAuthentication() throws Exception {
|
||||
mockMvc.perform(get("/api/v1/learners/me"))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(jsonPath("$.code").value("UNAUTHENTICATED"));
|
||||
|
||||
mockMvc.perform(get("/api/v1/learners/me")
|
||||
.header("Authorization", "Bearer not-a-valid-token"))
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginWithWrongPasswordIsRejected() throws Exception {
|
||||
register("wrong@aplp.dev", PASSWORD, "Wrong");
|
||||
mockMvc.perform(post("/api/v1/auth/login")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json("email", "wrong@aplp.dev", "password", "not-the-password")))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(jsonPath("$.code").value("INVALID_CREDENTIALS"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validationErrorsReturnUniformShape() throws Exception {
|
||||
mockMvc.perform(post("/api/v1/auth/register")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"email\":\"not-an-email\",\"password\":\"x\",\"displayName\":\"\"}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.code").value("VALIDATION_FAILED"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateLearnerDisplayName() throws Exception {
|
||||
TokenPair pair = register("update-me@aplp.dev", PASSWORD, "Old Name");
|
||||
mockMvc.perform(patch("/api/v1/learners/me")
|
||||
.header("Authorization", "Bearer " + pair.accessToken())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"displayName\":\"New Name\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.displayName").value("New Name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void refreshWithRevokedTokenIsRejected() throws Exception {
|
||||
TokenPair pair = loginOrRegister("revoked@aplp.dev");
|
||||
|
||||
mockMvc.perform(post("/api/v1/auth/logout")
|
||||
.header("Authorization", "Bearer " + pair.accessToken())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json("refreshToken", pair.refreshToken())))
|
||||
.andExpect(status().isNoContent());
|
||||
|
||||
mockMvc.perform(post("/api/v1/auth/refresh")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json("refreshToken", pair.refreshToken())))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(jsonPath("$.code").value("INVALID_REFRESH_TOKEN"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void refreshWithRandomTokenIsRejected() throws Exception {
|
||||
mockMvc.perform(post("/api/v1/auth/refresh")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json("refreshToken", "totally-random")))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(jsonPath("$.code").value("INVALID_REFRESH_TOKEN"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void healthIsPublic() throws Exception {
|
||||
mockMvc.perform(get("/actuator/health"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.status").value("UP"));
|
||||
}
|
||||
|
||||
private TokenPair register(String email, String password, String displayName) throws Exception {
|
||||
MvcResult result = mockMvc.perform(post("/api/v1/auth/register")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json("email", email, "password", password, "displayName", displayName)))
|
||||
.andExpect(status().isCreated())
|
||||
.andReturn();
|
||||
JsonNode body = bodyOf(result);
|
||||
assertThat(body.get("tokenType").asText()).isEqualTo("Bearer");
|
||||
return new TokenPair(body.get("accessToken").asText(), body.get("refreshToken").asText());
|
||||
}
|
||||
|
||||
private TokenPair login(String email, String password) throws Exception {
|
||||
MvcResult result = mockMvc.perform(post("/api/v1/auth/login")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json("email", email, "password", password)))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn();
|
||||
JsonNode body = bodyOf(result);
|
||||
assertThat(body.get("user").get("email").asText()).isEqualTo(email);
|
||||
return new TokenPair(body.get("accessToken").asText(), body.get("refreshToken").asText());
|
||||
}
|
||||
|
||||
private TokenPair loginOrRegister(String email) throws Exception {
|
||||
try {
|
||||
return register(email, PASSWORD, "Revoked");
|
||||
} catch (AssertionError ignored) {
|
||||
return login(email, PASSWORD);
|
||||
}
|
||||
}
|
||||
|
||||
private TokenPair refresh(String refreshToken) throws Exception {
|
||||
MvcResult result = mockMvc.perform(post("/api/v1/auth/refresh")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json("refreshToken", refreshToken)))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn();
|
||||
JsonNode body = bodyOf(result);
|
||||
assertThat(body.get("user").get("email").asText()).isEqualTo(EMAIL);
|
||||
return new TokenPair(body.get("accessToken").asText(), body.get("refreshToken").asText());
|
||||
}
|
||||
|
||||
private void logout(String access, String refreshToken) throws Exception {
|
||||
mockMvc.perform(post("/api/v1/auth/logout")
|
||||
.header("Authorization", "Bearer " + access)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json("refreshToken", refreshToken)))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
private void viewMyProfile(String access) throws Exception {
|
||||
mockMvc.perform(get("/api/v1/learners/me")
|
||||
.header("Authorization", "Bearer " + access))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.displayName").exists());
|
||||
}
|
||||
|
||||
private String json(String... kv) throws Exception {
|
||||
var map = new java.util.LinkedHashMap<String, String>();
|
||||
for (int i = 0; i < kv.length; i += 2) {
|
||||
map.put(kv[i], kv[i + 1]);
|
||||
}
|
||||
return objectMapper.writeValueAsString(map);
|
||||
}
|
||||
|
||||
private JsonNode bodyOf(MvcResult result) throws Exception {
|
||||
return objectMapper.readTree(result.getResponse().getContentAsString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.aplp.backend;
|
||||
|
||||
import com.aplp.backend.common.security.JwtTokenProvider;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("test")
|
||||
class JwtTokenProviderTest {
|
||||
|
||||
@Autowired
|
||||
private JwtTokenProvider tokenProvider;
|
||||
|
||||
@Test
|
||||
void createsAndParsesAccessToken() {
|
||||
var user = new com.aplp.backend.common.security.AuthenticatedUser(42L, "a@b.c", "Nam");
|
||||
String token = tokenProvider.createAccessToken(user);
|
||||
|
||||
var claims = tokenProvider.parse(token);
|
||||
|
||||
assertThat(claims.subject()).isEqualTo("42");
|
||||
assertThat(claims.expiration()).isAfter(claims.issuedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsesRefreshToken() {
|
||||
String token = tokenProvider.createRefreshToken(7L);
|
||||
var claims = tokenProvider.parse(token);
|
||||
assertThat(claims.subject()).isEqualTo("7");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:h2:mem:aplp-test;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DEFAULT_NULL_ORDERING=HIGH
|
||||
username: sa
|
||||
password:
|
||||
driver-class-name: org.h2.Driver
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
flyway:
|
||||
enabled: true
|
||||
|
||||
app:
|
||||
jwt:
|
||||
secret: dGVzdC1vbmx5LXNlY3JldC1rZXktc2hvdWxkLWJlLWxvbmctZW5vdWdoLWZvci1oczI1Ni0xMjM0NTY3ODkw
|
||||
access-token-ttl: 15m
|
||||
refresh-token-ttl: 30d
|
||||
Reference in New Issue
Block a user