diff --git a/backend/.gitattributes b/backend/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..8af972cded0d3e3ccb3c6e801150168bcc93150a --- /dev/null +++ b/backend/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c2065bc26202b2d072aca3efc3d1c2efad3afcbf --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e6907e4296e738bfbffac427c20bd69a106dedf9 --- /dev/null +++ b/backend/Dockerfile @@ -0,0 +1,10 @@ +FROM eclipse-temurin:17-jdk AS build +WORKDIR /app +COPY . . +RUN ./gradlew bootJar --no-daemon + +FROM eclipse-temurin:17-jre +WORKDIR /app +COPY --from=build /app/build/libs/*.jar app.jar +EXPOSE 8080 +ENTRYPOINT ["java", "-jar", "app.jar"] diff --git a/backend/build.gradle b/backend/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..deebb251d9d432555972af3699b631fd3c6ed063 --- /dev/null +++ b/backend/build.gradle @@ -0,0 +1,32 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.4.4' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'kisbe32' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-data-rest' + implementation 'org.springframework.boot:spring-boot-starter-actuator' + runtimeOnly 'org.postgresql:postgresql' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/backend/gradle/wrapper/gradle-wrapper.jar b/backend/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..9bbc975c742b298b441bfb90dbc124400a3751b9 Binary files /dev/null and b/backend/gradle/wrapper/gradle-wrapper.jar differ diff --git a/backend/gradle/wrapper/gradle-wrapper.properties b/backend/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..37f853b1c84d2e2dd1c88441fcc755d7f6643668 --- /dev/null +++ b/backend/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/backend/gradlew b/backend/gradlew new file mode 100755 index 0000000000000000000000000000000000000000..faf93008b77e7b52e18c44e4eef257fc2f8fd76d --- /dev/null +++ b/backend/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed 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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +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 + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/backend/gradlew.bat b/backend/gradlew.bat new file mode 100644 index 0000000000000000000000000000000000000000..9d21a21834d5195c278ba17baec3115b2aaab06e --- /dev/null +++ b/backend/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem 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, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/backend/settings.gradle b/backend/settings.gradle new file mode 100644 index 0000000000000000000000000000000000000000..0f5036dcc20c98777024d86546cd03aa9307dedd --- /dev/null +++ b/backend/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'backend' diff --git a/backend/src/main/java/kisbe32/backend/AuthController.java b/backend/src/main/java/kisbe32/backend/AuthController.java new file mode 100644 index 0000000000000000000000000000000000000000..e396a83b1d668139ba961a2bc71fadabf647a7de --- /dev/null +++ b/backend/src/main/java/kisbe32/backend/AuthController.java @@ -0,0 +1,30 @@ +package kisbe32.backend; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@CrossOrigin // Enable CORS for all origins +public class AuthController { + + @Autowired + private UserRepository userRepository; + + @PostMapping("/login") + public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest request) { + User user = userRepository.findByUsername(request.getUsername()); + + // Simple string comparison for password + if (user != null && user.getPassword().equals(request.getPassword())) { + return ResponseEntity.ok(new LoginResponse(true, user.getId(), user.getUsername())); + } else { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .body(new LoginResponse(false, null, null)); + } + } +} \ No newline at end of file diff --git a/backend/src/main/java/kisbe32/backend/BackendApplication.java b/backend/src/main/java/kisbe32/backend/BackendApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..89448d855fbf887e1ae0461f296c5007b5d3c2ba --- /dev/null +++ b/backend/src/main/java/kisbe32/backend/BackendApplication.java @@ -0,0 +1,27 @@ +package kisbe32.backend; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.rest.core.config.RepositoryRestConfiguration; +import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@SpringBootApplication +public class BackendApplication { + public static void main(String[] args) { + SpringApplication.run(BackendApplication.class, args); + } +} + +// Optional: Configure the REST API to expose IDs +@Component +class RestConfig implements RepositoryRestConfigurer { + @Override + public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) { + // Expose entity IDs in REST responses + config.exposeIdsFor(User.class, Product.class, Order.class, OrderItem.class); + } +} \ No newline at end of file diff --git a/backend/src/main/java/kisbe32/backend/LoginRequest.java b/backend/src/main/java/kisbe32/backend/LoginRequest.java new file mode 100644 index 0000000000000000000000000000000000000000..26aa511843c9c40f6065ae7e2ecd4e710e62c572 --- /dev/null +++ b/backend/src/main/java/kisbe32/backend/LoginRequest.java @@ -0,0 +1,41 @@ +package kisbe32.backend; + +class LoginRequest { + private String username; + private String password; + + // Default constructor needed for JSON deserialization + public LoginRequest() {} + + public LoginRequest(String username, String password) { + this.username = username; + this.password = password; + } + + public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } + + public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } +} + +class LoginResponse { + private boolean success; + private Integer userId; + private String username; + + public LoginResponse(boolean success, Integer userId, String username) { + this.success = success; + this.userId = userId; + this.username = username; + } + + public boolean isSuccess() { return success; } + public void setSuccess(boolean success) { this.success = success; } + + public Integer getUserId() { return userId; } + public void setUserId(Integer userId) { this.userId = userId; } + + public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } +} \ No newline at end of file diff --git a/backend/src/main/java/kisbe32/backend/OrderItemRepository.java b/backend/src/main/java/kisbe32/backend/OrderItemRepository.java new file mode 100644 index 0000000000000000000000000000000000000000..1447349652f7882ebf8a763274e0e14f171c6f68 --- /dev/null +++ b/backend/src/main/java/kisbe32/backend/OrderItemRepository.java @@ -0,0 +1,16 @@ +package kisbe32.backend; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +import java.util.List; + +@RepositoryRestResource(collectionResourceRel = "orderitems", path = "orderitems") +interface OrderItemRepository extends JpaRepository<OrderItem, Integer> { + // Find order items by order ID + List<OrderItem> findByOrderId(@Param("orderId") Integer orderId); + + // Find order items by product ID + List<OrderItem> findByProductId(@Param("productId") Integer productId); +} diff --git a/backend/src/main/java/kisbe32/backend/OrderRepository.java b/backend/src/main/java/kisbe32/backend/OrderRepository.java new file mode 100644 index 0000000000000000000000000000000000000000..3ed2633070e0cffd352c824391eaefc521521e5e --- /dev/null +++ b/backend/src/main/java/kisbe32/backend/OrderRepository.java @@ -0,0 +1,16 @@ +package kisbe32.backend; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +import java.util.List; + +@RepositoryRestResource(collectionResourceRel = "orders", path = "orders") +interface OrderRepository extends JpaRepository<Order, Integer> { + // Find orders by user ID + List<Order> findByUserId(@Param("userId") Integer userId); + + // Find orders by status + List<Order> findByStatus(@Param("status") String status); +} diff --git a/backend/src/main/java/kisbe32/backend/ProductRepository.java b/backend/src/main/java/kisbe32/backend/ProductRepository.java new file mode 100644 index 0000000000000000000000000000000000000000..2494bc1df4adf193a06766978fbc285e3d4ff737 --- /dev/null +++ b/backend/src/main/java/kisbe32/backend/ProductRepository.java @@ -0,0 +1,19 @@ +package kisbe32.backend; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +import java.util.List; + +@RepositoryRestResource(collectionResourceRel = "products", path = "products") +interface ProductRepository extends JpaRepository<Product, Integer> { + // Find products by category + List<Product> findByCategory(@Param("category") String category); + + // Find products with stock greater than a given amount + List<Product> findByStockGreaterThan(@Param("stock") Integer stock); + + // Find products within a price range + List<Product> findByPriceBetween(@Param("min") java.math.BigDecimal min, @Param("max") java.math.BigDecimal max); +} diff --git a/backend/src/main/java/kisbe32/backend/User.java b/backend/src/main/java/kisbe32/backend/User.java index b2fbba21cb48c97c673eb2d082e81ad33b85ea1c..5d0139f2a032c008a43e69d938e623a19fe4ef3a 100644 --- a/backend/src/main/java/kisbe32/backend/User.java +++ b/backend/src/main/java/kisbe32/backend/User.java @@ -1,41 +1,40 @@ package kisbe32.backend; -import jakarta.persistence.*; -import java.time.LocalDateTime; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "users") public class User { @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE) - @Column(name = "id", nullable = false) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; - - @Column(name = "username", nullable = false, length = 50, unique = true) private String username; - - @Column(name = "email", nullable = false, length = 100, unique = true) private String email; - - @Column(name = "password", nullable = false, length = 255) private String password; - @Column(name = "created_at") - private LocalDateTime createdAt; - - protected User() {} + // Default constructor required by JPA + public User() {} public User(String username, String email, String password) { this.username = username; this.email = email; this.password = password; - this.createdAt = LocalDateTime.now(); } - // Getters + // Getters and setters public Integer getId() { return id; } + public void setId(Integer id) { this.id = id; } + public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } + public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } + public String getPassword() { return password; } - public LocalDateTime getCreatedAt() { return createdAt; } + public void setPassword(String password) { this.password = password; } } \ No newline at end of file diff --git a/backend/src/main/java/kisbe32/backend/UserRepository.java b/backend/src/main/java/kisbe32/backend/UserRepository.java new file mode 100644 index 0000000000000000000000000000000000000000..11146dffd97da45521fef7bee8476416cf83a4d6 --- /dev/null +++ b/backend/src/main/java/kisbe32/backend/UserRepository.java @@ -0,0 +1,9 @@ +package kisbe32.backend; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository extends JpaRepository<User, Integer> { + User findByUsername(String username); +} \ No newline at end of file diff --git a/backend/src/main/java/kisbe32/backend/WebConfig.java b/backend/src/main/java/kisbe32/backend/WebConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..826898c66b4d0a84951b967fd179116184bb02d2 --- /dev/null +++ b/backend/src/main/java/kisbe32/backend/WebConfig.java @@ -0,0 +1,15 @@ +package kisbe32.backend; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") // Allow all endpoints + .allowedOrigins("*") + .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS"); + } +} \ No newline at end of file diff --git a/backend/src/main/resources/application.properties b/backend/src/main/resources/application.properties new file mode 100644 index 0000000000000000000000000000000000000000..f975b96cfebfce46dcb1d0ec5ac183ce5d87ba97 --- /dev/null +++ b/backend/src/main/resources/application.properties @@ -0,0 +1,9 @@ +spring.application.name=backend + +spring.datasource.url=jdbc:postgresql://jokaiter.duckdns.org:34821/szofttech_project +spring.datasource.username=szofttech_project +spring.datasource.password=Utopia_Gown_Duo4 +spring.jpa.hibernate.ddl-auto=update +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect + +spring.data.rest.base-path=/api \ No newline at end of file diff --git a/backend/src/test/java/kisbe32/backend/ApiIntegrationTest.java b/backend/src/test/java/kisbe32/backend/ApiIntegrationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..6003157042681a295212f13c13b692cb0283216d --- /dev/null +++ b/backend/src/test/java/kisbe32/backend/ApiIntegrationTest.java @@ -0,0 +1,126 @@ +package kisbe32.backend; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.*; +import org.springframework.test.context.ActiveProfiles; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +public class ApiIntegrationTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Autowired + private ProductRepository productRepository; + + @Autowired + private UserRepository userRepository; + + @Autowired + private OrderRepository orderRepository; + + @Autowired + private OrderItemRepository orderItemRepository; + + @Test + public void testGetProducts() { + // Given: Add test products + Product product1 = new Product("Product 1", "Description 1", new BigDecimal("10.99"), 5, "Category 1"); + Product product2 = new Product("Product 2", "Description 2", new BigDecimal("15.99"), 10, "Category 2"); + productRepository.saveAll(List.of(product1, product2)); + + // When: Request is made to get all products + ResponseEntity<Map<String, Object>> response = restTemplate.exchange( + "/api/products", + HttpMethod.GET, + null, + new ParameterizedTypeReference<Map<String, Object>>() {} + ); + + // Then: The response should contain products + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getBody()).isNotNull(); + List<Map<String, Object>> products = (List<Map<String, Object>>) response.getBody().get("_embedded"); + assertThat(products).isNotEmpty(); + } + + @Test + public void testCreateOrderAndOrderItems() { + // Given: A user and products exist + User user = new User("testuser", "test@example.com", "password"); + userRepository.save(user); + + Product product = new Product("Test Product", "Description", new BigDecimal("19.99"), 20, "Test Category"); + productRepository.save(product); + + // When: Create an order + Map<String, Object> orderRequest = new HashMap<>(); + orderRequest.put("userId", user.getId()); + orderRequest.put("status", "PENDING"); + + ResponseEntity<Map> orderResponse = restTemplate.postForEntity( + "/api/orders", orderRequest, Map.class); + + // Then: The order should be created + assertThat(orderResponse.getStatusCode()).isEqualTo(HttpStatus.CREATED); + String orderLocation = orderResponse.getHeaders().getLocation().toString(); + + // When: Create an order item + Map<String, Object> orderItemRequest = new HashMap<>(); + orderItemRequest.put("orderId", getIdFromLocation(orderLocation)); + orderItemRequest.put("productId", product.getId()); + orderItemRequest.put("quantity", 2); + orderItemRequest.put("price", product.getPrice()); + + ResponseEntity<Map> orderItemResponse = restTemplate.postForEntity( + "/api/orderitems", orderItemRequest, Map.class); + + // Then: The order item should be created + assertThat(orderItemResponse.getStatusCode()).isEqualTo(HttpStatus.CREATED); + } + + @Test + public void testLogin() { + // Given: A user exists + String username = "loginuser"; + String password = "password123"; + User user = new User(username, "login@example.com", password); + userRepository.save(user); + + // When: Login with valid credentials + AuthController.LoginRequest loginRequest = new AuthController.LoginRequest(username, password); + + ResponseEntity<AuthController.LoginResponse> response = restTemplate.postForEntity( + "/api/login", loginRequest, AuthController.LoginResponse.class); + + // Then: Should get successful response + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getBody().isSuccess()).isTrue(); + assertThat(response.getBody().getUserId()).isEqualTo(user.getId()); + + // When: Login with invalid password + loginRequest.setPassword("wrongpassword"); + ResponseEntity<AuthController.LoginResponse> failedResponse = restTemplate.postForEntity( + "/api/login", loginRequest, AuthController.LoginResponse.class); + + // Then: Should get unauthorized response + assertThat(failedResponse.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(failedResponse.getBody().isSuccess()).isFalse(); + } + + private Integer getIdFromLocation(String location) { + return Integer.parseInt(location.substring(location.lastIndexOf("/") + 1)); + } +} \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2ae14cbc0d3170cafd956f1d094515d7d3033c80 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,43 @@ +version: '3.8' +services: + backend: + build: ./backend + ports: + - "8080:8080" + environment: + - SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/szofttech_project + - SPRING_DATASOURCE_USERNAME=szofttech_project + - SPRING_DATASOURCE_PASSWORD=Utopia_Gown_Duo4 + - SPRING_JPA_HIBERNATE_DDL_AUTO=update + depends_on: + - db + networks: + - app-network + + frontend: + build: ./frontend + ports: + - "80:80" + depends_on: + - backend + networks: + - app-network + + db: + image: postgres:17 + ports: + - "5432:5432" + environment: + - POSTGRES_DB=szofttech_project + - POSTGRES_USER=szofttech_project + - POSTGRES_PASSWORD=Utopia_Gown_Duo4 + volumes: + - postgres-data:/var/lib/postgresql/data + networks: + - app-network + +networks: + app-network: + +volumes: + postgres-data: diff --git a/frontend/.idea/vcs.xml b/frontend/.idea/vcs.xml index 94a25f7f4cb416c083d265558da75d457237d671..288b36b1efb71c411d5c27a1ea6c08e41a7fed46 100644 --- a/frontend/.idea/vcs.xml +++ b/frontend/.idea/vcs.xml @@ -1,6 +1,7 @@ <?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="VcsDirectoryMappings"> + <mapping directory="$PROJECT_DIR$/.." vcs="Git" /> <mapping directory="$PROJECT_DIR$" vcs="Git" /> </component> </project> \ No newline at end of file diff --git a/frontend/Dockerfile b/frontend/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c448e2faead19eca30ff602c21901b8b52d2cbb1 --- /dev/null +++ b/frontend/Dockerfile @@ -0,0 +1,27 @@ +# Build stage +FROM node:lts-alpine as build-stage +WORKDIR /app +COPY package*.json ./ +RUN npm install +COPY . . +RUN npm run build + +# Production stage +FROM nginx:stable-alpine as production-stage +COPY --from=build-stage /app/dist /usr/share/nginx/html +# Create nginx config to handle SPA routing and API proxying +RUN echo 'server { \ + listen 80; \ + location / { \ + root /usr/share/nginx/html; \ + index index.html; \ + try_files $uri $uri/ /index.html; \ + } \ + location /api/ { \ + proxy_pass http://backend:8080/api/; \ + proxy_set_header Host $host; \ + proxy_set_header X-Real-IP $remote_addr; \ + } \ +}' > /etc/nginx/conf.d/default.conf +EXPOSE 80 +CMD ["nginx", "-g", "daemon off;"] diff --git a/frontend/src/components/Cart.vue b/frontend/src/components/Cart.vue index 3ab48ccd739a1800dde2c2b3c3478917d7f1f1d1..27b444358d623a9cdd446d56cc945d935ba1959c 100644 --- a/frontend/src/components/Cart.vue +++ b/frontend/src/components/Cart.vue @@ -3,6 +3,7 @@ import { ref, computed, onMounted } from 'vue'; import cartStore from '../stores/cartStore.js'; import axios from 'axios'; import { defineEmits } from 'vue'; +import {API_BASE_URL} from "@/config/api.js"; const emit = defineEmits(['navigate']); @@ -59,7 +60,7 @@ async function checkout() { })) }; - const response = await axios.post('http://localhost:3000/orders', orderData, { + const response = await axios.post(`${API_BASE_URL}/orders`, orderData, { headers: { Authorization: `Bearer ${token}` } diff --git a/frontend/src/components/Login.vue b/frontend/src/components/Login.vue index 8445158305b7668bfa08f89f96205ed6cbe74825..b99afe7d239592139e8fd1f1a185830b8818327e 100644 --- a/frontend/src/components/Login.vue +++ b/frontend/src/components/Login.vue @@ -1,6 +1,7 @@ <script setup> import { defineEmits, ref } from 'vue' import axios from "axios"; +import { API_BASE_URL } from "@/config/api.js"; const emit = defineEmits(['navigate']) @@ -14,7 +15,7 @@ async function onLogin() { error.value = '' isLoading.value = true - const response = await axios.post('http://localhost:3000/login', { + const response = await axios.post(`${API_BASE_URL}/login`, { username: username.value, password: password.value }); diff --git a/frontend/src/components/MainContent.vue b/frontend/src/components/MainContent.vue index 0a8d24225f588bacc89dfde3506913e811433293..ac91181d540c2e472fd1c65da4b46037e507d9b9 100644 --- a/frontend/src/components/MainContent.vue +++ b/frontend/src/components/MainContent.vue @@ -2,6 +2,7 @@ import { ref, computed, onMounted } from 'vue'; import axios from 'axios'; import cartStore from '../stores/cartStore.js' +import {API_BASE_URL} from "@/config/api.js"; function goToCart() { emit('navigate', 'cart') @@ -95,7 +96,7 @@ const fetchProducts = async () => { error.value = null; // Itt történik az API hívás a backend felé - const response = await axios.get('http://localhost:3000/products'); + const response = await axios.get(`${API_BASE_URL}/products`); // Az adatbázisból érkező adatok formázása products.value = response.data.map(product => ({ diff --git a/frontend/src/components/Orders.vue b/frontend/src/components/Orders.vue index 49b16eb2f017bea267a062cedda4be1f69298492..8413367092c85099bc3e740ed27dc04f56aaf3a4 100644 --- a/frontend/src/components/Orders.vue +++ b/frontend/src/components/Orders.vue @@ -1,6 +1,7 @@ <script setup> import { ref, onMounted } from 'vue' import axios from 'axios' +import {API_BASE_URL} from "@/config/api.js"; const emit = defineEmits(['navigate']) const orders = ref([]) @@ -23,7 +24,7 @@ async function fetchOrders() { return } - const response = await axios.get('http://localhost:3000/user/orders', { + const response = await axios.get(`${API_BASE_URL}/orders`, { headers: { Authorization: `Bearer ${token}` } diff --git a/frontend/src/components/Register.vue b/frontend/src/components/Register.vue index ab6f3ccd79369dbf0c6a84dc994874f2cf465eb2..76f08d8e5f177a77059fa03096e8f7fe065dfbe9 100644 --- a/frontend/src/components/Register.vue +++ b/frontend/src/components/Register.vue @@ -1,6 +1,7 @@ <script setup> import { defineEmits, ref } from 'vue' import axios from "axios"; +import {API_BASE_URL} from "@/config/api.js"; const emit = defineEmits(['navigate']) @@ -21,7 +22,7 @@ async function onRegister() { error.value = '' isLoading.value = true - const response = await axios.post('http://localhost:3000/register', { + const response = await axios.post(`${API_BASE_URL}/register`, { username: username.value, password: password.value }); diff --git a/frontend/src/config/api.js b/frontend/src/config/api.js new file mode 100644 index 0000000000000000000000000000000000000000..b7e6565cc77d603eca20e802973d9161e593c33f --- /dev/null +++ b/frontend/src/config/api.js @@ -0,0 +1 @@ +export const API_BASE_URL = 'http://localhost:8080/api'; \ No newline at end of file diff --git a/frontend/vite.config.js b/frontend/vite.config.js index 19477912fddec499053a37c203133537c367fc78..4eafdcac1e6470bb8b4c143dbbb805cb0bbb18c1 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -18,9 +18,8 @@ export default defineConfig({ server: { proxy: { '/api': { - target: 'http://localhost:5000', - changeOrigin: true, - secure: false + target: 'http://localhost:8080', + changeOrigin: true } } }