commit 62e9918af521a338651a04f4080f0d7a559b2847 Author: wangli Date: Mon Mar 2 21:16:34 2026 +0000 first commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..667aaef --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..8dea6c2 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.12/apache-maven-3.9.12-bin.zip diff --git a/docs/development_guide.md b/docs/development_guide.md new file mode 100644 index 0000000..883a99f --- /dev/null +++ b/docs/development_guide.md @@ -0,0 +1,72 @@ +# CSC8019 Backend Development Guide + +This guide provides a comprehensive overview of the standards and best practices for developing in the CSC8019-backend project. + +## 1. API Standards + +### Unified Response Format (`Result`) +All Controller methods MUST return the `Result` wrapper to ensure a consistent response structure across the entire API. + +- **Structure**: + - `code`: Status code (e.g., 200 for success, 500 for error, 401 for unauthorized). + - `message`: Descriptive message. + - `data`: The actual payload (generic type `T`). + +- **Example Usage**: +```java +@GetMapping("/hello") +public Result hello() { + return Result.success("Success Data"); +} +``` + +## 2. Global Exception Handling + +The project uses a global exception handler (`GlobalExceptionHandler`) to intercept and format errors. + +- **`CustomException`**: Use this for business logic errors. It takes a `ResultCode` or a specific message. +- **Auto-handling**: Spring Security exceptions (401, 403) and general system exceptions (500) are automatically caught and returned in the `Result` format. + +## 3. JPA Usage Guide + +We follow a layered architectural pattern for data access. + +### 1. Entity Module +Define your data models in the `entity` package using JPA annotations. +```java +@Entity +@Data +public class MyEntity { + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String name; +} +``` + +### 2. Repository Module +Extend `JpaRepository` for standard CRUD operations. Place these in the `repository` package. +```java +@Repository +public interface MyRepository extends JpaRepository { +} +``` + +### 3. Service Module +Always use an interface and an implementation class (`impl` package). +- **Interface**: Define the business contract. +- **Impl**: Implement the logic and inject the Repository. + +## 4. Security Annotations + +The project uses custom annotations for Role-Based Access Control (RBAC): + +- `@IsStaff`: Restricts access to users with the `STAFF` role. +- `@IsClient`: Restricts access to users with the `CLIENT` role. + +Place these annotations on Controller methods or classes that require authorization. + +## 5. Module Structure + +The `business` package is organized by functional domain (e.g., `menu`, `order`, `store`). Each domain should follow the `controller` -> `service` -> `repository` hierarchy. + +Example: `uk.ac.ncl.csc8019backend.business.menu.controller` diff --git a/docs/login_guide.md b/docs/login_guide.md new file mode 100644 index 0000000..8af8200 --- /dev/null +++ b/docs/login_guide.md @@ -0,0 +1,66 @@ +# User Login and API Call Guide + +This guide describes how to authenticate and use JWT tokens to call protected API endpoints. + +## 1. Authentication (Login) + +Send a `POST` request to the `/api/auth/login` endpoint with your credentials. + +- **URL**: `http://localhost:8080/api/auth/login` +- **Method**: `POST` +- **Body (JSON)**: +```json +{ + "username": "your_username", + "password": "your_password" +} +``` + +### Response Example +If successful, you will receive a response containing the token: +```json +{ + "code": 200, + "message": "Login successful", + "data": { + "token": "eyJhbGciOiJIUzI1NiJ9...", + "tokenHead": "Bearer " + } +} +``` + +## 2. Calling Protected Endpoints + +For any subsequent requests to protected endpoints (e.g., `/api/staff/hello`), you must include the token in the `Authorization` header. + +- **Header Name**: `Authorization` +- **Header Value**: `Bearer ` + +### Example using cURL +```bash +curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..." http://localhost:8080/api/staff/hello +``` + +### Example Response (Authorized) +```json +{ + "code": 200, + "message": "Success", + "data": "Hello from staff-only endpoint!" +} +``` + +### Example Response (Unauthorized/Missing Token) +```json +{ + "code": 401, + "message": "Unauthorized", + "data": null +} +``` + +## 3. Role-Based Access + +- **STAFF Only**: Endpoints annotated with `@IsStaff` require a token from a user with the `STAFF` role. +- **CLIENT Only**: Endpoints annotated with `@IsClient` require a token from a user with the `CLIENT` role. +- **Public**: Endpoints starting with `/api/public/` do not require a token. diff --git a/mvnw b/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..76839f8 --- /dev/null +++ b/pom.xml @@ -0,0 +1,122 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.11 + + + uk.ac.ncl + CSC8019-backend + 0.0.1-SNAPSHOT + CSC8019-backend + CSC8019-backend + + + + + + + + + + + + + + + 17 + + + + com.baomidou + mybatis-plus-spring-boot3-starter + 3.5.10.1 + + + com.baomidou + mybatis-plus-jsqlparser + 3.5.10.1 + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + com.mysql + mysql-connector-j + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + io.jsonwebtoken + jjwt-api + 0.12.6 + + + io.jsonwebtoken + jjwt-impl + 0.12.6 + runtime + + + io.jsonwebtoken + jjwt-jackson + 0.12.6 + runtime + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/sql/demo.sql b/sql/demo.sql new file mode 100644 index 0000000..aa62819 --- /dev/null +++ b/sql/demo.sql @@ -0,0 +1,11 @@ +-- DDL for demo table +CREATE TABLE IF NOT EXISTS `demo` ( + `id` BIGINT AUTO_INCREMENT PRIMARY KEY, + `name` VARCHAR(255) NOT NULL, + `description` TEXT, + `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- Sample data +INSERT INTO `demo` (`name`, `description`) VALUES ('Demo Item 1', 'Selection from the demo table'); +INSERT INTO `demo` (`name`, `description`) VALUES ('Demo Item 2', 'Another example record'); diff --git a/sql/security.sql b/sql/security.sql new file mode 100644 index 0000000..cf158d6 --- /dev/null +++ b/sql/security.sql @@ -0,0 +1,13 @@ +-- Create users table +CREATE TABLE IF NOT EXISTS `users` ( + `id` BIGINT NOT NULL AUTO_INCREMENT, + `username` VARCHAR(255) NOT NULL, + `password` VARCHAR(255) NOT NULL, + `role` VARCHAR(50) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `UK_username` (`username`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- Sample data (password is '123456' hashed with BCrypt) +-- INSERT INTO `users` (username, password, role) VALUES ('admin', '$2a$10$XlV.q.7.q.q.q.q.q.q.q.q.q.q.q.q.q.q.q.q.q.q.q.q.q.', 'STAFF'); +-- INSERT INTO `users` (username, password, role) VALUES ('user', '$2a$10$XlV.q.7.q.q.q.q.q.q.q.q.q.q.q.q.q.q.q.q.q.q.q.q.q.q.', 'CLIENT'); diff --git a/src/main/java/uk/ac/ncl/csc8019backend/Csc8019BackendApplication.java b/src/main/java/uk/ac/ncl/csc8019backend/Csc8019BackendApplication.java new file mode 100644 index 0000000..1296449 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/Csc8019BackendApplication.java @@ -0,0 +1,14 @@ +package uk.ac.ncl.csc8019backend; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Csc8019BackendApplication { + + public static void main(String[] args) { + SpringApplication.run(Csc8019BackendApplication.class, args); + } + +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/demo/controller/DemoController.java b/src/main/java/uk/ac/ncl/csc8019backend/business/demo/controller/DemoController.java new file mode 100644 index 0000000..92b9646 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/business/demo/controller/DemoController.java @@ -0,0 +1,34 @@ +package uk.ac.ncl.csc8019backend.business.demo.controller; + +import org.springframework.web.bind.annotation.*; +import uk.ac.ncl.csc8019backend.business.demo.entity.Demo; +import uk.ac.ncl.csc8019backend.business.demo.service.DemoService; +import uk.ac.ncl.csc8019backend.system.common.Result; + +import java.util.List; + +@RestController +@RequestMapping("/api/demo") +public class DemoController { + + private final DemoService demoService; + + public DemoController(DemoService demoService) { + this.demoService = demoService; + } + + @GetMapping("/list") + public Result> list() { + return Result.success(demoService.getAllDemos()); + } + + @GetMapping("/{id}") + public Result get(@PathVariable Long id) { + return Result.success(demoService.getDemoById(id)); + } + + @PostMapping("/create") + public Result create(@RequestBody Demo demo) { + return Result.success(demoService.createDemo(demo)); + } +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/demo/entity/Demo.java b/src/main/java/uk/ac/ncl/csc8019backend/business/demo/entity/Demo.java new file mode 100644 index 0000000..6ea39a4 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/business/demo/entity/Demo.java @@ -0,0 +1,18 @@ +package uk.ac.ncl.csc8019backend.business.demo.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +@TableName("demo") +@Data +public class Demo { + + @TableId(type = IdType.AUTO) + private Long id; + + private String name; + + private String description; +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/demo/repository/DemoRepository.java b/src/main/java/uk/ac/ncl/csc8019backend/business/demo/repository/DemoRepository.java new file mode 100644 index 0000000..5edaae3 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/business/demo/repository/DemoRepository.java @@ -0,0 +1,9 @@ +package uk.ac.ncl.csc8019backend.business.demo.repository; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import uk.ac.ncl.csc8019backend.business.demo.entity.Demo; + +@Mapper +public interface DemoRepository extends BaseMapper { +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/demo/service/DemoService.java b/src/main/java/uk/ac/ncl/csc8019backend/business/demo/service/DemoService.java new file mode 100644 index 0000000..915a0ce --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/business/demo/service/DemoService.java @@ -0,0 +1,10 @@ +package uk.ac.ncl.csc8019backend.business.demo.service; + +import uk.ac.ncl.csc8019backend.business.demo.entity.Demo; +import java.util.List; + +public interface DemoService { + List getAllDemos(); + Demo getDemoById(Long id); + Demo createDemo(Demo demo); +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/demo/service/impl/DemoServiceImpl.java b/src/main/java/uk/ac/ncl/csc8019backend/business/demo/service/impl/DemoServiceImpl.java new file mode 100644 index 0000000..c69b692 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/business/demo/service/impl/DemoServiceImpl.java @@ -0,0 +1,43 @@ +package uk.ac.ncl.csc8019backend.business.demo.service.impl; + +import org.springframework.stereotype.Service; +import uk.ac.ncl.csc8019backend.business.demo.entity.Demo; +import uk.ac.ncl.csc8019backend.business.demo.repository.DemoRepository; +import uk.ac.ncl.csc8019backend.business.demo.service.DemoService; +import uk.ac.ncl.csc8019backend.system.exception.CustomException; + +import java.util.List; + +@Service +public class DemoServiceImpl implements DemoService { + + private final DemoRepository demoRepository; + + public DemoServiceImpl(DemoRepository demoRepository) { + this.demoRepository = demoRepository; + } + + @Override + public List getAllDemos() { + return demoRepository.selectList(null); + } + + @Override + public Demo getDemoById(Long id) { + Demo demo = demoRepository.selectById(id); + if (demo == null) { + throw new CustomException("Demo data not found with id: " + id); + } + return demo; + } + + @Override + public Demo createDemo(Demo demo) { + if (demo.getId() == null) { + demoRepository.insert(demo); + } else { + demoRepository.updateById(demo); + } + return demo; + } +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/loyalty/controller/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/loyalty/controller/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/loyalty/entity/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/loyalty/entity/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/loyalty/repository/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/loyalty/repository/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/loyalty/service/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/loyalty/service/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/menu/controller/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/menu/controller/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/menu/entity/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/menu/entity/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/menu/repository/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/menu/repository/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/menu/service/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/menu/service/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/onlinepayment/controller/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/onlinepayment/controller/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/onlinepayment/entity/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/onlinepayment/entity/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/onlinepayment/repository/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/onlinepayment/repository/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/onlinepayment/service/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/onlinepayment/service/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/order/controller/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/order/controller/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/order/entity/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/order/entity/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/order/repository/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/order/repository/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/order/service/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/order/service/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/raildata/controller/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/raildata/controller/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/raildata/entity/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/raildata/entity/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/raildata/repository/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/raildata/repository/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/raildata/service/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/raildata/service/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/store/controller/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/store/controller/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/store/controller/StoreController.java b/src/main/java/uk/ac/ncl/csc8019backend/business/store/controller/StoreController.java new file mode 100644 index 0000000..420ff8f --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/business/store/controller/StoreController.java @@ -0,0 +1,36 @@ +package uk.ac.ncl.csc8019backend.business.store.controller; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import uk.ac.ncl.csc8019backend.business.store.dto.StoreDTO; +import uk.ac.ncl.csc8019backend.business.store.dto.StoreQueryDTO; +import uk.ac.ncl.csc8019backend.business.store.entity.Store; +import uk.ac.ncl.csc8019backend.business.store.service.IStoreService; +import uk.ac.ncl.csc8019backend.system.common.Result; + +@RestController +@RequestMapping("/api/store") +public class StoreController { + + @Autowired + private IStoreService storeService; + + @GetMapping("/list") + public Result> list(StoreQueryDTO queryDTO) { + IPage stores = storeService.listStorePage(queryDTO); + return Result.success(stores); + } + + @PostMapping("/add") + public Result add(@RequestBody StoreDTO storeDTO) { + storeService.saveStore(storeDTO); + return Result.success(); + } + + @PostMapping("/update") + public Result update(@RequestBody StoreDTO storeDTO) { + storeService.updateStore(storeDTO); + return Result.success(); + } +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/store/dto/StoreDTO.java b/src/main/java/uk/ac/ncl/csc8019backend/business/store/dto/StoreDTO.java new file mode 100644 index 0000000..da381d3 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/business/store/dto/StoreDTO.java @@ -0,0 +1,22 @@ +package uk.ac.ncl.csc8019backend.business.store.dto; + +import lombok.Data; + +import java.util.List; + +@Data +public class StoreDTO { + private Integer id; + private String name; + private String sequence; + private String location; + private List openingHours; + + @Data + public static class OpeningHour { + private Boolean isOpen; + private String openTime; + private String closeTime; + private Integer dateIndex; + } +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/store/dto/StoreQueryDTO.java b/src/main/java/uk/ac/ncl/csc8019backend/business/store/dto/StoreQueryDTO.java new file mode 100644 index 0000000..91872d0 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/business/store/dto/StoreQueryDTO.java @@ -0,0 +1,10 @@ +package uk.ac.ncl.csc8019backend.business.store.dto; + +import lombok.Data; + +@Data +public class StoreQueryDTO { + private String name; + private Long pageNum = 1L; + private Long pageSize = 10L; +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/store/entity/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/store/entity/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/store/entity/Store.java b/src/main/java/uk/ac/ncl/csc8019backend/business/store/entity/Store.java new file mode 100644 index 0000000..e8562b2 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/business/store/entity/Store.java @@ -0,0 +1,19 @@ +package uk.ac.ncl.csc8019backend.business.store.entity; + + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +@Data +@TableName("store") +public class Store { + @TableId(type = IdType.AUTO) + private Integer id; + private String sequence; + private String name; + private String location; + private String openingTime; + +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/store/repository/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/store/repository/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/store/repository/StoreMapper.java b/src/main/java/uk/ac/ncl/csc8019backend/business/store/repository/StoreMapper.java new file mode 100644 index 0000000..7ed650a --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/business/store/repository/StoreMapper.java @@ -0,0 +1,10 @@ +package uk.ac.ncl.csc8019backend.business.store.repository; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import uk.ac.ncl.csc8019backend.business.store.entity.Store; + +@Mapper +public interface StoreMapper extends BaseMapper { + +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/store/service/.gitkeep b/src/main/java/uk/ac/ncl/csc8019backend/business/store/service/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/store/service/IStoreService.java b/src/main/java/uk/ac/ncl/csc8019backend/business/store/service/IStoreService.java new file mode 100644 index 0000000..1fd2bdf --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/business/store/service/IStoreService.java @@ -0,0 +1,20 @@ +package uk.ac.ncl.csc8019backend.business.store.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.IService; +import uk.ac.ncl.csc8019backend.business.store.dto.StoreDTO; +import uk.ac.ncl.csc8019backend.business.store.dto.StoreQueryDTO; +import uk.ac.ncl.csc8019backend.business.store.entity.Store; + +import java.util.List; + +public interface IStoreService extends IService { + + List listAllStore(); + + IPage listStorePage(StoreQueryDTO queryDTO); + + void saveStore(StoreDTO storeDTO); + + void updateStore(StoreDTO storeDTO); +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/business/store/service/impl/StoreServiceImpl.java b/src/main/java/uk/ac/ncl/csc8019backend/business/store/service/impl/StoreServiceImpl.java new file mode 100644 index 0000000..405f1be --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/business/store/service/impl/StoreServiceImpl.java @@ -0,0 +1,78 @@ +package uk.ac.ncl.csc8019backend.business.store.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import uk.ac.ncl.csc8019backend.business.store.dto.StoreDTO; +import uk.ac.ncl.csc8019backend.business.store.dto.StoreQueryDTO; +import uk.ac.ncl.csc8019backend.business.store.entity.Store; +import uk.ac.ncl.csc8019backend.business.store.repository.StoreMapper; +import uk.ac.ncl.csc8019backend.business.store.service.IStoreService; + +import java.util.List; + +@Service +public class StoreServiceImpl extends ServiceImpl implements IStoreService { + + @Autowired + private ObjectMapper objectMapper; + + @Override + public List listAllStore(){ + return this.list(); + } + + @Override + public IPage listStorePage(StoreQueryDTO queryDTO) { + Page page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize()); + LambdaQueryWrapper qw = new LambdaQueryWrapper<>(); + qw.like(StringUtils.hasText(queryDTO.getName()), Store::getName, queryDTO.getName()); + qw.orderByAsc(Store::getSequence); + return this.page(page, qw); + } + + @Override + public void saveStore(StoreDTO storeDTO) { + Store store = new Store(); + store.setName(storeDTO.getName()); + store.setSequence(storeDTO.getSequence()); + store.setLocation(storeDTO.getLocation()); + + if (storeDTO.getOpeningHours() != null) { + try { + String openingTime = objectMapper.writeValueAsString(storeDTO.getOpeningHours()); + store.setOpeningTime(openingTime); + } catch (JsonProcessingException e) { + throw new RuntimeException("Failed to serialize opening hours", e); + } + } + + this.save(store); + } + + @Override + public void updateStore(StoreDTO storeDTO) { + Store store = new Store(); + store.setId(storeDTO.getId()); + store.setName(storeDTO.getName()); + store.setSequence(storeDTO.getSequence()); + store.setLocation(storeDTO.getLocation()); + + if (storeDTO.getOpeningHours() != null) { + try { + String openingTime = objectMapper.writeValueAsString(storeDTO.getOpeningHours()); + store.setOpeningTime(openingTime); + } catch (JsonProcessingException e) { + throw new RuntimeException("Failed to serialize opening hours", e); + } + } + + this.updateById(store); + } +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/annotation/IsClient.java b/src/main/java/uk/ac/ncl/csc8019backend/system/annotation/IsClient.java new file mode 100644 index 0000000..f44b128 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/annotation/IsClient.java @@ -0,0 +1,14 @@ +package uk.ac.ncl.csc8019backend.system.annotation; + +import org.springframework.security.access.prepost.PreAuthorize; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@PreAuthorize("hasRole('CLIENT')") +public @interface IsClient { +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/annotation/IsStaff.java b/src/main/java/uk/ac/ncl/csc8019backend/system/annotation/IsStaff.java new file mode 100644 index 0000000..9ac2392 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/annotation/IsStaff.java @@ -0,0 +1,14 @@ +package uk.ac.ncl.csc8019backend.system.annotation; + +import org.springframework.security.access.prepost.PreAuthorize; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@PreAuthorize("hasRole('STAFF')") +public @interface IsStaff { +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/common/Result.java b/src/main/java/uk/ac/ncl/csc8019backend/system/common/Result.java new file mode 100644 index 0000000..867be38 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/common/Result.java @@ -0,0 +1,54 @@ +package uk.ac.ncl.csc8019backend.system.common; + +import lombok.Data; + +@Data +public class Result { + private int code; + private String message; + private T data; + + protected Result() {} + + protected Result(int code, String message, T data) { + this.code = code; + this.message = message; + this.data = data; + } + + public static Result success() { + return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), null); + } + + public static Result success(T data) { + return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data); + } + + public static Result success(T data, String message) { + return new Result<>(ResultCode.SUCCESS.getCode(), message, data); + } + + public static Result failed() { + return new Result<>(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMessage(), null); + } + + public static Result failed(String message) { + return new Result<>(ResultCode.FAILED.getCode(), message, null); + } + + public static Result failed(int code, String message) { + return new Result<>(code, message, null); + } + + public static Result failed(ResultCode resultCode) { + return new Result<>(resultCode.getCode(), resultCode.getMessage(), null); + } + + public static Result unauthorized() { + return new Result<>(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage(), null); + } + + public static Result forbidden() { + return new Result<>(ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage(), null); + } +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/common/ResultCode.java b/src/main/java/uk/ac/ncl/csc8019backend/system/common/ResultCode.java new file mode 100644 index 0000000..a5504e6 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/common/ResultCode.java @@ -0,0 +1,21 @@ +package uk.ac.ncl.csc8019backend.system.common; + +import lombok.Getter; + +@Getter +public enum ResultCode { + SUCCESS(200, "Success"), + ERROR(500, "Internal Server Error"), + UNAUTHORIZED(401, "Unauthorized"), + FORBIDDEN(403, "Forbidden"), + VALIDATE_FAILED(404, "Not Found"), + FAILED(500, "Failed"); + + private final int code; + private final String message; + + ResultCode(int code, String message) { + this.code = code; + this.message = message; + } +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/controller/AuthController.java b/src/main/java/uk/ac/ncl/csc8019backend/system/controller/AuthController.java new file mode 100644 index 0000000..fa07990 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/controller/AuthController.java @@ -0,0 +1,45 @@ +package uk.ac.ncl.csc8019backend.system.controller; + +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import uk.ac.ncl.csc8019backend.system.common.Result; +import uk.ac.ncl.csc8019backend.system.dto.LoginRequest; +import uk.ac.ncl.csc8019backend.system.security.JwtUtils; + +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("/api/auth") +public class AuthController { + + private final AuthenticationManager authenticationManager; + private final JwtUtils jwtUtils; + + public AuthController(AuthenticationManager authenticationManager, JwtUtils jwtUtils) { + this.authenticationManager = authenticationManager; + this.jwtUtils = jwtUtils; + } + + @PostMapping("/login") + public Result> login(@RequestBody LoginRequest loginRequest) { + Authentication authentication = authenticationManager.authenticate( + new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()) + ); + + UserDetails userDetails = (UserDetails) authentication.getPrincipal(); + String token = jwtUtils.generateToken(userDetails); + + Map data = new HashMap<>(); + data.put("token", token); + data.put("tokenHead", "Bearer "); + + return Result.success(data, "Login successful"); + } +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/dto/LoginRequest.java b/src/main/java/uk/ac/ncl/csc8019backend/system/dto/LoginRequest.java new file mode 100644 index 0000000..8dc70f3 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/dto/LoginRequest.java @@ -0,0 +1,9 @@ +package uk.ac.ncl.csc8019backend.system.dto; + +import lombok.Data; + +@Data +public class LoginRequest { + private String username; + private String password; +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/entity/Role.java b/src/main/java/uk/ac/ncl/csc8019backend/system/entity/Role.java new file mode 100644 index 0000000..6bf1ae7 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/entity/Role.java @@ -0,0 +1,6 @@ +package uk.ac.ncl.csc8019backend.system.entity; + +public enum Role { + STAFF, + CLIENT +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/entity/User.java b/src/main/java/uk/ac/ncl/csc8019backend/system/entity/User.java new file mode 100644 index 0000000..d208839 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/entity/User.java @@ -0,0 +1,30 @@ +package uk.ac.ncl.csc8019backend.system.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@TableName("users") +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class User { + + @TableId(type = IdType.AUTO) + private Long id; + + @TableField("username") + private String username; + + @TableField("password") + private String password; + + @TableField("role") + private Role role; +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/exception/CustomException.java b/src/main/java/uk/ac/ncl/csc8019backend/system/exception/CustomException.java new file mode 100644 index 0000000..e5d30e6 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/exception/CustomException.java @@ -0,0 +1,24 @@ +package uk.ac.ncl.csc8019backend.system.exception; + +import lombok.Getter; +import uk.ac.ncl.csc8019backend.system.common.ResultCode; + +@Getter +public class CustomException extends RuntimeException { + private final ResultCode resultCode; + + public CustomException(String message) { + super(message); + this.resultCode = ResultCode.FAILED; + } + + public CustomException(ResultCode resultCode) { + super(resultCode.getMessage()); + this.resultCode = resultCode; + } + + public CustomException(ResultCode resultCode, String message) { + super(message); + this.resultCode = resultCode; + } +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/exception/GlobalExceptionHandler.java b/src/main/java/uk/ac/ncl/csc8019backend/system/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..2654bf6 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/exception/GlobalExceptionHandler.java @@ -0,0 +1,38 @@ +package uk.ac.ncl.csc8019backend.system.exception; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import uk.ac.ncl.csc8019backend.system.common.Result; +import uk.ac.ncl.csc8019backend.system.common.ResultCode; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(CustomException.class) + public Result handleCustomException(CustomException e) { + log.error("Business Exception: {}", e.getMessage()); + return Result.failed(e.getResultCode().getCode(), e.getMessage()); + } + + @ExceptionHandler(AccessDeniedException.class) + public Result handleAccessDeniedException(AccessDeniedException e) { + log.error("Access Denied: {}", e.getMessage()); + return Result.forbidden(); + } + + @ExceptionHandler(AuthenticationException.class) + public Result handleAuthenticationException(AuthenticationException e) { + log.error("Authentication Failed: {}", e.getMessage()); + return Result.unauthorized(); + } + + @ExceptionHandler(Exception.class) + public Result handleException(Exception e) { + log.error("Global Exception: ", e); + return Result.failed(ResultCode.ERROR); + } +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/repository/UserRepository.java b/src/main/java/uk/ac/ncl/csc8019backend/system/repository/UserRepository.java new file mode 100644 index 0000000..62186f3 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/repository/UserRepository.java @@ -0,0 +1,15 @@ +package uk.ac.ncl.csc8019backend.system.repository; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import uk.ac.ncl.csc8019backend.system.entity.User; + +import java.util.Optional; + +@Mapper +public interface UserRepository extends BaseMapper { + default Optional findByUsername(String username) { + return Optional.ofNullable(this.selectOne(new LambdaQueryWrapper().eq(User::getUsername, username))); + } +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/security/CustomUserDetailsService.java b/src/main/java/uk/ac/ncl/csc8019backend/system/security/CustomUserDetailsService.java new file mode 100644 index 0000000..c8efade --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/security/CustomUserDetailsService.java @@ -0,0 +1,33 @@ +package uk.ac.ncl.csc8019backend.system.security; + +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import uk.ac.ncl.csc8019backend.system.entity.User; +import uk.ac.ncl.csc8019backend.system.repository.UserRepository; + +import java.util.Collections; + +@Service +public class CustomUserDetailsService implements UserDetailsService { + + private final UserRepository userRepository; + + public CustomUserDetailsService(UserRepository userRepository) { + this.userRepository = userRepository; + } + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + User user = userRepository.findByUsername(username) + .orElseThrow(() -> new UsernameNotFoundException("User not found with username: " + username)); + + return new org.springframework.security.core.userdetails.User( + user.getUsername(), + user.getPassword(), + Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + user.getRole().name())) + ); + } +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/security/JwtAuthenticationFilter.java b/src/main/java/uk/ac/ncl/csc8019backend/system/security/JwtAuthenticationFilter.java new file mode 100644 index 0000000..ae65050 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/security/JwtAuthenticationFilter.java @@ -0,0 +1,58 @@ +package uk.ac.ncl.csc8019backend.system.security; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@Component +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + private final JwtUtils jwtUtils; + private final CustomUserDetailsService userDetailsService; + + public JwtAuthenticationFilter(JwtUtils jwtUtils, CustomUserDetailsService userDetailsService) { + this.jwtUtils = jwtUtils; + this.userDetailsService = userDetailsService; + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + + final String authHeader = request.getHeader("Authorization"); + final String jwt; + final String username; + + if (authHeader == null || !authHeader.startsWith("Bearer ")) { + filterChain.doFilter(request, response); + return; + } + + jwt = authHeader.substring(7); + username = jwtUtils.extractUsername(jwt); + + if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { + UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); + + if (jwtUtils.validateToken(jwt, userDetails)) { + UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken( + userDetails, + null, + userDetails.getAuthorities() + ); + authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + SecurityContextHolder.getContext().setAuthentication(authToken); + } + } + filterChain.doFilter(request, response); + } +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/security/JwtUtils.java b/src/main/java/uk/ac/ncl/csc8019backend/system/security/JwtUtils.java new file mode 100644 index 0000000..79129b2 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/security/JwtUtils.java @@ -0,0 +1,75 @@ +package uk.ac.ncl.csc8019backend.system.security; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import java.nio.charset.StandardCharsets; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +@Component +public class JwtUtils { + + @Value("${jwt.secret}") + private String secret; + + @Value("${jwt.expiration}") + private Long expiration; + + private SecretKey getSigningKey() { + byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8); + return Keys.hmacShaKeyFor(keyBytes); + } + + public String generateToken(UserDetails userDetails) { + Map claims = new HashMap<>(); + return createToken(claims, userDetails.getUsername()); + } + + private String createToken(Map claims, String subject) { + return Jwts.builder() + .claims(claims) + .subject(subject) + .issuedAt(new Date(System.currentTimeMillis())) + .expiration(new Date(System.currentTimeMillis() + expiration)) + .signWith(getSigningKey()) + .compact(); + } + + public Boolean validateToken(String token, UserDetails userDetails) { + final String username = extractUsername(token); + return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)); + } + + public String extractUsername(String token) { + return extractClaim(token, Claims::getSubject); + } + + public Date extractExpiration(String token) { + return extractClaim(token, Claims::getExpiration); + } + + public T extractClaim(String token, Function claimsResolver) { + final Claims claims = extractAllClaims(token); + return claimsResolver.apply(claims); + } + + private Claims extractAllClaims(String token) { + return Jwts.parser() + .verifyWith(getSigningKey()) + .build() + .parseSignedClaims(token) + .getPayload(); + } + + private Boolean isTokenExpired(String token) { + return extractExpiration(token).before(new Date()); + } +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/security/MybatisPlusConfig.java b/src/main/java/uk/ac/ncl/csc8019backend/system/security/MybatisPlusConfig.java new file mode 100644 index 0000000..52d6532 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/security/MybatisPlusConfig.java @@ -0,0 +1,18 @@ +package uk.ac.ncl.csc8019backend.system.security; + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class MybatisPlusConfig { + + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); + interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); + return interceptor; + } +} diff --git a/src/main/java/uk/ac/ncl/csc8019backend/system/security/SecurityConfig.java b/src/main/java/uk/ac/ncl/csc8019backend/system/security/SecurityConfig.java new file mode 100644 index 0000000..07d4ed0 --- /dev/null +++ b/src/main/java/uk/ac/ncl/csc8019backend/system/security/SecurityConfig.java @@ -0,0 +1,52 @@ +package uk.ac.ncl.csc8019backend.system.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.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; + +@Configuration +@EnableWebSecurity +@EnableMethodSecurity +public class SecurityConfig { + + private final JwtAuthenticationFilter jwtAuthenticationFilter; + + public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter) { + this.jwtAuthenticationFilter = jwtAuthenticationFilter; + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http + .csrf(AbstractHttpConfigurer::disable) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(auth -> auth + .requestMatchers("/api/auth/login").permitAll() + .requestMatchers("/**").permitAll() + .anyRequest().authenticated() + ) + .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); + + return http.build(); + } + + @Bean + public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { + return authenticationConfiguration.getAuthenticationManager(); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..65ba950 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,17 @@ +spring: + application: + name: CSC8019-backend + datasource: + url: jdbc:mysql://database-1.cnqwmw824u8a.eu-north-1.rds.amazonaws.com:3306/democoffee?useSSL=false&serverTimezone=UTC + username: root + password: CSC8019! + driver-class-name: com.mysql.cj.jdbc.Driver +mybatis-plus: + mapper-locations: classpath*:/mapper/**/*.xml + configuration: + map-underscore-to-camel-case: true + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + +jwt: + secret: "myVerySecureAndSecretKeyForHS256AlgorithmWhichIsAtLeast32BytesLong" + expiration: 604800000 # 7 days in milliseconds diff --git a/src/test/java/uk/ac/ncl/csc8019backend/Csc8019BackendApplicationTests.java b/src/test/java/uk/ac/ncl/csc8019backend/Csc8019BackendApplicationTests.java new file mode 100644 index 0000000..3947f3c --- /dev/null +++ b/src/test/java/uk/ac/ncl/csc8019backend/Csc8019BackendApplicationTests.java @@ -0,0 +1,13 @@ +package uk.ac.ncl.csc8019backend; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Csc8019BackendApplicationTests { + + @Test + void contextLoads() { + } + +}