Merge pull request #45 from ricardo-campos-org/feat/43-setup-and-authentication
feat: setup and authentication
@@ -27,10 +27,10 @@ jobs:
|
||||
${{ runner.os }}-node-
|
||||
|
||||
- name: Clean and Install
|
||||
run: npm ci
|
||||
run: cd client && npm ci
|
||||
- name: Build
|
||||
run: npm run build
|
||||
run: cd client && npm run build
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
run: cd client && npm run lint
|
||||
#- name: Unit tests
|
||||
# run: npm run test
|
||||
|
||||
@@ -22,10 +22,10 @@ jobs:
|
||||
with:
|
||||
node-version: '20'
|
||||
- name: Clean and Install
|
||||
run: npm ci
|
||||
run: cd client && npm ci
|
||||
- name: Build
|
||||
run: npm run build
|
||||
run: cd client && npm run build
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
run: cd client && npm run lint
|
||||
#- name: Unit tests
|
||||
# run: npm run test
|
||||
|
||||
@@ -18,11 +18,11 @@ jobs:
|
||||
with:
|
||||
node-version: '20'
|
||||
- name: Clean and Install
|
||||
run: npm ci
|
||||
run: cd client && npm ci
|
||||
- name: Build
|
||||
run: npm run build
|
||||
run: cd client && npm run build
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
run: cd client && npm run lint
|
||||
#- name: Unit tests
|
||||
# run: npm run test
|
||||
|
||||
@@ -44,6 +44,7 @@ jobs:
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
push: true
|
||||
context: ./client
|
||||
tags: rmcampos/tasknote:${{ github.event.number }}
|
||||
build-args: BUILD=${{ github.event.number }}
|
||||
cache-from: type=gha
|
||||
|
||||
@@ -24,3 +24,9 @@ yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
.env
|
||||
|
||||
# Local PG data
|
||||
/localpgdata
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
|
||||
@@ -32,8 +32,8 @@ TODO: add GIF or screenshot of the app
|
||||
## 🚀 Tech Stack
|
||||
|
||||
- **Frontend:** React, Typescript, Vite, Vitest, Code Coverage
|
||||
- **Backend:** Node.js
|
||||
- **Database:** PostgreSQL
|
||||
- **Backend:** Java 17, Spring Web, GraalVM Cloud Native Image
|
||||
- **Database:** PostgreSQL, Flyway
|
||||
- **Other Technologies:** Docker, Docker Compose, Caddy
|
||||
|
||||
## 🛠 Installation
|
||||
@@ -51,6 +51,95 @@ TODO: add GIF or screenshot of the app
|
||||
npm start
|
||||
```
|
||||
|
||||
## 🏃♀️ Running locally
|
||||
|
||||
### Locally without Docker
|
||||
|
||||
**Client:**
|
||||
|
||||
```sh
|
||||
cd client
|
||||
npm install
|
||||
npm start
|
||||
```
|
||||
|
||||
**Java API:**
|
||||
```sh
|
||||
cd java-api
|
||||
./mvnw spring-boot:run \
|
||||
-Dspring-boot.run.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005"
|
||||
```
|
||||
|
||||
PS: You have the option to define four environment variables for the database connection. In case
|
||||
you decide not to do, they'll be set to default. They are:
|
||||
|
||||
```
|
||||
POSTGRES_HOST=localhost
|
||||
POSTGRES_DB=tasknote
|
||||
POSTGRES_USER=tasknoteuser
|
||||
POSTGRES_PASSWORD=default
|
||||
```
|
||||
|
||||
PS2: Java API needs a running database to work. You can leverage Docker Compose for this, running
|
||||
this command:
|
||||
|
||||
```sh
|
||||
docker-compose up --profile dev postgres -d
|
||||
```
|
||||
|
||||
**Checking if it's running:**
|
||||
|
||||
- You can head to the Actuator Health page at: http://localhost:8585/actuator/health
|
||||
- And you want, you can open up the Swagger UI at: http://localhost:8585/swagger-ui/index.html
|
||||
|
||||
### Locally with Docker Compose
|
||||
**All at once:**
|
||||
```sh
|
||||
docker compose --profile dev up -d
|
||||
```
|
||||
|
||||
**Cleaning up:**
|
||||
```sh
|
||||
docker compose --profile dev down --remove-orphans
|
||||
```
|
||||
|
||||
## 🦾 Automation
|
||||
|
||||
### Client
|
||||
|
||||
Unit tests: Client relies on these libraries:
|
||||
- React-Testing-Library
|
||||
- Vitest
|
||||
|
||||
Here's how you can run locally:
|
||||
|
||||
```sh
|
||||
cd client
|
||||
npm run test
|
||||
```
|
||||
|
||||
**Integration tests**
|
||||
|
||||
Not available.
|
||||
|
||||
**Code style enforcement**
|
||||
|
||||
Here, ESlint, Airbnb
|
||||
|
||||
### Java API
|
||||
|
||||
**Unit tests**
|
||||
|
||||
Here
|
||||
|
||||
**Integration tests**
|
||||
|
||||
Here
|
||||
|
||||
**Code style enforcement**
|
||||
|
||||
Google Checkstyle
|
||||
|
||||
## 🎮 Usage
|
||||
|
||||
Once you're in the home screen, you can click the button to create your first TODO item.
|
||||
|
||||
|
Before Width: | Height: | Size: 39 KiB After Width: | Height: | Size: 39 KiB |
|
Before Width: | Height: | Size: 182 KiB After Width: | Height: | Size: 182 KiB |
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 35 KiB |
|
Before Width: | Height: | Size: 831 B After Width: | Height: | Size: 831 B |
|
Before Width: | Height: | Size: 2.2 KiB After Width: | Height: | Size: 2.2 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 1.1 MiB |
|
Before Width: | Height: | Size: 235 KiB After Width: | Height: | Size: 235 KiB |
|
Before Width: | Height: | Size: 113 KiB After Width: | Height: | Size: 113 KiB |
@@ -1,10 +1,8 @@
|
||||
---
|
||||
|
||||
services:
|
||||
tasknote:
|
||||
client:
|
||||
container_name: tasknote
|
||||
profiles:
|
||||
- "dev"
|
||||
image: node:20.17-bullseye-slim
|
||||
ports:
|
||||
- "5000:5000"
|
||||
@@ -18,6 +16,53 @@ services:
|
||||
healthcheck:
|
||||
test: timeout 10s bash -c 'true > /dev/tcp/127.0.0.1/3000'
|
||||
|
||||
java-api:
|
||||
container_name: java-api
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_started
|
||||
environment:
|
||||
POSTGRES_DB: tasknote
|
||||
POSTGRES_HOST: postgres
|
||||
POSTGRES_USER: tasknoteuser
|
||||
POSTGRES_PASSWORD: default
|
||||
POSTGRES_PORT: 5432
|
||||
ports:
|
||||
- "8585:8585"
|
||||
- "5005:5005"
|
||||
image: maven:3.9.9-eclipse-temurin-17
|
||||
entrypoint: sh -c './encora-cert.sh'
|
||||
working_dir: /app
|
||||
volumes:
|
||||
- "./java-api:/app"
|
||||
- $HOME/zscaler-certs:/certs
|
||||
healthcheck:
|
||||
test: curl -f http://localhost:8585/actuator/health | grep '"status":"UP"'
|
||||
interval: 1m30s
|
||||
timeout: 30s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
|
||||
postgres:
|
||||
container_name: postgres
|
||||
image: postgres:15.8-bookworm
|
||||
environment:
|
||||
POSTGRES_DB: tasknote
|
||||
POSTGRES_HOST: postgres
|
||||
POSTGRES_USER: tasknoteuser
|
||||
POSTGRES_PASSWORD: default
|
||||
POSTGRES_PORT: 5432
|
||||
volumes:
|
||||
- "/pgdata"
|
||||
ports:
|
||||
- "5432:5432"
|
||||
healthcheck:
|
||||
test: psql -q -U $${POSTGRES_USER} -d $${POSTGRES_DB} -c 'SELECT 1'
|
||||
interval: 1m30s
|
||||
timeout: 15s
|
||||
retries: 3
|
||||
start_period: 15s
|
||||
|
||||
caddy:
|
||||
container_name: caddy
|
||||
profiles:
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
HELP.md
|
||||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**/target/
|
||||
!**/src/test/**/target/
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
build/
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
@@ -0,0 +1,19 @@
|
||||
# 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
|
||||
#
|
||||
# https://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.
|
||||
wrapperVersion=3.3.2
|
||||
distributionType=only-script
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Import certificates - Needed by Encora ZScaler VPN
|
||||
if [ -f "/certs/ziaroot.crt" ]; then
|
||||
keytool -import -trustcacerts -file /certs/ziaroot.crt -keystore $JAVA_HOME/lib/security/cacerts -storepass changeit -noprompt
|
||||
fi
|
||||
|
||||
if [ -f "/certs/zscaler-ca.crt" ]; then
|
||||
keytool -import -trustcacerts -file /certs/zscaler-ca.crt -keystore $JAVA_HOME/lib/security/cacerts -storepass changeit -noprompt
|
||||
fi
|
||||
|
||||
mvn -ntp spring-boot:run \
|
||||
-Dspring-boot.run.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=*:5005" \
|
||||
-Dmaven.plugin.validation=VERBOSE
|
||||
@@ -0,0 +1,259 @@
|
||||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Apache Maven Wrapper startup batch script, version 3.3.2
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
|
||||
# MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
set -euf
|
||||
[ "${MVNW_VERBOSE-}" != debug ] || set -x
|
||||
|
||||
# OS specific support.
|
||||
native_path() { printf %s\\n "$1"; }
|
||||
case "$(uname)" in
|
||||
CYGWIN* | MINGW*)
|
||||
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
|
||||
native_path() { cygpath --path --windows "$1"; }
|
||||
;;
|
||||
esac
|
||||
|
||||
# set JAVACMD and JAVACCMD
|
||||
set_java_home() {
|
||||
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
|
||||
if [ -n "${JAVA_HOME-}" ]; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
JAVACCMD="$JAVA_HOME/jre/sh/javac"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
JAVACCMD="$JAVA_HOME/bin/javac"
|
||||
|
||||
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
|
||||
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
|
||||
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
JAVACMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v java
|
||||
)" || :
|
||||
JAVACCMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v javac
|
||||
)" || :
|
||||
|
||||
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
|
||||
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# hash string like Java String::hashCode
|
||||
hash_string() {
|
||||
str="${1:-}" h=0
|
||||
while [ -n "$str" ]; do
|
||||
char="${str%"${str#?}"}"
|
||||
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
|
||||
str="${str#?}"
|
||||
done
|
||||
printf %x\\n $h
|
||||
}
|
||||
|
||||
verbose() { :; }
|
||||
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
|
||||
|
||||
die() {
|
||||
printf %s\\n "$1" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
trim() {
|
||||
# MWRAPPER-139:
|
||||
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
|
||||
# Needed for removing poorly interpreted newline sequences when running in more
|
||||
# exotic environments such as mingw bash on Windows.
|
||||
printf "%s" "${1}" | tr -d '[:space:]'
|
||||
}
|
||||
|
||||
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
|
||||
while IFS="=" read -r key value; do
|
||||
case "${key-}" in
|
||||
distributionUrl) distributionUrl=$(trim "${value-}") ;;
|
||||
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
|
||||
esac
|
||||
done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties"
|
||||
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties"
|
||||
|
||||
case "${distributionUrl##*/}" in
|
||||
maven-mvnd-*bin.*)
|
||||
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
|
||||
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
|
||||
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
|
||||
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
|
||||
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
|
||||
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
|
||||
*)
|
||||
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
|
||||
distributionPlatform=linux-amd64
|
||||
;;
|
||||
esac
|
||||
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
|
||||
;;
|
||||
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
|
||||
*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
|
||||
esac
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<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
|
||||
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url"
|
||||
mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
|
||||
|
||||
clean || :
|
||||
exec_maven "$@"
|
||||
@@ -0,0 +1,149 @@
|
||||
<# : batch portion
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM https://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Apache Maven Wrapper startup batch script, version 3.3.2
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
|
||||
@SET __MVNW_CMD__=
|
||||
@SET __MVNW_ERROR__=
|
||||
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
|
||||
@SET PSModulePath=
|
||||
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
|
||||
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
|
||||
)
|
||||
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
|
||||
@SET __MVNW_PSMODULEP_SAVE=
|
||||
@SET __MVNW_ARG0_NAME__=
|
||||
@SET MVNW_USERNAME=
|
||||
@SET MVNW_PASSWORD=
|
||||
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
|
||||
@echo Cannot start maven from wrapper >&2 && exit /b 1
|
||||
@GOTO :EOF
|
||||
: end batch / begin powershell #>
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
if ($env:MVNW_VERBOSE -eq "true") {
|
||||
$VerbosePreference = "Continue"
|
||||
}
|
||||
|
||||
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
|
||||
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
|
||||
if (!$distributionUrl) {
|
||||
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
}
|
||||
|
||||
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
|
||||
"maven-mvnd-*" {
|
||||
$USE_MVND = $true
|
||||
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
|
||||
$MVN_CMD = "mvnd.cmd"
|
||||
break
|
||||
}
|
||||
default {
|
||||
$USE_MVND = $false
|
||||
$MVN_CMD = $script -replace '^mvnw','mvn'
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
if ($env:MVNW_REPOURL) {
|
||||
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
|
||||
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
|
||||
}
|
||||
$distributionUrlName = $distributionUrl -replace '^.*/',''
|
||||
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
|
||||
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
|
||||
if ($env:MAVEN_USER_HOME) {
|
||||
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
|
||||
}
|
||||
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
|
||||
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
|
||||
|
||||
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
|
||||
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
exit $?
|
||||
}
|
||||
|
||||
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
|
||||
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
|
||||
}
|
||||
|
||||
# prepare tmp dir
|
||||
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
|
||||
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
|
||||
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
|
||||
trap {
|
||||
if ($TMP_DOWNLOAD_DIR.Exists) {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
}
|
||||
|
||||
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
|
||||
|
||||
# Download and Install Apache Maven
|
||||
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
Write-Verbose "Downloading from: $distributionUrl"
|
||||
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
$webclient = New-Object System.Net.WebClient
|
||||
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
|
||||
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
|
||||
}
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
|
||||
if ($distributionSha256Sum) {
|
||||
if ($USE_MVND) {
|
||||
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
|
||||
}
|
||||
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
|
||||
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
|
||||
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
|
||||
}
|
||||
}
|
||||
|
||||
# unzip and move
|
||||
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
|
||||
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
|
||||
try {
|
||||
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
|
||||
} catch {
|
||||
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
|
||||
Write-Error "fail to move MAVEN_HOME"
|
||||
}
|
||||
} finally {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
@@ -0,0 +1,167 @@
|
||||
<?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>3.3.3</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<groupId>br.com.tasknoteapp</groupId>
|
||||
<artifactId>java-api</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>java-api</name>
|
||||
<description>Java backend REST API to serve TaskNote frontend client</description>
|
||||
|
||||
<!-- URL -->
|
||||
<url/>
|
||||
|
||||
<!-- License -->
|
||||
<licenses>
|
||||
<license/>
|
||||
</licenses>
|
||||
|
||||
<!-- Developers -->
|
||||
<developers>
|
||||
<developer/>
|
||||
</developers>
|
||||
|
||||
<!-- Properties -->
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
</properties>
|
||||
|
||||
<!-- Dependencies -->
|
||||
<dependencies>
|
||||
|
||||
<!-- Spring -->
|
||||
<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>
|
||||
|
||||
<!-- OPs & Tools -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<!-- Database -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-database-postgresql</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Testing -->
|
||||
<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>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Documentation -->
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
<version>2.6.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Authentication -->
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-api</artifactId>
|
||||
<version>0.12.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-impl</artifactId>
|
||||
<version>0.12.6</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
<version>0.12.6</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>tasknote-api</finalName>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.hibernate.orm.tooling</groupId>
|
||||
<artifactId>hibernate-enhance-maven-plugin</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>enhance</id>
|
||||
<goals>
|
||||
<goal>enhance</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<enableLazyInitialization>true</enableLazyInitialization>
|
||||
<enableDirtyTracking>true</enableDirtyTracking>
|
||||
<enableAssociationManagement>true</enableAssociationManagement>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.graalvm.buildtools</groupId>
|
||||
<artifactId>native-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,18 @@
|
||||
package br.com.tasknoteapp.java_api;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/** Entrypoint of the Java API service application. */
|
||||
@SpringBootApplication
|
||||
public class JavaApiApplication {
|
||||
|
||||
/**
|
||||
* Main method of the application.
|
||||
*
|
||||
* @param args Additional arguments, if any.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(JavaApiApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package br.com.tasknoteapp.java_api.auth;
|
||||
|
||||
public record JwtAuthenticationResponse(String token) {}
|
||||
@@ -0,0 +1,11 @@
|
||||
package br.com.tasknoteapp.java_api.auth;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
/** This record represents a login request with user email and password. */
|
||||
@Schema(description = "Login request with user email and password.")
|
||||
public record LoginRequest(
|
||||
@Schema(description = "User email.") @Email @NotNull String email,
|
||||
@Schema(description = "User password.") @NotNull String password) {}
|
||||
@@ -0,0 +1,83 @@
|
||||
package br.com.tasknoteapp.java_api.config;
|
||||
|
||||
import br.com.tasknoteapp.java_api.filter.JwtAuthenticationFilter;
|
||||
import br.com.tasknoteapp.java_api.service.UserService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
/** This class contains security configurations. */
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@RequiredArgsConstructor
|
||||
public class SecurityConfig {
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
|
||||
/**
|
||||
* Filters a request to add security checks and configurations.
|
||||
*
|
||||
* @param http instance of HttpSecurity containing the request.
|
||||
* @return SecurityFilterChain with allowed endpoints and all configuration.
|
||||
* @throws Exception due to bad configuration possibilities.
|
||||
*/
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http.cors(Customizer.withDefaults())
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.authorizeHttpRequests(
|
||||
request ->
|
||||
request
|
||||
.requestMatchers("/auth/**")
|
||||
.permitAll()
|
||||
.requestMatchers("/rest/**")
|
||||
.authenticated()
|
||||
.requestMatchers(HttpMethod.OPTIONS, "/**")
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.permitAll())
|
||||
.sessionManagement(
|
||||
manager -> manager.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.httpBasic(AbstractHttpConfigurer::disable)
|
||||
.formLogin(AbstractHttpConfigurer::disable)
|
||||
.authenticationProvider(authenticationProvider())
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationProvider authenticationProvider() {
|
||||
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
|
||||
authProvider.setUserDetailsService(userService.userDetailsService());
|
||||
authProvider.setPasswordEncoder(passwordEncoder());
|
||||
return authProvider;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(AuthenticationConfiguration config)
|
||||
throws Exception {
|
||||
return config.getAuthenticationManager();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package br.com.tasknoteapp.java_api.config;
|
||||
|
||||
import io.swagger.v3.oas.models.Components;
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Contact;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import io.swagger.v3.oas.models.info.License;
|
||||
import io.swagger.v3.oas.models.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||
import io.swagger.v3.oas.models.security.SecurityScheme.Type;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/** This class contains the configuration for Swagger API. */
|
||||
@Configuration
|
||||
public class SwaggerConfig {
|
||||
|
||||
@Value("${br.com.tasknote.java-api.version}")
|
||||
private String nrSparBackendVersion;
|
||||
|
||||
/**
|
||||
* Gets the API OpenAPI config.
|
||||
*
|
||||
* @return OpenAPI with config.
|
||||
*/
|
||||
@Bean
|
||||
public OpenAPI apiConfig() {
|
||||
Info info = new Info();
|
||||
info.setTitle("TaskNote API");
|
||||
info.setDescription("RESTful service API to serve the TaskNote client Web App.");
|
||||
info.setVersion(nrSparBackendVersion);
|
||||
|
||||
Contact contact = new Contact();
|
||||
contact.setName("Ricardo Campos");
|
||||
contact.setEmail("ricardompcampos@gmail.com");
|
||||
contact.setUrl("https://github.com/ricardo-campos-org/react-typescript-todolist");
|
||||
info.setContact(contact);
|
||||
|
||||
License license = new License();
|
||||
license.setName("GPL 3.0");
|
||||
license.setUrl("https://www.gnu.org/licenses/gpl-3.0");
|
||||
info.setLicense(license);
|
||||
|
||||
SecurityScheme securityScheme = new SecurityScheme();
|
||||
securityScheme.setType(Type.HTTP);
|
||||
securityScheme.setScheme("bearer");
|
||||
securityScheme.setBearerFormat("JWT");
|
||||
|
||||
Components components = new Components();
|
||||
components.addSecuritySchemes("bearerAuth", securityScheme);
|
||||
|
||||
OpenAPI openApi = new OpenAPI();
|
||||
openApi.setInfo(info);
|
||||
openApi.addSecurityItem(new SecurityRequirement().addList("bearerAuth"));
|
||||
openApi.setComponents(components);
|
||||
|
||||
return openApi;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package br.com.tasknoteapp.java_api.controller;
|
||||
|
||||
import br.com.tasknoteapp.java_api.auth.JwtAuthenticationResponse;
|
||||
import br.com.tasknoteapp.java_api.auth.LoginRequest;
|
||||
import br.com.tasknoteapp.java_api.exception.UserAlreadyExistsException;
|
||||
import br.com.tasknoteapp.java_api.service.AuthService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth")
|
||||
@Tag(name = "Authentication", description = "Authentication controller.")
|
||||
@AllArgsConstructor
|
||||
public class AuthenticationController {
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
/**
|
||||
* Authenticate a user given his email and password.
|
||||
*
|
||||
* @param loginRequest User data containing email and password.
|
||||
* @return OK if authenticated, 401 - Unauthorized otherwise
|
||||
*/
|
||||
@PostMapping(path = "/signin", consumes = "application/json", produces = "application/json")
|
||||
@Operation(
|
||||
summary = "SigIn an existing user",
|
||||
description = "SigIn an existing user given his email and password",
|
||||
responses = {
|
||||
@ApiResponse(responseCode = "200", description = "User successfully logged in"),
|
||||
@ApiResponse(responseCode = "400", description = "Wrong or missing information"),
|
||||
})
|
||||
public JwtAuthenticationResponse signin(@RequestBody @Valid LoginRequest loginRequest) {
|
||||
String token = authService.signin(loginRequest);
|
||||
return new JwtAuthenticationResponse(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* Signup a new user.
|
||||
*
|
||||
* @param loginRequest User data with email and password.
|
||||
* @return JwtAuthenticationResponse containing user token
|
||||
* @throws UserAlreadyExistsException
|
||||
*/
|
||||
@PutMapping(path = "/signup", consumes = "application/json", produces = "application/json")
|
||||
@Operation(
|
||||
summary = "Signup a new user",
|
||||
description = "Signup a new user given his email and password",
|
||||
responses = {
|
||||
@ApiResponse(responseCode = "201", description = "User successfully created and saved"),
|
||||
@ApiResponse(responseCode = "400", description = "Wrong or missing information"),
|
||||
@ApiResponse(responseCode = "409", description = "User already exists")
|
||||
})
|
||||
public ResponseEntity<JwtAuthenticationResponse> signup(
|
||||
@RequestBody @Valid LoginRequest loginRequest) {
|
||||
String token = authService.create(loginRequest);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(new JwtAuthenticationResponse(token));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package br.com.tasknoteapp.java_api.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/rest/some")
|
||||
public class SomeController {
|
||||
|
||||
@GetMapping
|
||||
public String some() {
|
||||
return "Some";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package br.com.tasknoteapp.java_api.entity;
|
||||
|
||||
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.LocalDateTime;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
/** This class represents a User in the database. */
|
||||
@Data
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class UserEntity implements UserDetails {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(unique = true, nullable = false)
|
||||
private String email;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String password;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Boolean admin;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@Column(name = "inactivated_at", nullable = true)
|
||||
private LocalDateTime inactivatedAt;
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
// email in our case
|
||||
return email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package br.com.tasknoteapp.java_api.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
@ResponseStatus(code = HttpStatus.CONFLICT)
|
||||
public class UserAlreadyExistsException extends ResponseStatusException {
|
||||
|
||||
public UserAlreadyExistsException() {
|
||||
super(HttpStatus.CONFLICT, "User already exists");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package br.com.tasknoteapp.java_api.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
@ResponseStatus(code = HttpStatus.NOT_FOUND)
|
||||
public class UserNotFoundException extends ResponseStatusException {
|
||||
|
||||
public UserNotFoundException() {
|
||||
super(HttpStatus.NOT_FOUND, "User not found");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package br.com.tasknoteapp.java_api.filter;
|
||||
|
||||
import br.com.tasknoteapp.java_api.service.JwtService;
|
||||
import br.com.tasknoteapp.java_api.service.UserService;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
@Autowired private UserService userService;
|
||||
|
||||
@Autowired private JwtService jwtService;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
@NonNull HttpServletRequest request,
|
||||
@NonNull HttpServletResponse response,
|
||||
@NonNull FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
final String authorizationHeader = request.getHeader("Authorization");
|
||||
|
||||
log.info("-1-authorizationHeader {}", authorizationHeader);
|
||||
|
||||
if (Objects.isNull(authorizationHeader) || authorizationHeader.isBlank()) {
|
||||
log.info("-2-authorizationHeader {}", authorizationHeader);
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("-3-authorizationHeader {}", authorizationHeader);
|
||||
|
||||
String jwtToken = authorizationHeader.substring(7);
|
||||
String email = jwtService.getEmailFromToken(jwtToken);
|
||||
|
||||
log.info("-4-email {}", email);
|
||||
|
||||
if (!Objects.isNull(email)
|
||||
&& Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {
|
||||
log.info("-5-email {}", email);
|
||||
UserDetails user = userService.userDetailsService().loadUserByUsername(email);
|
||||
|
||||
if (jwtService.validateTokenAndUser(jwtToken, user)) {
|
||||
log.info("-6-jwtToken {}", jwtToken);
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||
|
||||
UsernamePasswordAuthenticationToken authToken =
|
||||
new UsernamePasswordAuthenticationToken(
|
||||
user.getUsername(), user.getPassword(), user.getAuthorities());
|
||||
|
||||
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
context.setAuthentication(authToken);
|
||||
SecurityContextHolder.setContext(context);
|
||||
}
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package br.com.tasknoteapp.java_api.repository;
|
||||
|
||||
import br.com.tasknoteapp.java_api.entity.UserEntity;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
/** This interface contains methods to access the user table in the database. */
|
||||
public interface UserRepository extends JpaRepository<UserEntity, Long> {
|
||||
|
||||
Optional<UserEntity> findByEmail(String email);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package br.com.tasknoteapp.java_api.service;
|
||||
|
||||
import br.com.tasknoteapp.java_api.auth.LoginRequest;
|
||||
import br.com.tasknoteapp.java_api.entity.UserEntity;
|
||||
import java.util.Optional;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
|
||||
public interface AuthService {
|
||||
|
||||
/**
|
||||
* Create a new user in the app.
|
||||
*
|
||||
* @param login User details with email and password.
|
||||
* @return Token
|
||||
*/
|
||||
public String create(LoginRequest login);
|
||||
|
||||
/**
|
||||
* Find a user by email in the database.
|
||||
*
|
||||
* @param email The user email.
|
||||
* @return Optional of a UserEntity instance.
|
||||
*/
|
||||
public Optional<UserEntity> findByEmail(String email);
|
||||
|
||||
/**
|
||||
* Load a user from the database given his email.
|
||||
*
|
||||
* @param email The user email.
|
||||
* @return User with found record.
|
||||
*/
|
||||
public User loadUserByUsername(String email);
|
||||
|
||||
/**
|
||||
* SignIn a user given his email and password.
|
||||
*
|
||||
* @param login User details with email and password.
|
||||
* @return Token
|
||||
*/
|
||||
public String signin(LoginRequest login);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package br.com.tasknoteapp.java_api.service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
public interface JwtService {
|
||||
|
||||
public String getEmailFromToken(String token);
|
||||
|
||||
public LocalDateTime extractExpiration(String token);
|
||||
|
||||
public String generateToken(String username);
|
||||
|
||||
public String createToken(Map<String, Object> claims, String email);
|
||||
|
||||
public boolean isTokenExpired(String token);
|
||||
|
||||
public boolean validateTokenAndUser(String token, UserDetails user);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package br.com.tasknoteapp.java_api.service;
|
||||
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
|
||||
public interface UserService {
|
||||
UserDetailsService userDetailsService();
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package br.com.tasknoteapp.java_api.service.impl;
|
||||
|
||||
import br.com.tasknoteapp.java_api.auth.LoginRequest;
|
||||
import br.com.tasknoteapp.java_api.entity.UserEntity;
|
||||
import br.com.tasknoteapp.java_api.exception.UserAlreadyExistsException;
|
||||
import br.com.tasknoteapp.java_api.exception.UserNotFoundException;
|
||||
import br.com.tasknoteapp.java_api.repository.UserRepository;
|
||||
import br.com.tasknoteapp.java_api.service.AuthService;
|
||||
import br.com.tasknoteapp.java_api.service.JwtService;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Optional;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
class AuthServiceImpl implements AuthService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
private final JwtService jwtService;
|
||||
|
||||
private final AuthenticationManager authenticationManager;
|
||||
|
||||
/**
|
||||
* Create a new user in the app.
|
||||
*
|
||||
* @param login User details with email and password.
|
||||
* @return Token
|
||||
*/
|
||||
@Override
|
||||
public String create(LoginRequest login) {
|
||||
log.info("Creating user! {}", login.email());
|
||||
|
||||
if (findByEmail(login.email()).isPresent()) {
|
||||
throw new UserAlreadyExistsException();
|
||||
}
|
||||
|
||||
UserEntity user = new UserEntity();
|
||||
user.setEmail(login.email());
|
||||
user.setPassword(passwordEncoder.encode(login.password()));
|
||||
user.setAdmin(login.email().equals("ricardompcampos@gmail.com"));
|
||||
user.setCreatedAt(LocalDateTime.now());
|
||||
userRepository.save(user);
|
||||
|
||||
String token = jwtService.generateToken(user.getEmail());
|
||||
|
||||
log.info("User created! Token {}", token);
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a user by email in the database.
|
||||
*
|
||||
* @param email The user email.
|
||||
* @return Optional of a UserEntity instance.
|
||||
*/
|
||||
@Override
|
||||
public Optional<UserEntity> findByEmail(String email) {
|
||||
return userRepository.findByEmail(email);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a user from the database given his email.
|
||||
*
|
||||
* @param email The user email.
|
||||
* @return User with found record.
|
||||
*/
|
||||
@Override
|
||||
public User loadUserByUsername(String email) {
|
||||
Optional<UserEntity> user = userRepository.findByEmail(email);
|
||||
if (user.isEmpty()) {
|
||||
throw new UserNotFoundException();
|
||||
}
|
||||
|
||||
return new User(user.get().getEmail(), user.get().getPassword(), new ArrayList<>());
|
||||
}
|
||||
|
||||
/**
|
||||
* SignIn a user given his email and password.
|
||||
*
|
||||
* @param login User details with email and password.
|
||||
* @return Token
|
||||
*/
|
||||
@Override
|
||||
public String signin(LoginRequest login) {
|
||||
log.info("Creating user! {}", login.email());
|
||||
|
||||
Optional<UserEntity> user = findByEmail(login.email());
|
||||
if (user.isEmpty()) {
|
||||
throw new UserNotFoundException();
|
||||
}
|
||||
|
||||
authenticationManager.authenticate(
|
||||
new UsernamePasswordAuthenticationToken(login.email(), login.password()));
|
||||
|
||||
String token = jwtService.generateToken(user.get().getEmail());
|
||||
|
||||
log.info("User authenticated! Token {}", token);
|
||||
return token;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package br.com.tasknoteapp.java_api.service.impl;
|
||||
|
||||
import br.com.tasknoteapp.java_api.service.JwtService;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import javax.crypto.SecretKey;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class JwtServiceImpl implements JwtService {
|
||||
|
||||
private final long SECOND = 1000;
|
||||
private final long MINUTE = SECOND * 60;
|
||||
private final long EXPIRATION_TIME = MINUTE * 30;
|
||||
private final SecretKey KEY = Jwts.SIG.HS256.key().build();
|
||||
|
||||
@Override
|
||||
public String getEmailFromToken(String token) {
|
||||
return extractClaim(token, Claims::getSubject);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDateTime extractExpiration(String token) {
|
||||
Date date = extractClaim(token, Claims::getExpiration);
|
||||
return date.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String generateToken(String username) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
return createToken(claims, username);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String createToken(Map<String, Object> claims, String email) {
|
||||
return Jwts.builder()
|
||||
.issuer("Java-API")
|
||||
.subject(email)
|
||||
.issuedAt(new Date(System.currentTimeMillis()))
|
||||
.expiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
|
||||
.signWith(KEY)
|
||||
.compact();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTokenExpired(String token) {
|
||||
return extractExpiration(token).isBefore(LocalDateTime.now());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean validateTokenAndUser(String token, UserDetails user) {
|
||||
final String email = user.getUsername();
|
||||
return !isTokenExpired(token) && getEmailFromToken(token).equals(email);
|
||||
}
|
||||
|
||||
private <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
|
||||
final Claims claims = extractAllClaims(token);
|
||||
return claimsResolver.apply(claims);
|
||||
}
|
||||
|
||||
private Claims extractAllClaims(String token) {
|
||||
return Jwts.parser().verifyWith(KEY).build().parseSignedClaims(token).getPayload();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package br.com.tasknoteapp.java_api.service.impl;
|
||||
|
||||
import br.com.tasknoteapp.java_api.entity.UserEntity;
|
||||
import br.com.tasknoteapp.java_api.repository.UserRepository;
|
||||
import br.com.tasknoteapp.java_api.service.UserService;
|
||||
import java.util.Optional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class UserServiceImpl implements UserService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
@Override
|
||||
public UserDetailsService userDetailsService() {
|
||||
return new UserDetailsService() {
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String email) {
|
||||
Optional<UserEntity> user = userRepository.findByEmail(email);
|
||||
if (user.isEmpty()) {
|
||||
throw new RuntimeException("User not found: " + email);
|
||||
}
|
||||
|
||||
return user.get();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
spring.application.name=java-api
|
||||
server.port = 8585
|
||||
server.error.include-message=always
|
||||
|
||||
# Actuator and ops
|
||||
management.endpoint.health.show-details=always
|
||||
|
||||
# Database, datasource and JPA
|
||||
spring.datasource.driver-class-name=org.postgresql.Driver
|
||||
spring.datasource.url=jdbc:postgresql://${POSTGRES_HOST:localhost}:5432/${POSTGRES_DB:postgres}
|
||||
spring.datasource.username=${POSTGRES_USER:postgres}
|
||||
spring.datasource.password=${POSTGRES_PASSWORD:default}
|
||||
spring.jpa.properties.hibernate.default_schema=tasknote
|
||||
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
|
||||
spring.jpa.show-sql=true
|
||||
spring.flyway.enabled=true
|
||||
spring.flyway.baseline-on-migrate=true
|
||||
spring.flyway.locations=classpath:db/migration
|
||||
|
||||
# Native Cloud
|
||||
springdoc.enable-native-support=true
|
||||
|
||||
# Version (build)
|
||||
br.com.tasknote.java-api.version=${BUILD:local}
|
||||
@@ -0,0 +1,12 @@
|
||||
CREATE SCHEMA IF NOT EXISTS tasknote;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tasknote.users (
|
||||
id SERIAL,
|
||||
email VARCHAR(100) NOT NULL,
|
||||
password VARCHAR(255) NOT NULL,
|
||||
admin BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMP NOT NULL,
|
||||
inactivated_at TIMESTAMP,
|
||||
CONSTRAINT users_pk PRIMARY KEY (id),
|
||||
CONSTRAINT users_email_uk UNIQUE (email)
|
||||
);
|
||||
@@ -0,0 +1,13 @@
|
||||
package br.com.tasknoteapp.java_api;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class JavaApiApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||