From 8474ae0661066322699375e3316991943b2d7037 Mon Sep 17 00:00:00 2001 From: Rohit Nandi Date: Thu, 14 Nov 2024 22:21:24 +0530 Subject: [PATCH 1/6] Dev (#20) * #8 Adds init spring-boot project * #8 Adds Instant type jackson converter * #8 Adds ApiErrorResponse * #8 Adds ApiResponse * #8 Adds ApiListResponse * #8 Adds TestBaseAuditingEntity * Feature/8 user portal part 1 (#17) * #8 Adds init spring-boot project * #8 Adds Instant type jackson converter * #8 Adds ApiErrorResponse * #8 Adds ApiResponse * #8 Adds ApiListResponse * #8 Adds TestBaseAuditingEntity * #8 Adds Event Endpoint, Auditing entity (#18) * #8 Adds AuditingEntityListener * #8 Adds BookingStatus, Genre, OperationalStatus, VendorStatus, VenueType enums * #8 Add entities Event, EventShow, EventType, Seat, SeatInShow, SeatType, SeatTypeInShow, Vendor, Venue * #8 Add getAllEvents endpoints * #8 Add test cases for getAllEvents endpoints * Resolved reviewed comments * Resolved reviewed comments * #8 Resolved reviewed comments * Refactor code to events package * Adds response layer, fix test cases. Removes sonar lints --------- Co-authored-by: damini1994 <55175815+damini1994@users.noreply.github.com> --- .../backend/java/bms-monolith/.gitattributes | 2 + .../backend/java/bms-monolith/.gitignore | 33 +++ .../.mvn/wrapper/maven-wrapper.properties | 19 ++ book-my-show/backend/java/bms-monolith/mvnw | 259 ++++++++++++++++++ .../backend/java/bms-monolith/mvnw.cmd | 149 ++++++++++ .../backend/java/bms-monolith/pom.xml | 93 +++++++ .../bms_monolith/BmsMonolithApplication.java | 13 + .../bms_monolith/common/config/JpaConfig.java | 16 ++ .../common/constants/BMSConstants.java | 14 + .../common/entity/BaseAuditingEntity.java | 52 ++++ .../bms/bms_monolith/common/entity/Event.java | 57 ++++ .../bms_monolith/common/entity/EventShow.java | 49 ++++ .../bms_monolith/common/entity/EventType.java | 21 ++ .../bms/bms_monolith/common/entity/Seat.java | 30 ++ .../common/entity/SeatInShow.java | 31 +++ .../bms_monolith/common/entity/SeatType.java | 25 ++ .../common/entity/SeatTypeInShow.java | 27 ++ .../bms_monolith/common/entity/Vendor.java | 37 +++ .../bms/bms_monolith/common/entity/Venue.java | 44 +++ .../common/enums/BookingStatus.java | 7 + .../bms/bms_monolith/common/enums/Genre.java | 9 + .../common/enums/OperationalStatus.java | 6 + .../common/enums/VendorStatus.java | 7 + .../bms_monolith/common/enums/VenueType.java | 6 + .../exception/GlobalExceptionHandler.java | 24 ++ .../common/response/ApiErrorResponse.java | 23 ++ .../common/response/ApiListResponse.java | 45 +++ .../common/response/ApiResponse.java | 22 ++ .../controller/EventController.java | 41 +++ .../eventservice/dto/EventResponse.java | 41 +++ .../eventservice/dto/EventShowResponse.java | 45 +++ .../eventservice/dto/SeatInShowResponse.java | 29 ++ .../dto/SeatTypeInShowResponse.java | 29 ++ .../exception/EventExceptionHandler.java | 19 ++ .../exception/EventServiceException.java | 8 + .../repository/IEventRepository.java | 15 + .../eventservice/service/IEventService.java | 10 + .../service/impl/EventServiceImpl.java | 35 +++ .../src/main/resources/application-test.yml | 4 + .../src/main/resources/application.yaml | 18 ++ .../BmsMonolithApplicationTests.java | 17 ++ .../common/entity/TestBaseAuditingEntity.java | 50 ++++ .../common/reponse/TestApiErrorResponse.java | 59 ++++ .../common/reponse/TestApiListResponse.java | 87 ++++++ .../common/reponse/TestApiResponse.java | 60 ++++ .../controller/EventControllerTest.java | 96 +++++++ .../service/EventServiceImplTest.java | 67 +++++ 47 files changed, 1850 insertions(+) create mode 100644 book-my-show/backend/java/bms-monolith/.gitattributes create mode 100644 book-my-show/backend/java/bms-monolith/.gitignore create mode 100644 book-my-show/backend/java/bms-monolith/.mvn/wrapper/maven-wrapper.properties create mode 100644 book-my-show/backend/java/bms-monolith/mvnw create mode 100644 book-my-show/backend/java/bms-monolith/mvnw.cmd create mode 100644 book-my-show/backend/java/bms-monolith/pom.xml create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/BmsMonolithApplication.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/config/JpaConfig.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/constants/BMSConstants.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/BaseAuditingEntity.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Event.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/EventShow.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/EventType.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Seat.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatInShow.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatType.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatTypeInShow.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Vendor.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Venue.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/BookingStatus.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/Genre.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/OperationalStatus.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/VendorStatus.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/VenueType.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/response/ApiErrorResponse.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/response/ApiListResponse.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/response/ApiResponse.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/controller/EventController.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/EventResponse.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/EventShowResponse.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatInShowResponse.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatTypeInShowResponse.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/exception/EventExceptionHandler.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/exception/EventServiceException.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/repository/IEventRepository.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/service/IEventService.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/service/impl/EventServiceImpl.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/resources/application-test.yml create mode 100644 book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml create mode 100644 book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/BmsMonolithApplicationTests.java create mode 100644 book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/entity/TestBaseAuditingEntity.java create mode 100644 book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/reponse/TestApiErrorResponse.java create mode 100644 book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/reponse/TestApiListResponse.java create mode 100644 book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/reponse/TestApiResponse.java create mode 100644 book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/controller/EventControllerTest.java create mode 100644 book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/service/EventServiceImplTest.java diff --git a/book-my-show/backend/java/bms-monolith/.gitattributes b/book-my-show/backend/java/bms-monolith/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/book-my-show/backend/java/bms-monolith/.gitignore b/book-my-show/backend/java/bms-monolith/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/.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/book-my-show/backend/java/bms-monolith/.mvn/wrapper/maven-wrapper.properties b/book-my-show/backend/java/bms-monolith/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..d58dfb7 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# 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. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/book-my-show/backend/java/bms-monolith/mvnw b/book-my-show/backend/java/bms-monolith/mvnw new file mode 100644 index 0000000..19529dd --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/book-my-show/backend/java/bms-monolith/mvnw.cmd b/book-my-show/backend/java/bms-monolith/mvnw.cmd new file mode 100644 index 0000000..249bdf3 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/book-my-show/backend/java/bms-monolith/pom.xml b/book-my-show/backend/java/bms-monolith/pom.xml new file mode 100644 index 0000000..76f9214 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/pom.xml @@ -0,0 +1,93 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.5 + + + org.lbcc.bms + bms-monolith + 0.0.1-SNAPSHOT + BMS Monolith + Monolithic application for booking and managing events + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + com.mysql + mysql-connector-j + runtime + + + org.springframework.boot + spring-boot-starter-validation + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + 2.18.0 + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/BmsMonolithApplication.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/BmsMonolithApplication.java new file mode 100644 index 0000000..f43b60d --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/BmsMonolithApplication.java @@ -0,0 +1,13 @@ +package org.lbcc.bms.bms_monolith; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BmsMonolithApplication { + + public static void main(String[] args) { + SpringApplication.run(BmsMonolithApplication.class, args); + } + +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/config/JpaConfig.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/config/JpaConfig.java new file mode 100644 index 0000000..ca00d90 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/config/JpaConfig.java @@ -0,0 +1,16 @@ +package org.lbcc.bms.bms_monolith.common.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.data.domain.AuditorAware; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +import java.util.Optional; + +@EnableJpaAuditing +public class JpaConfig { + + @Bean + public AuditorAware auditorProvider() { + return () -> Optional.of("system"); // TODO: Replace with code to fetch username when spring-security is implemented. + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/constants/BMSConstants.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/constants/BMSConstants.java new file mode 100644 index 0000000..b691851 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/constants/BMSConstants.java @@ -0,0 +1,14 @@ +package org.lbcc.bms.bms_monolith.common.constants; + +public final class BMSConstants { + + private BMSConstants() { + } + + public static final int DEFAULT_PAGE = 0; + public static final int DEFAULT_PAGE_SIZE = 50; + public static final String EVENT_SUCCESS_MESSAGE = "Events fetched successfully"; + public static final String UNEXPECTED_ERROR_MESSAGE = "An unexpected error occurred"; + public static final String UNEXPECTED_ERROR_CODE = "UNEXPECTED_ERROR"; + public static final String EVENT_SERVICE_ERROR = "EVENT_SERVICE_ERROR"; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/BaseAuditingEntity.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/BaseAuditingEntity.java new file mode 100644 index 0000000..83b1dd5 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/BaseAuditingEntity.java @@ -0,0 +1,52 @@ +package org.lbcc.bms.bms_monolith.common.entity; + +import jakarta.persistence.MappedSuperclass; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.experimental.SuperBuilder; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.Instant; +import java.util.UUID; + +@AllArgsConstructor +@Getter +@MappedSuperclass +@NoArgsConstructor +@Setter +@SuperBuilder +@EntityListeners(AuditingEntityListener.class) +public abstract class BaseAuditingEntity { + + @Id + @GeneratedValue(strategy = GenerationType.UUID) + @Column(columnDefinition = "CHAR(36)") + private UUID id; + + @CreatedDate + @Column(updatable = false) + private Instant createdDate; + + @LastModifiedDate + @Column(insertable = false) + private Instant lastModifiedDate; + + @CreatedBy + @Column(updatable = false, length = 10) + private String createdBy; + + @LastModifiedBy + @Column(insertable = false, length = 10) + private String lastModifiedBy; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Event.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Event.java new file mode 100644 index 0000000..12dbaf9 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Event.java @@ -0,0 +1,57 @@ +package org.lbcc.bms.bms_monolith.common.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToMany; +import jakarta.persistence.CascadeType; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.FetchType; +import jakarta.persistence.Column; +import jakarta.validation.constraints.Size; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.experimental.SuperBuilder; + +import java.time.Instant; +import java.util.List; + +@Entity +@Getter @Setter +@AllArgsConstructor @NoArgsConstructor +@SuperBuilder +public class Event extends BaseAuditingEntity { + + @Size(min=10, max=50, message = "Title must be between 10 and 50 characters.") + @Column(nullable = false, length = 50) + private String title; + + @Column(length = 1000) + private String description; + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "vendor_id") + private Vendor vendor; + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "venue_id") + private Venue venue; + + @OneToMany(mappedBy = "event", cascade = CascadeType.ALL) + private List show; + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "event_type_id") + private EventType eventType; + + @Column(nullable = false) + private Instant startDate; + + @Column // default 255 in length + private String thumbnailUrl; + + @Column(nullable = false) + private Instant endDate; + +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/EventShow.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/EventShow.java new file mode 100644 index 0000000..a8196e1 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/EventShow.java @@ -0,0 +1,49 @@ +package org.lbcc.bms.bms_monolith.common.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.ElementCollection; +import jakarta.persistence.CollectionTable; +import jakarta.persistence.Column; +import jakarta.persistence.Enumerated; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToMany; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.EnumType; +import jakarta.persistence.CascadeType; +import jakarta.persistence.FetchType; +import jakarta.validation.constraints.NotNull; + +import lombok.Getter; +import lombok.experimental.SuperBuilder; +import org.lbcc.bms.bms_monolith.common.enums.Genre; + +import java.time.Instant; +import java.util.List; + +@Entity +@Getter +@SuperBuilder +public class EventShow extends BaseAuditingEntity { + + @ElementCollection(targetClass = Genre.class) + @CollectionTable(name = "show_genre", joinColumns = @JoinColumn(name = "show_id")) + @Column(name = "genre") + @Enumerated(EnumType.STRING) + private List genres; + + @NotNull + private Instant startDate; + + @NotNull + private Instant endDate; + + @ManyToOne + @JoinColumn(name = "event_id", nullable = false) + private Event event; + + @OneToMany(mappedBy = "show", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private List seatInShows; + + @OneToMany(mappedBy = "show", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private List seatTypeInShows; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/EventType.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/EventType.java new file mode 100644 index 0000000..e3b4af8 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/EventType.java @@ -0,0 +1,21 @@ +package org.lbcc.bms.bms_monolith.common.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.experimental.SuperBuilder; + +@Entity +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +@SuperBuilder +public class EventType extends BaseAuditingEntity { + + @Column(length = 15) + private String label; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Seat.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Seat.java new file mode 100644 index 0000000..0673e1d --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Seat.java @@ -0,0 +1,30 @@ +package org.lbcc.bms.bms_monolith.common.entity; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.lbcc.bms.bms_monolith.common.enums.OperationalStatus; + +@Entity +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +public class Seat extends BaseAuditingEntity { + + @ManyToOne + @JoinColumn(name = "seat_type_id") + private SeatType seatType; + + @ManyToOne + @JoinColumn(name = "venue_id") + private Venue venue; + + @Enumerated(EnumType.STRING) + private OperationalStatus operationalStatus; + + @Column(length = 5) + private String label; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatInShow.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatInShow.java new file mode 100644 index 0000000..1c5851e --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatInShow.java @@ -0,0 +1,31 @@ +package org.lbcc.bms.bms_monolith.common.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.Enumerated; +import jakarta.persistence.EnumType; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.lbcc.bms.bms_monolith.common.enums.BookingStatus; + +@Entity +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +public class SeatInShow extends BaseAuditingEntity { + + @ManyToOne + @JoinColumn(name = "seat_type_in_show_id") + private SeatTypeInShow seatTypeInShow; + + @ManyToOne + @JoinColumn(name = "show_id") + private EventShow show; + + @Enumerated(EnumType.STRING) + private BookingStatus bookingStatus; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatType.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatType.java new file mode 100644 index 0000000..4a11cc2 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatType.java @@ -0,0 +1,25 @@ +package org.lbcc.bms.bms_monolith.common.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.math.BigDecimal; + +@Entity +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +public class SeatType extends BaseAuditingEntity { + + @Column(length = 15) + private String label; + + @Column(precision = 10, scale = 2) + private BigDecimal price; + +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatTypeInShow.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatTypeInShow.java new file mode 100644 index 0000000..45f7fb1 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatTypeInShow.java @@ -0,0 +1,27 @@ +package org.lbcc.bms.bms_monolith.common.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.Column; +import lombok.Getter; +import lombok.experimental.SuperBuilder; + +import java.math.BigDecimal; + +@Entity +@Getter +@SuperBuilder +public class SeatTypeInShow extends BaseAuditingEntity { + + @ManyToOne + @JoinColumn(name = "seat_type_id") + private SeatType seatType; + + @ManyToOne + @JoinColumn(name = "show_id") + private EventShow show; + + @Column(precision = 10, scale = 2) + private BigDecimal price; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Vendor.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Vendor.java new file mode 100644 index 0000000..5feef8b --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Vendor.java @@ -0,0 +1,37 @@ +package org.lbcc.bms.bms_monolith.common.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.Enumerated; +import jakarta.persistence.EnumType; +import jakarta.persistence.Column; +import jakarta.validation.constraints.Size; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.lbcc.bms.bms_monolith.common.enums.VendorStatus; + +@Entity +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +public class Vendor extends BaseAuditingEntity { + + private String name; + private String contactNumber; + private String email; + private String address; + private String website; + + @Enumerated(EnumType.STRING) + private VendorStatus status; + + @Column(nullable = true, length = 100) + @Size(min = 10, max = 100, message = "Registration date must be between 10 and 100 characters.") + private String registrationDate; + + @Column(nullable = false, length = 255) + @Size(min = 25, max = 255, message = "Logo URL must be between 25 and 255 characters.") + private String logoUrl; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Venue.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Venue.java new file mode 100644 index 0000000..3e698c7 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Venue.java @@ -0,0 +1,44 @@ +package org.lbcc.bms.bms_monolith.common.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.Enumerated; +import jakarta.persistence.EnumType; +import jakarta.persistence.CascadeType; +import jakarta.persistence.FetchType; +import jakarta.persistence.OneToMany; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.lbcc.bms.bms_monolith.common.enums.OperationalStatus; +import org.lbcc.bms.bms_monolith.common.enums.VenueType; + +import java.math.BigDecimal; +import java.util.List; + +@Entity +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +public class Venue extends BaseAuditingEntity { + + private String name; + private String address; + private BigDecimal latitude; + private BigDecimal longitude; + private Integer totalSeatingCapacity; + + @Enumerated(EnumType.STRING) + private VenueType venueType; + + @Enumerated(EnumType.STRING) + private OperationalStatus operationalStatus; + + @OneToMany(mappedBy = "venue", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @NotNull(message = "Seats list cannot be null.") + @Size(min = 1, max = 100, message = "Seats list must contain between 1 and 100 seats.") + private List seats; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/BookingStatus.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/BookingStatus.java new file mode 100644 index 0000000..e2c1e05 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/BookingStatus.java @@ -0,0 +1,7 @@ +package org.lbcc.bms.bms_monolith.common.enums; + +public enum BookingStatus { + BOOKED, + AVAILABLE, + NOT_AVAILABLE; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/Genre.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/Genre.java new file mode 100644 index 0000000..f58d2c0 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/Genre.java @@ -0,0 +1,9 @@ +package org.lbcc.bms.bms_monolith.common.enums; + +public enum Genre { + COMEDY, + DRAMA, + ACTION, + THRILLER, + HORROR; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/OperationalStatus.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/OperationalStatus.java new file mode 100644 index 0000000..5f15b49 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/OperationalStatus.java @@ -0,0 +1,6 @@ +package org.lbcc.bms.bms_monolith.common.enums; + +public enum OperationalStatus { + OPERATIONAL, + NON_OPERATIONAL; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/VendorStatus.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/VendorStatus.java new file mode 100644 index 0000000..bc6e4a8 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/VendorStatus.java @@ -0,0 +1,7 @@ +package org.lbcc.bms.bms_monolith.common.enums; + +public enum VendorStatus { + ACTIVE, + INACTIVE, + SUSPENDED; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/VenueType.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/VenueType.java new file mode 100644 index 0000000..5c5fde9 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/VenueType.java @@ -0,0 +1,6 @@ +package org.lbcc.bms.bms_monolith.common.enums; + +public enum VenueType { + AUDITORIUM, + STADIUM; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..b0de11d --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java @@ -0,0 +1,24 @@ +package org.lbcc.bms.bms_monolith.common.exception; + +import org.lbcc.bms.bms_monolith.common.constants.BMSConstants; +import org.lbcc.bms.bms_monolith.common.response.ApiErrorResponse; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +@ControllerAdvice +public class GlobalExceptionHandler { + @ExceptionHandler(Exception.class) + public ResponseEntity handleGlobalException(Exception ex) { + return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, BMSConstants.UNEXPECTED_ERROR_MESSAGE, BMSConstants.UNEXPECTED_ERROR_CODE); + } + + public static ResponseEntity buildErrorResponse(HttpStatus status, String message, String code) { + ApiErrorResponse errorResponse = ApiErrorResponse.builder() + .message(message) + .code(code) + .build(); + return ResponseEntity.status(status).body(errorResponse); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/response/ApiErrorResponse.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/response/ApiErrorResponse.java new file mode 100644 index 0000000..14d2369 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/response/ApiErrorResponse.java @@ -0,0 +1,23 @@ +package org.lbcc.bms.bms_monolith.common.response; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.Instant; + +@AllArgsConstructor +@Builder +@Getter +@JsonInclude(JsonInclude.Include.NON_NULL) +@NoArgsConstructor +public class ApiErrorResponse { + @Builder.Default + private boolean success = false; + private String message; + private String code; + @Builder.Default + private Instant timestamp = Instant.now(); +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/response/ApiListResponse.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/response/ApiListResponse.java new file mode 100644 index 0000000..a96c00f --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/response/ApiListResponse.java @@ -0,0 +1,45 @@ +package org.lbcc.bms.bms_monolith.common.response; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.data.domain.Page; + +import java.time.Instant; +import java.util.List; + +@AllArgsConstructor +@Builder(builderClassName = "ApiResponseBuilder") +@Getter +@JsonInclude(JsonInclude.Include.NON_NULL) +@NoArgsConstructor +public class ApiListResponse { + private boolean success; + private String message; + private List data; + @Builder.Default + private Instant timestamp = Instant.now(); + + // pagination metadata + private int totalItems; + private int totalPages; + private int currentPage; + private int pageSize; + private boolean hasNextPage; + private boolean hasPreviousPage; + + public static class ApiResponseBuilder { + public ApiResponseBuilder setPage(Page page) { + this.data = page.getContent(); + this.totalItems = (int) page.getTotalElements(); + this.totalPages = page.getTotalPages(); + this.currentPage = page.getNumber(); + this.pageSize = page.getSize(); + this.hasNextPage = page.hasNext(); + this.hasPreviousPage = page.hasPrevious(); + return this; + } + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/response/ApiResponse.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/response/ApiResponse.java new file mode 100644 index 0000000..31786ff --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/response/ApiResponse.java @@ -0,0 +1,22 @@ +package org.lbcc.bms.bms_monolith.common.response; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.Instant; + +@AllArgsConstructor +@Builder +@Getter +@JsonInclude(JsonInclude.Include.NON_NULL) +@NoArgsConstructor +public class ApiResponse { + private boolean success; + private String message; + private T data; + @Builder.Default + private Instant timestamp = Instant.now(); +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/controller/EventController.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/controller/EventController.java new file mode 100644 index 0000000..8318d96 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/controller/EventController.java @@ -0,0 +1,41 @@ +package org.lbcc.bms.bms_monolith.eventservice.controller; + +import org.lbcc.bms.bms_monolith.common.constants.BMSConstants; +import org.lbcc.bms.bms_monolith.common.response.ApiListResponse; +import org.lbcc.bms.bms_monolith.eventservice.dto.EventResponse; +import org.lbcc.bms.bms_monolith.eventservice.service.IEventService; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.web.PageableDefault; +import org.springframework.data.web.SortDefault; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping(path="/events") +public class EventController { + + private final IEventService iEventService; + + public EventController(IEventService iEventService) { + this.iEventService = iEventService; + } + + @GetMapping + public ResponseEntity> getAllEvents( + @PageableDefault(size = BMSConstants.DEFAULT_PAGE_SIZE) + @SortDefault(sort = "startDate", direction = Sort.Direction.DESC) Pageable pageable) { + + Page eventsPage = iEventService.getAllEvents(pageable); + + ApiListResponse response = ApiListResponse.builder() + .success(true) + .message(BMSConstants.EVENT_SUCCESS_MESSAGE) + .setPage(eventsPage) + .build(); + + return ResponseEntity.ok(response); + } + +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/EventResponse.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/EventResponse.java new file mode 100644 index 0000000..6aba519 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/EventResponse.java @@ -0,0 +1,41 @@ +package org.lbcc.bms.bms_monolith.eventservice.dto; + +import lombok.Builder; +import lombok.Getter; +import org.lbcc.bms.bms_monolith.common.entity.Event; + +import java.util.List; +import java.util.stream.Collectors; + +@Getter +@Builder +public class EventResponse { + + private String title; + private String description; + private String vendorName; + private String venueName; + private List shows; + private String eventTypeName; + private String startDate; + private String endDate; + private String thumbnailUrl; + + public static EventResponse fromEntity(Event event) { + return new EventResponse( + event.getTitle(), + event.getDescription(), + event.getVendor() != null ? event.getVendor().getName() : null, + event.getVenue() != null ? event.getVenue().getName() : null, + event.getShow() != null ? event.getShow().stream() + .map(EventShowResponse::fromEntity) + .toList() : null, + event.getEventType() != null ? event.getEventType().getLabel() : null, + event.getStartDate() != null ? event.getStartDate().toString() : null, + event.getEndDate() != null ? event.getEndDate().toString() : null, + event.getThumbnailUrl() + ); + } +} + + diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/EventShowResponse.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/EventShowResponse.java new file mode 100644 index 0000000..c764df7 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/EventShowResponse.java @@ -0,0 +1,45 @@ +package org.lbcc.bms.bms_monolith.eventservice.dto; + +import lombok.Getter; +import org.lbcc.bms.bms_monolith.common.entity.EventShow; + +import java.util.List; + +@Getter +public class EventShowResponse { + + private List genres; + private String startDate; + private String endDate; + private List seatInShows; + private List seatTypeInShows; + + // Constructors, Getters, and Setters + + public EventShowResponse(List genres, String startDate, String endDate, + List seatInShows, List seatTypeInShows) { + this.genres = genres; + this.startDate = startDate; + this.endDate = endDate; + this.seatInShows = seatInShows; + this.seatTypeInShows = seatTypeInShows; + } + + // Static factory method for conversion from EventShow entity to EventShowResponse DTO + public static EventShowResponse fromEntity(EventShow show) { + return new EventShowResponse( + show.getGenres() != null ? show.getGenres().stream() + .map(Enum::name) + .toList() : null, + show.getStartDate().toString(), + show.getEndDate().toString(), + show.getSeatInShows() != null ? show.getSeatInShows().stream() + .map(SeatInShowResponse::fromEntity) + .toList() : null, + show.getSeatTypeInShows() != null ? show.getSeatTypeInShows().stream() + .map(SeatTypeInShowResponse::fromEntity) + .toList() : null + ); + } +} + diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatInShowResponse.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatInShowResponse.java new file mode 100644 index 0000000..6184e9a --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatInShowResponse.java @@ -0,0 +1,29 @@ +package org.lbcc.bms.bms_monolith.eventservice.dto; + +import lombok.Getter; +import org.lbcc.bms.bms_monolith.common.entity.SeatInShow; + +import java.util.UUID; + +@Getter +public class SeatInShowResponse { + + private UUID seatTypeInShowId; + private String bookingStatus; + + // Constructors, Getters, and Setters + + public SeatInShowResponse(UUID seatTypeInShowId, String bookingStatus) { + this.seatTypeInShowId = seatTypeInShowId; + this.bookingStatus = bookingStatus; + } + + // Static factory method for conversion from SeatInShow entity to SeatInShowResponse DTO + public static SeatInShowResponse fromEntity(SeatInShow seatInShow) { + return new SeatInShowResponse( + seatInShow.getSeatTypeInShow() != null ? seatInShow.getSeatTypeInShow().getId() : null, + seatInShow.getBookingStatus() != null ? seatInShow.getBookingStatus().name() : null + ); + } +} + diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatTypeInShowResponse.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatTypeInShowResponse.java new file mode 100644 index 0000000..c5601d1 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatTypeInShowResponse.java @@ -0,0 +1,29 @@ +package org.lbcc.bms.bms_monolith.eventservice.dto; + +import lombok.Getter; +import org.lbcc.bms.bms_monolith.common.entity.SeatTypeInShow; + +import java.math.BigDecimal; +import java.util.UUID; + +@Getter +public class SeatTypeInShowResponse { + + private UUID seatTypeId; + private String seatTypeName; + private BigDecimal price; + + public SeatTypeInShowResponse(UUID seatTypeId, String seatTypeName, BigDecimal price) { + this.seatTypeId = seatTypeId; + this.seatTypeName = seatTypeName; + this.price = price; + } + + public static SeatTypeInShowResponse fromEntity(SeatTypeInShow seatTypeInShow) { + return new SeatTypeInShowResponse( + seatTypeInShow.getSeatType() != null ? seatTypeInShow.getSeatType().getId() : null, + seatTypeInShow.getSeatType() != null ? seatTypeInShow.getSeatType().getLabel() : null, + seatTypeInShow.getPrice() + ); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/exception/EventExceptionHandler.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/exception/EventExceptionHandler.java new file mode 100644 index 0000000..8394571 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/exception/EventExceptionHandler.java @@ -0,0 +1,19 @@ +package org.lbcc.bms.bms_monolith.eventservice.exception; + +import org.lbcc.bms.bms_monolith.common.constants.BMSConstants; +import org.lbcc.bms.bms_monolith.common.response.ApiErrorResponse; +import org.lbcc.bms.bms_monolith.common.exception.GlobalExceptionHandler; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +@ControllerAdvice +public class EventExceptionHandler { + + @ExceptionHandler(EventServiceException.class) + public ResponseEntity handleEventServiceException(EventServiceException ex) { + return GlobalExceptionHandler.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), BMSConstants.EVENT_SERVICE_ERROR); + } +} + diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/exception/EventServiceException.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/exception/EventServiceException.java new file mode 100644 index 0000000..3c53330 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/exception/EventServiceException.java @@ -0,0 +1,8 @@ +package org.lbcc.bms.bms_monolith.eventservice.exception; + +public class EventServiceException extends RuntimeException { + + public EventServiceException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/repository/IEventRepository.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/repository/IEventRepository.java new file mode 100644 index 0000000..aa7939c --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/repository/IEventRepository.java @@ -0,0 +1,15 @@ +package org.lbcc.bms.bms_monolith.eventservice.repository; + +import org.lbcc.bms.bms_monolith.common.entity.Event; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.UUID; + +@Repository +public interface IEventRepository extends JpaRepository { + + Page findAll(Pageable pageable); +} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/service/IEventService.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/service/IEventService.java new file mode 100644 index 0000000..5ea592d --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/service/IEventService.java @@ -0,0 +1,10 @@ +package org.lbcc.bms.bms_monolith.eventservice.service; + +import org.lbcc.bms.bms_monolith.eventservice.dto.EventResponse; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +public interface IEventService { + + Page getAllEvents(Pageable pageable); +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/service/impl/EventServiceImpl.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/service/impl/EventServiceImpl.java new file mode 100644 index 0000000..268630f --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/service/impl/EventServiceImpl.java @@ -0,0 +1,35 @@ +package org.lbcc.bms.bms_monolith.eventservice.service.impl; + +import lombok.extern.slf4j.Slf4j; +import org.lbcc.bms.bms_monolith.common.entity.Event; +import org.lbcc.bms.bms_monolith.eventservice.dto.EventResponse; +import org.lbcc.bms.bms_monolith.eventservice.exception.EventServiceException; +import org.lbcc.bms.bms_monolith.eventservice.repository.IEventRepository; +import org.lbcc.bms.bms_monolith.eventservice.service.IEventService; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +@Service +@Slf4j +public class EventServiceImpl implements IEventService { + + private final IEventRepository IEventRepository; + + public EventServiceImpl(IEventRepository IEventRepository) { + this.IEventRepository = IEventRepository; + } + + @Override + public Page getAllEvents(Pageable pageable) { + try { + Page eventsPage = IEventRepository.findAll(pageable); + log.info("Fetched {} events with pageable {}", eventsPage.getTotalElements(), pageable); + + return eventsPage.map(EventResponse::fromEntity); + } catch (Exception e) { + log.error("Error fetching events: {}", e.getMessage()); + throw new EventServiceException("Failed to fetch events", e); + } + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/resources/application-test.yml b/book-my-show/backend/java/bms-monolith/src/main/resources/application-test.yml new file mode 100644 index 0000000..d80cae5 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/resources/application-test.yml @@ -0,0 +1,4 @@ +spring: + datasource: + username: root + password: password diff --git a/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml b/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml new file mode 100644 index 0000000..a30b3ae --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml @@ -0,0 +1,18 @@ +Spring: + application: + name: BMS Monolith + datasource: + url: jdbc:mysql://localhost:3306/bms + username: ${DB_USERNAME:root} + password: ${DB_PASSWORD:root} + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + properties: + hibernate: + dialect: org.hibernate.dialect.MySQLDialect + hibernate: + ddl-auto: update + show-sql: true +server: + servlet: + context-path: /api/v1 \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/BmsMonolithApplicationTests.java b/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/BmsMonolithApplicationTests.java new file mode 100644 index 0000000..d479e3b --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/BmsMonolithApplicationTests.java @@ -0,0 +1,17 @@ +package org.lbcc.bms.bms_monolith; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +@SpringBootTest(properties = "spring.profiles.active=test") +class BmsMonolithApplicationTests { + + @Test + void contextLoads() { + // Test whether the application context is loading correctly + assertTrue(true, "Context should load"); + } + +} diff --git a/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/entity/TestBaseAuditingEntity.java b/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/entity/TestBaseAuditingEntity.java new file mode 100644 index 0000000..cb107ef --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/entity/TestBaseAuditingEntity.java @@ -0,0 +1,50 @@ +package org.lbcc.bms.bms_monolith.common.entity; + +import jakarta.persistence.Entity; +import lombok.experimental.SuperBuilder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TestBaseAuditingEntity { + private TestEntity testEntity; + private UUID randomId; + + @BeforeEach + void setUp() { + randomId = UUID.randomUUID(); + testEntity = TestEntity.builder() + .id(randomId) + .createdDate(Instant.now()) + .lastModifiedDate(Instant.now()) + .createdBy("admin") + .lastModifiedBy("admin") + .build(); + } + + @Test + void testBaseEntityFields() { + // Verify the fields of the BaseEntity + assertEquals(randomId, testEntity.getId()); + assertEquals("admin", testEntity.getCreatedBy()); + assertEquals("admin", testEntity.getLastModifiedBy()); + + Instant createdDate = testEntity.getCreatedDate(); + Instant updatedDate = testEntity.getLastModifiedDate(); + + // Verify createdDate and updatedDate are not null + assertEquals(createdDate, testEntity.getCreatedDate()); + assertEquals(updatedDate, testEntity.getLastModifiedDate()); + } +} + +@Entity +@SuperBuilder +class TestEntity extends BaseAuditingEntity { + // You can add any additional fields specific to this test entity if needed +} + diff --git a/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/reponse/TestApiErrorResponse.java b/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/reponse/TestApiErrorResponse.java new file mode 100644 index 0000000..3d0e84e --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/reponse/TestApiErrorResponse.java @@ -0,0 +1,59 @@ +package org.lbcc.bms.bms_monolith.common.reponse; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.junit.jupiter.api.Test; +import org.lbcc.bms.bms_monolith.common.response.ApiErrorResponse; + +import java.io.IOException; +import java.time.Instant; + +import static org.junit.jupiter.api.Assertions.*; + +class TestApiErrorResponse { + + @Test + void testApiErrorResponseBuilder() { + // Create ApiErrorResponse using builder + ApiErrorResponse response = ApiErrorResponse.builder() + .success(false) + .message("An error occurred") + .code("400_BAD_REQUEST") + .build(); + + // Verify the values + assertFalse(response.isSuccess()); + assertEquals("An error occurred", response.getMessage()); + assertEquals("400_BAD_REQUEST", response.getCode()); + + // Check that timestamp is not null and is recent + assertNotNull(response.getTimestamp()); + assertTrue(response.getTimestamp().isBefore(Instant.now().plusSeconds(1)), + "Timestamp should be set to a value close to the current time"); + } + + @Test + void testJsonSerialization() throws IOException { + // Create an instance of ApiErrorResponse + ApiErrorResponse response = ApiErrorResponse.builder() + .success(false) + .message("Validation error") + .code("400_BAD_REQUEST") + .build(); + + // Serialize to JSON + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JavaTimeModule()); + String json = objectMapper.writeValueAsString(response); + + // Deserialize back to object + ApiErrorResponse deserializedResponse = objectMapper.readValue(json, ApiErrorResponse.class); + + // Verify that values match + assertEquals(response.isSuccess(), deserializedResponse.isSuccess()); + assertEquals(response.getMessage(), deserializedResponse.getMessage()); + assertEquals(response.getCode(), deserializedResponse.getCode()); + assertEquals(response.getTimestamp(), deserializedResponse.getTimestamp()); + } +} + diff --git a/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/reponse/TestApiListResponse.java b/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/reponse/TestApiListResponse.java new file mode 100644 index 0000000..c458a0a --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/reponse/TestApiListResponse.java @@ -0,0 +1,87 @@ +package org.lbcc.bms.bms_monolith.common.reponse; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.lbcc.bms.bms_monolith.common.response.ApiListResponse; +import org.mockito.Mockito; +import org.springframework.data.domain.Page; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class TestApiListResponse { + + private Page mockPage; + + @BeforeEach + void setUp() { + // Create a mock Page with sample data + mockPage = Mockito.mock(Page.class); + + // Stub methods for the mock Page + List content = Arrays.asList("Item1", "Item2", "Item3"); + Mockito.when(mockPage.getContent()).thenReturn(content); + Mockito.when(mockPage.getTotalElements()).thenReturn(100L); + Mockito.when(mockPage.getTotalPages()).thenReturn(10); + Mockito.when(mockPage.getNumber()).thenReturn(1); // Page numbers are 0-based by default + Mockito.when(mockPage.getSize()).thenReturn(10); + Mockito.when(mockPage.hasNext()).thenReturn(true); + Mockito.when(mockPage.hasPrevious()).thenReturn(true); + } + + @Test + void testApiListResponseBuilder_setPage() { + // Build the ApiListResponse using the builder and setPage method + ApiListResponse response = ApiListResponse.builder() + .success(true) + .message("Test message") + .setPage(mockPage) + .build(); + + // Assertions + assertEquals("Test message", response.getMessage()); + assertTrue(response.isSuccess()); + assertEquals(Arrays.asList("Item1", "Item2", "Item3"), response.getData()); + assertEquals(100, response.getTotalItems()); + assertEquals(10, response.getTotalPages()); + assertEquals(1, response.getCurrentPage()); + assertEquals(10, response.getPageSize()); + assertTrue(response.isHasNextPage()); + assertTrue(response.isHasPreviousPage()); + } + + @Test + void testJsonSerialization() throws JsonProcessingException { + // Build the ApiListResponse using the builder and setPage method + ApiListResponse response = ApiListResponse.builder() + .success(true) + .message("Test message") + .setPage(mockPage) + .build(); + + // Configure ObjectMapper to handle Java 8 date/time types + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JavaTimeModule()); + + // Serialize to JSON + String json = objectMapper.writeValueAsString(response); + + // Assertions to check if the JSON string is not null and contains expected fields + assertNotNull(json); + assertTrue(json.contains("\"success\":true")); + assertTrue(json.contains("\"message\":\"Test message\"")); + assertTrue(json.contains("\"totalItems\":100")); + assertTrue(json.contains("\"totalPages\":10")); + assertTrue(json.contains("\"currentPage\":1")); + assertTrue(json.contains("\"pageSize\":10")); + assertTrue(json.contains("\"hasNextPage\":true")); + assertTrue(json.contains("\"hasPreviousPage\":true")); + assertTrue(json.contains("\"data\":[\"Item1\",\"Item2\",\"Item3\"]")); + assertTrue(json.contains("\"timestamp\"")); // timestamp field should be present + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/reponse/TestApiResponse.java b/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/reponse/TestApiResponse.java new file mode 100644 index 0000000..93678bf --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/common/reponse/TestApiResponse.java @@ -0,0 +1,60 @@ +package org.lbcc.bms.bms_monolith.common.reponse; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.junit.jupiter.api.Test; +import org.lbcc.bms.bms_monolith.common.response.ApiResponse; + +import java.io.IOException; +import java.time.Instant; + +import static org.junit.jupiter.api.Assertions.*; + +class TestApiResponse { + + @Test + void testApiResponseBuilder() { + ApiResponse response = ApiResponse.builder() + .success(true) + .message("SUCCESS") + .data("Response Body") + .build(); + + assertTrue(response.isSuccess()); + assertEquals("SUCCESS", response.getMessage()); + assertEquals("Response Body", response.getData()); + + assertNotNull(response.getTimestamp()); + assertTrue(response.getTimestamp().isBefore(Instant.now().plusSeconds(1)), + "Timestamp should be set to a value close to the current time"); + } + + @Test + void testJsonSerialization() throws IOException { + // Create an instance of ApiErrorResponse + ApiResponse response = ApiResponse.builder() + .success(true) + .message("SUCCESS") + .data("Response Body") + .build(); + + // Serialize to JSON + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JavaTimeModule()); + String json = objectMapper.writeValueAsString(response); + + // Deserialize back to object + ApiResponse deserializedResponse = objectMapper.readValue( + json, new TypeReference>() {} + ); + + // Verify that values match + assertEquals(response.isSuccess(), deserializedResponse.isSuccess()); + assertEquals(response.getMessage(), deserializedResponse.getMessage()); + assertEquals(response.getData(), deserializedResponse.getData()); + assertEquals(response.getTimestamp(), deserializedResponse.getTimestamp()); + } +} + + diff --git a/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/controller/EventControllerTest.java b/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/controller/EventControllerTest.java new file mode 100644 index 0000000..28166fa --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/controller/EventControllerTest.java @@ -0,0 +1,96 @@ +package org.lbcc.bms.bms_monolith.controller; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.lbcc.bms.bms_monolith.common.response.ApiListResponse; +import org.lbcc.bms.bms_monolith.common.entity.Event; +import org.lbcc.bms.bms_monolith.eventservice.controller.EventController; +import org.lbcc.bms.bms_monolith.eventservice.dto.EventResponse; +import org.lbcc.bms.bms_monolith.eventservice.exception.EventServiceException; +import org.lbcc.bms.bms_monolith.eventservice.service.IEventService; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; +import org.springframework.http.HttpStatus; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; +import java.util.UUID; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class EventControllerTest { + + @Mock + private IEventService eventService; + + @InjectMocks + private EventController eventController; + + @Test + void testGetAllEventsSuccess() { + Event event = new Event(); + event.setId(UUID.randomUUID()); + event.setTitle("Sample Event"); + Pageable defaultPage = PageRequest.of(0, 10); + Page eventPage = new PageImpl<>(List.of(EventResponse.fromEntity(event)), defaultPage, 1); + + when(eventService.getAllEvents(any(Pageable.class))).thenReturn(eventPage); + + ResponseEntity> response = eventController.getAllEvents(defaultPage); + + ApiListResponse expectedResponse = ApiListResponse.builder() + .success(true) + .message("Events fetched successfully") + .data(eventPage.getContent()) + .totalItems((int) eventPage.getTotalElements()) + .totalPages(eventPage.getTotalPages()) + .currentPage(eventPage.getNumber()) + .pageSize(eventPage.getSize()) + .hasNextPage(eventPage.hasNext()) + .hasPreviousPage(eventPage.hasPrevious()) + .build(); + + // Assertions to verify response + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertEquals(expectedResponse.getMessage(), response.getBody().getMessage()); + assertEquals(expectedResponse.isSuccess(), response.getBody().isSuccess()); + assertEquals(1, response.getBody().getTotalItems()); + } + + @Test + void testGetAllEventsInvalidPageParameters() { + Page emptyPage = Page.empty(PageRequest.of(0, 10)); + + when(eventService.getAllEvents(PageRequest.of(0, 10))).thenReturn(emptyPage); + + ResponseEntity> response = eventController.getAllEvents(PageRequest.of(0, 10)); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertEquals("Events fetched successfully", response.getBody().getMessage()); + assertEquals(true, response.getBody().isSuccess()); + } + + @Test + void testGetAllEventsExceptionHandling() { + when(eventService.getAllEvents(any(Pageable.class))) + .thenThrow(new EventServiceException("Failed to fetch events", new RuntimeException())); + Pageable pageable = PageRequest.of(0, 10); + EventServiceException exception = assertThrows(EventServiceException.class, () -> + eventController.getAllEvents(pageable) + ); + + assertEquals("Failed to fetch events", exception.getMessage()); + } + +} diff --git a/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/service/EventServiceImplTest.java b/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/service/EventServiceImplTest.java new file mode 100644 index 0000000..e747df5 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/test/java/org/lbcc/bms/bms_monolith/service/EventServiceImplTest.java @@ -0,0 +1,67 @@ +package org.lbcc.bms.bms_monolith.service; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.lbcc.bms.bms_monolith.common.entity.Event; +import org.lbcc.bms.bms_monolith.eventservice.dto.EventResponse; +import org.lbcc.bms.bms_monolith.eventservice.exception.EventServiceException; +import org.lbcc.bms.bms_monolith.eventservice.repository.IEventRepository; +import org.lbcc.bms.bms_monolith.eventservice.service.impl.EventServiceImpl; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; + +import java.util.Collections; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class EventServiceImplTest { + + @Mock + private IEventRepository IEventRepository; + + @InjectMocks + private EventServiceImpl eventService; + + @Test + void testGetAllEventsSuccess() { + Event event = new Event(); + event.setTitle("Sample Event"); + event.setDescription("Sample Description"); + + Pageable pageable = PageRequest.of(0, 10); + Page eventPage = new PageImpl<>(Collections.singletonList(event), pageable, 1); + + when(IEventRepository.findAll(pageable)).thenReturn(eventPage); + + Page response = eventService.getAllEvents(pageable); + + assertNotNull(response); + assertEquals(1, response.getTotalElements()); + assertEquals("Sample Event", response.getContent().get(0).getTitle()); + assertEquals("Sample Description", response.getContent().get(0).getDescription()); + } + + @Test + void testGetAllEventsExceptionHandling() { + when(IEventRepository.findAll(any(Pageable.class))).thenThrow(new RuntimeException("Database error")); + + Pageable pageable = PageRequest.of(0, 10); + EventServiceException exception = assertThrows(EventServiceException.class, () -> + eventService.getAllEvents(pageable) + ); + + assertEquals("Failed to fetch events", exception.getMessage()); + } +} From a8f5cc47761eb437b3a6a63911e903a4be9ebdcd Mon Sep 17 00:00:00 2001 From: Naresh Darga Date: Tue, 26 Nov 2024 21:03:59 +0530 Subject: [PATCH 2/6] security- changes for user login --- .../backend/java/bms-monolith/pom.xml | 36 ++++++++ .../bms_monolith/BmsMonolithApplication.java | 1 + .../exception/GlobalExceptionHandler.java | 59 +++++++++++-- .../security/AuthEntryPointJwt.java | 41 +++++++++ .../security/AuthTokenFilter.java | 67 ++++++++++++++ .../security/WebSecurityConfig.java | 88 +++++++++++++++++++ .../userservice/common/JwtUtils.java | 69 +++++++++++++++ .../userservice/common/RoleDataSeeder.java | 39 ++++++++ .../userservice/common/RoleFactory.java | 33 +++++++ .../userservice/common/RoleType.java | 9 ++ .../userservice/common/SignUpRequestDto.java | 34 +++++++ .../controller/AuthController.java | 31 +++++++ .../controller/UserController.java | 18 ++++ .../exeception/RoleNotFoundException.java | 7 ++ .../UserAlreadyExistsException.java | 7 ++ .../exeception/UsernameNotFoundException.java | 7 ++ .../userservice/model/BaseEntity.java | 48 ++++++++++ .../bms_monolith/userservice/model/Role.java | 23 +++++ .../bms_monolith/userservice/model/User.java | 38 ++++++++ .../repository/RoleRepository.java | 11 +++ .../repository/UserRepository.java | 13 +++ .../userservice/service/AuthService.java | 14 +++ .../userservice/service/UserService.java | 11 +++ .../service/impl/AuthServiceImpl.java | 75 ++++++++++++++++ .../service/impl/UserDetailsImpl.java | 67 ++++++++++++++ .../service/impl/UserDetailsServiceImpl.java | 27 ++++++ .../service/impl/UserServiceImpl.java | 34 +++++++ .../src/main/resources/application.yaml | 19 ++-- 28 files changed, 916 insertions(+), 10 deletions(-) create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/AuthEntryPointJwt.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/AuthTokenFilter.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/WebSecurityConfig.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/JwtUtils.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleDataSeeder.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleFactory.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleType.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/SignUpRequestDto.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/AuthController.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/UserController.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/RoleNotFoundException.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UserAlreadyExistsException.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UsernameNotFoundException.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/BaseEntity.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/Role.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/User.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/RoleRepository.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/UserRepository.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/AuthService.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/UserService.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsImpl.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsServiceImpl.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserServiceImpl.java diff --git a/book-my-show/backend/java/bms-monolith/pom.xml b/book-my-show/backend/java/bms-monolith/pom.xml index 76f9214..2acf613 100644 --- a/book-my-show/backend/java/bms-monolith/pom.xml +++ b/book-my-show/backend/java/bms-monolith/pom.xml @@ -54,6 +54,16 @@ org.springframework.boot spring-boot-starter-validation + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.security + spring-security-test + test + + org.projectlombok @@ -70,6 +80,32 @@ jackson-datatype-jsr310 2.18.0 + + io.jsonwebtoken + jjwt-api + 0.11.5 + + + io.jsonwebtoken + jjwt-impl + 0.11.5 + + + io.jsonwebtoken + jjwt-jackson + 0.11.5 + + + + org.postgresql + postgresql + 42.7.4 + + + org.springframework.boot + spring-boot-starter-actuator + + diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/BmsMonolithApplication.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/BmsMonolithApplication.java index f43b60d..ad6b857 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/BmsMonolithApplication.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/BmsMonolithApplication.java @@ -4,6 +4,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication + public class BmsMonolithApplication { public static void main(String[] args) { diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java index b0de11d..0c80f1a 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java @@ -2,18 +2,19 @@ import org.lbcc.bms.bms_monolith.common.constants.BMSConstants; import org.lbcc.bms.bms_monolith.common.response.ApiErrorResponse; +import org.lbcc.bms.bms_monolith.userservice.exeception.RoleNotFoundException; +import org.lbcc.bms.bms_monolith.userservice.exeception.UserAlreadyExistsException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; +import java.util.ArrayList; +import java.util.List; + @ControllerAdvice public class GlobalExceptionHandler { - @ExceptionHandler(Exception.class) - public ResponseEntity handleGlobalException(Exception ex) { - return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, BMSConstants.UNEXPECTED_ERROR_MESSAGE, BMSConstants.UNEXPECTED_ERROR_CODE); - } - public static ResponseEntity buildErrorResponse(HttpStatus status, String message, String code) { ApiErrorResponse errorResponse = ApiErrorResponse.builder() .message(message) @@ -21,4 +22,52 @@ public static ResponseEntity buildErrorResponse(HttpStatus sta .build(); return ResponseEntity.status(status).body(errorResponse); } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleGlobalException(Exception ex) { + return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, BMSConstants.UNEXPECTED_ERROR_MESSAGE, BMSConstants.UNEXPECTED_ERROR_CODE); + } + + @ExceptionHandler(value = MethodArgumentNotValidException.class) + public ResponseEntity MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException exception) { + + List errorMessage = new ArrayList<>(); + + exception.getBindingResult().getFieldErrors().forEach(error -> { + errorMessage.add(error.getDefaultMessage()); + }); + return ResponseEntity + .badRequest() + .body( + ApiErrorResponse.builder() + // .isSuccess(false) + .message("Registration Failed: Please provide valid data.") + .code(errorMessage.toString()) + .build() + ); + } + + @ExceptionHandler(value = UserAlreadyExistsException.class) + public ResponseEntity UserAlreadyExistsExceptionHandler(UserAlreadyExistsException exception) { + return ResponseEntity + .status(HttpStatus.CONFLICT) + .body( + ApiErrorResponse.builder() + // .isSuccess(false) + .message(exception.getMessage()) + .build() + ); + } + + @ExceptionHandler(value = RoleNotFoundException.class) + public ResponseEntity RoleNotFoundExceptionHandler(RoleNotFoundException exception) { + return ResponseEntity + .status(HttpStatus.NOT_FOUND) + .body( + ApiErrorResponse.builder() + .message(exception.getMessage()) + .build() + ); + } + } diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/AuthEntryPointJwt.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/AuthEntryPointJwt.java new file mode 100644 index 0000000..4d62880 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/AuthEntryPointJwt.java @@ -0,0 +1,41 @@ + +package org.lbcc.bms.bms_monolith.security; + +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +@Component +public class AuthEntryPointJwt implements AuthenticationEntryPoint { + + private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class); + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) + throws IOException { + logger.error("Unauthorized error: {}", authException.getMessage()); + + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + + final Map body = new HashMap<>(); + body.put("status", HttpServletResponse.SC_UNAUTHORIZED); + body.put("error", "Unauthorized"); + body.put("message", authException.getMessage()); + body.put("path", request.getServletPath()); + + final ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(response.getOutputStream(), body); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/AuthTokenFilter.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/AuthTokenFilter.java new file mode 100644 index 0000000..7d2667e --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/AuthTokenFilter.java @@ -0,0 +1,67 @@ + +package org.lbcc.bms.bms_monolith.security; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.lbcc.bms.bms_monolith.userservice.common.JwtUtils; +import org.lbcc.bms.bms_monolith.userservice.service.impl.UserDetailsServiceImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +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.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + + +public class AuthTokenFilter extends OncePerRequestFilter { + @Autowired + private JwtUtils jwtUtils; + + @Autowired + private UserDetailsServiceImpl userDetailsService; + + private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class); + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + try { + String jwt = parseJwt(request); + if (jwt != null && jwtUtils.validateJwtToken(jwt)) { + String username = jwtUtils.getUserNameFromJwtToken(jwt); + + UserDetails userDetails = userDetailsService.loadUserByUsername(username); + UsernamePasswordAuthenticationToken authentication = + new UsernamePasswordAuthenticationToken( + userDetails, + null, + userDetails.getAuthorities()); + authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + + SecurityContextHolder.getContext().setAuthentication(authentication); + } + } catch (Exception e) { + logger.error("Cannot set user authentication: {}", e); + } + + filterChain.doFilter(request, response); + } + + private String parseJwt(HttpServletRequest request) { + String headerAuth = request.getHeader("Authorization"); + + if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) { + return headerAuth.substring(7); + } + + return null; + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/WebSecurityConfig.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/WebSecurityConfig.java new file mode 100644 index 0000000..c0071cd --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/WebSecurityConfig.java @@ -0,0 +1,88 @@ +package org.lbcc.bms.bms_monolith.security; + + +import org.lbcc.bms.bms_monolith.userservice.service.impl.UserDetailsServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +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.WebSecurityCustomizer; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; +import org.springframework.security.web.util.matcher.RequestMatcher; + +import java.util.List; + + +@Configuration +@EnableMethodSecurity +public class WebSecurityConfig{ + + List publicApis = List.of( "/api/auth/**"); + + private final AuthEntryPointJwt unauthorizedHandler = new AuthEntryPointJwt(); + UserDetailsServiceImpl userDetailsService = new UserDetailsServiceImpl(); + + @Bean + public AuthTokenFilter authenticationJwtTokenFilter() { + return new AuthTokenFilter(); + } + + @Bean + public DaoAuthenticationProvider authenticationProvider() { + + + DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); + + authProvider.setUserDetailsService(userDetailsService); + authProvider.setPasswordEncoder(passwordEncoder()); + + return authProvider; + } + + @Bean + public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) + throws Exception { + return authConfig.getAuthenticationManager(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + + http.csrf(AbstractHttpConfigurer::disable) + + .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler)) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + + .authorizeHttpRequests(auth -> + auth.requestMatchers(publicApis.stream() + .map(AntPathRequestMatcher::new) + .toArray(RequestMatcher[]::new)).permitAll() + .anyRequest().authenticated() + ); + + http.authenticationProvider(authenticationProvider()); + + http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); + + return http.build(); + } + @Bean + public WebSecurityCustomizer webSecurityCustomizer() { + return (web) -> web.ignoring().requestMatchers(publicApis.toArray(String[]::new)); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/JwtUtils.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/JwtUtils.java new file mode 100644 index 0000000..6533589 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/JwtUtils.java @@ -0,0 +1,69 @@ + +package org.lbcc.bms.bms_monolith.userservice.common; + +import io.jsonwebtoken.*; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import org.lbcc.bms.bms_monolith.userservice.service.impl.UserDetailsImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Component; + +import java.security.Key; +import java.util.Date; + +@Component +public class JwtUtils { + private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class); + + @Value("${app.jwtSecret}") + private String jwtSecret; + + @Value("${app.jwtExpirationMs}") + private int jwtExpirationMs; + + public String generateJwtToken(Authentication authentication) { + + UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal(); + + return Jwts.builder() + .setSubject((userPrincipal.getEmail())) + .setIssuedAt(new Date()) + .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs)) + .signWith(key(), SignatureAlgorithm.HS256) + .compact(); + } + + private Key key() { + return Keys.hmacShaKeyFor(Decoders.BASE64.decode(jwtSecret)); + } + + public String getUserNameFromJwtToken(String token) { + return Jwts.parserBuilder() + .setSigningKey(key()) + .build() + .parseClaimsJws(token) + .getBody() + .getSubject(); + } + + public boolean validateJwtToken(String authToken) { + try { + Jwts.parserBuilder().setSigningKey(key()).build().parse(authToken); + return true; + } catch (MalformedJwtException e) { + logger.error("Invalid JWT token: {}", e.getMessage()); + } catch (ExpiredJwtException e) { + logger.error("JWT token is expired: {}", e.getMessage()); + } catch (UnsupportedJwtException e) { + logger.error("JWT token is unsupported: {}", e.getMessage()); + } catch (IllegalArgumentException e) { + logger.error("JWT claims string is empty: {}", e.getMessage()); + } + + return false; + } +} + diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleDataSeeder.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleDataSeeder.java new file mode 100644 index 0000000..156e715 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleDataSeeder.java @@ -0,0 +1,39 @@ +package org.lbcc.bms.bms_monolith.userservice.common; + +import jakarta.transaction.Transactional; +import org.lbcc.bms.bms_monolith.userservice.model.Role; +import org.lbcc.bms.bms_monolith.userservice.repository.RoleRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +import java.time.Instant; +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +@Component +public class RoleDataSeeder { + @Autowired private RoleRepository roleRepository; + + @EventListener + @Transactional + public void LoadRoles(ContextRefreshedEvent event) { + + List roles = Arrays.stream(RoleType.values()).toList(); + + for (RoleType erole : roles) { + if (roleRepository.findByName(erole) == null) { + Role role = new Role(); + role.setName(erole); + role.setDescription(erole.name()); + role.setCreatedBy("system"); + role.setCreatedDate(Instant.now()); + role.setLastModifiedDate(Instant.now()); + role.setLastModifiedBy("system"); + roleRepository.save(role); + } + } + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleFactory.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleFactory.java new file mode 100644 index 0000000..25140fd --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleFactory.java @@ -0,0 +1,33 @@ +package org.lbcc.bms.bms_monolith.userservice.common; + +import org.lbcc.bms.bms_monolith.userservice.exeception.RoleNotFoundException; +import org.lbcc.bms.bms_monolith.userservice.model.Role; +import org.lbcc.bms.bms_monolith.userservice.repository.RoleRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class RoleFactory { + @Autowired + RoleRepository roleRepository; + + public Role getInstance(String role) throws RoleNotFoundException { + switch (role) { + case "admin" -> { + return roleRepository.findByName(RoleType.ADMIN); + } + case "user" -> { + return roleRepository.findByName(RoleType.USER); + } + case "vendor" -> { + return roleRepository.findByName(RoleType.VENDOR); + } + case "guest" -> { + return roleRepository.findByName(RoleType.GUEST); + } + + default -> throw new RoleNotFoundException("No role found for " + role); + } + } + +} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleType.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleType.java new file mode 100644 index 0000000..e893a2b --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleType.java @@ -0,0 +1,9 @@ +package org.lbcc.bms.bms_monolith.userservice.common; + +public enum RoleType { + GUEST, + VENDOR, + ADMIN, + USER, + +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/SignUpRequestDto.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/SignUpRequestDto.java new file mode 100644 index 0000000..4080f22 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/SignUpRequestDto.java @@ -0,0 +1,34 @@ +package org.lbcc.bms.bms_monolith.userservice.common; + +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Set; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class SignUpRequestDto { + @NotBlank(message = "Username is required!") + @Size(min= 3, message = "Username must have atleast 3 characters!") + @Size(max= 20, message = "Username can have have atmost 20 characters!") + private String userName; + + @Email(message = "Email is not in valid format!") + @NotBlank(message = "Email is required!") + private String email; + + @NotBlank(message = "Password is required!") + @Size(min = 8, message = "Password must have atleast 8 characters!") + @Size(max = 20, message = "Password can have have atmost 20 characters!") + private String password; + + private Set roles; + + +} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/AuthController.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/AuthController.java new file mode 100644 index 0000000..8df0792 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/AuthController.java @@ -0,0 +1,31 @@ +package org.lbcc.bms.bms_monolith.userservice.controller; + +import jakarta.validation.Valid; +import org.lbcc.bms.bms_monolith.common.response.ApiResponse; +import org.lbcc.bms.bms_monolith.userservice.common.SignUpRequestDto; +import org.lbcc.bms.bms_monolith.userservice.exeception.RoleNotFoundException; +import org.lbcc.bms.bms_monolith.userservice.exeception.UserAlreadyExistsException; +import org.lbcc.bms.bms_monolith.userservice.service.AuthService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@CrossOrigin("*") +@RequestMapping("/auth") +public class AuthController { + @Autowired + private AuthService authService; + + @PostMapping("/signup") + public ResponseEntity registerUser(@RequestBody @Valid SignUpRequestDto signUpRequestDto) + throws UserAlreadyExistsException, RoleNotFoundException { + return authService.signUpUser(signUpRequestDto); + } + @PostMapping("/signin") + public ResponseEntity signIn(@RequestBody @Valid SignUpRequestDto signUpRequestDto) + throws UserAlreadyExistsException, RoleNotFoundException { + return authService.signUpUser(signUpRequestDto); + } + +} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/UserController.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/UserController.java new file mode 100644 index 0000000..4aa615f --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/UserController.java @@ -0,0 +1,18 @@ +package org.lbcc.bms.bms_monolith.userservice.controller; + +import org.lbcc.bms.bms_monolith.common.response.ApiResponse; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/users") +public class UserController { + + @GetMapping("/") + public ResponseEntity> Test() { + return ResponseEntity.status(HttpStatus.OK).body(ApiResponse.builder().success(true).message(" jwt token test").build()); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/RoleNotFoundException.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/RoleNotFoundException.java new file mode 100644 index 0000000..e79aa86 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/RoleNotFoundException.java @@ -0,0 +1,7 @@ +package org.lbcc.bms.bms_monolith.userservice.exeception; + +public class RoleNotFoundException extends Exception{ + public RoleNotFoundException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UserAlreadyExistsException.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UserAlreadyExistsException.java new file mode 100644 index 0000000..5b9f596 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UserAlreadyExistsException.java @@ -0,0 +1,7 @@ +package org.lbcc.bms.bms_monolith.userservice.exeception; + +public class UserAlreadyExistsException extends Exception{ + public UserAlreadyExistsException(String message) { + super(message); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UsernameNotFoundException.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UsernameNotFoundException.java new file mode 100644 index 0000000..5d57ccf --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UsernameNotFoundException.java @@ -0,0 +1,7 @@ +package org.lbcc.bms.bms_monolith.userservice.exeception; + +public class UsernameNotFoundException extends RuntimeException { + public UsernameNotFoundException(String message) { + super(message); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/BaseEntity.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/BaseEntity.java new file mode 100644 index 0000000..2287e9f --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/BaseEntity.java @@ -0,0 +1,48 @@ +package org.lbcc.bms.bms_monolith.userservice.model; + +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.MappedSuperclass; +import java.time.Instant; +import java.util.UUID; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.experimental.SuperBuilder; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +@AllArgsConstructor +@Getter +@MappedSuperclass +@NoArgsConstructor +@Setter +@SuperBuilder +@EntityListeners(AuditingEntityListener.class) +public abstract class BaseEntity { + + + + @CreatedDate + @Column(updatable = false) + private Instant createdDate; + + @LastModifiedDate + @Column(insertable = false) + private Instant lastModifiedDate; + + @CreatedBy + @Column(updatable = false, length = 10) + private String createdBy; + + @LastModifiedBy + @Column(insertable = false, length = 10) + private String lastModifiedBy; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/Role.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/Role.java new file mode 100644 index 0000000..ae3e77e --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/Role.java @@ -0,0 +1,23 @@ +package org.lbcc.bms.bms_monolith.userservice.model; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.lbcc.bms.bms_monolith.userservice.common.RoleType; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@Entity +@Table(name = "roles") +public class Role extends BaseEntity { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "role_id") + private Long roleId; + @Enumerated(EnumType.STRING) + private RoleType name; + + @Column private String description; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/User.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/User.java new file mode 100644 index 0000000..81910d7 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/User.java @@ -0,0 +1,38 @@ +package org.lbcc.bms.bms_monolith.userservice.model; + +import jakarta.persistence.*; +import lombok.*; +import lombok.experimental.SuperBuilder; +import org.lbcc.bms.bms_monolith.common.entity.BaseAuditingEntity; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@Builder +@Entity +@Table(name="users") +public class User extends BaseEntity { + + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "user_id") + private Long id; + private String username; + private String email; + private String phone; + private String password; + private boolean enabled = true; + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable( + name = "user_roles", + joinColumns = {@JoinColumn(name = "user_id")}, + inverseJoinColumns = {@JoinColumn(name = "role_id")}) + private Set roles = new HashSet<>(); +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/RoleRepository.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/RoleRepository.java new file mode 100644 index 0000000..b1d5096 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/RoleRepository.java @@ -0,0 +1,11 @@ +package org.lbcc.bms.bms_monolith.userservice.repository; + +import org.lbcc.bms.bms_monolith.userservice.common.RoleType; +import org.lbcc.bms.bms_monolith.userservice.model.Role; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface RoleRepository extends JpaRepository { + Role findByName(RoleType name); +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/UserRepository.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/UserRepository.java new file mode 100644 index 0000000..081ff0f --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/UserRepository.java @@ -0,0 +1,13 @@ +package org.lbcc.bms.bms_monolith.userservice.repository; + +import org.lbcc.bms.bms_monolith.userservice.model.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; +@Repository +public interface UserRepository extends JpaRepository { + Optional findByEmail(String email); + Boolean existsByUsername(String username); + Boolean existsByEmail(String email); +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/AuthService.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/AuthService.java new file mode 100644 index 0000000..3d4322a --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/AuthService.java @@ -0,0 +1,14 @@ +package org.lbcc.bms.bms_monolith.userservice.service; + +import org.lbcc.bms.bms_monolith.common.response.ApiResponse; +import org.lbcc.bms.bms_monolith.userservice.common.SignUpRequestDto; +import org.lbcc.bms.bms_monolith.userservice.exeception.RoleNotFoundException; +import org.lbcc.bms.bms_monolith.userservice.exeception.UserAlreadyExistsException; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + + +@Service +public interface AuthService { + ResponseEntity signUpUser(SignUpRequestDto signUpRequestDto) throws UserAlreadyExistsException, RoleNotFoundException, org.lbcc.bms.bms_monolith.userservice.exeception.RoleNotFoundException; +} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/UserService.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/UserService.java new file mode 100644 index 0000000..3aec886 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/UserService.java @@ -0,0 +1,11 @@ +package org.lbcc.bms.bms_monolith.userservice.service; + +import org.lbcc.bms.bms_monolith.userservice.model.User; +import org.springframework.stereotype.Service; + +@Service +public interface UserService { + boolean existsByUsername(String username); + boolean existsByEmail(String email); + void save(User user); +} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java new file mode 100644 index 0000000..df78109 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java @@ -0,0 +1,75 @@ +package org.lbcc.bms.bms_monolith.userservice.service.impl; + +import org.lbcc.bms.bms_monolith.common.response.ApiResponse; +import org.lbcc.bms.bms_monolith.userservice.common.RoleFactory; +import org.lbcc.bms.bms_monolith.userservice.common.SignUpRequestDto; +import org.lbcc.bms.bms_monolith.userservice.exeception.RoleNotFoundException; +import org.lbcc.bms.bms_monolith.userservice.exeception.UserAlreadyExistsException; +import org.lbcc.bms.bms_monolith.userservice.model.Role; +import org.lbcc.bms.bms_monolith.userservice.model.User; +import org.lbcc.bms.bms_monolith.userservice.service.AuthService; +import org.lbcc.bms.bms_monolith.userservice.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Component; + +import java.util.HashSet; +import java.util.Set; + +@Component +public class AuthServiceImpl implements AuthService { + + @Autowired + private UserService userService; + + private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + + @Autowired + private RoleFactory roleFactory; + + @Override + public ResponseEntity signUpUser(SignUpRequestDto signUpRequestDto) + throws UserAlreadyExistsException , RoleNotFoundException { + if (userService.existsByEmail(signUpRequestDto.getEmail())) { + throw new UserAlreadyExistsException("Registration Failed: Provided email already exists. Try sign in or provide another email."); + } + if (userService.existsByUsername(signUpRequestDto.getUserName())) { + throw new UserAlreadyExistsException("Registration Failed: Provided username already exists. Try sign in or provide another username."); + } + + User user = createUser(signUpRequestDto); + userService.save(user); + return ResponseEntity.status(HttpStatus.CREATED).body( + ApiResponse.builder() + // .isSuccess(true) + .message("User account has been successfully created!") + .build() + ); + } + + private User createUser(SignUpRequestDto signUpRequestDto) throws RoleNotFoundException { + return User.builder() + .email(signUpRequestDto.getEmail()) + .username(signUpRequestDto.getUserName()) + .password(signUpRequestDto.getPassword()) + .enabled(true) + .roles(determineRoles(signUpRequestDto.getRoles())) + .build(); + } + + private Set determineRoles(Set strRoles) throws RoleNotFoundException { + Set roles = new HashSet<>(); + + if (strRoles == null) { + roles.add(roleFactory.getInstance("user")); + } else { + for (String role : strRoles) { + roles.add(roleFactory.getInstance(role)); + } + } + return roles; + } +} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsImpl.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsImpl.java new file mode 100644 index 0000000..a6f1c4c --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsImpl.java @@ -0,0 +1,67 @@ + +package org.lbcc.bms.bms_monolith.userservice.service.impl; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.AllArgsConstructor; +import lombok.Data; +import org.lbcc.bms.bms_monolith.userservice.model.User; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.io.Serial; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +@AllArgsConstructor +@Data +public class UserDetailsImpl implements UserDetails { + @Serial private static final long serialVersionUID = 1L; + private Long id; + private String username; + private String email; + @JsonIgnore private String password; + private Collection authorities; + private boolean enabled; + + public static UserDetailsImpl build(User user) { + List authorities = + user.getRoles().stream() + .map(role -> new SimpleGrantedAuthority(role.getName().name())) + .collect(Collectors.toList()); + + return new UserDetailsImpl( + user.getId(), + user.getUsername(), + user.getEmail(), + user.getPassword(), + authorities, + user.isEnabled()); + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + UserDetailsImpl user = (UserDetailsImpl) o; + return Objects.equals(id, user.id); + } +} + diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsServiceImpl.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsServiceImpl.java new file mode 100644 index 0000000..209cb3f --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsServiceImpl.java @@ -0,0 +1,27 @@ +package org.lbcc.bms.bms_monolith.userservice.service.impl; + +import jakarta.transaction.Transactional; +import org.lbcc.bms.bms_monolith.userservice.model.User; +import org.lbcc.bms.bms_monolith.userservice.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +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; + +@Service +public class UserDetailsServiceImpl implements UserDetailsService { + @Autowired UserRepository userRepository; + + @Override + @Transactional + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + User user = + userRepository + .findByEmail(username) + .orElseThrow( + () -> new UsernameNotFoundException("User Not Found with username: " + username)); + + return UserDetailsImpl.build(user); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserServiceImpl.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..4946fba --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserServiceImpl.java @@ -0,0 +1,34 @@ +package org.lbcc.bms.bms_monolith.userservice.service.impl; + +import org.lbcc.bms.bms_monolith.userservice.model.User; +import org.lbcc.bms.bms_monolith.userservice.repository.UserRepository; +import org.lbcc.bms.bms_monolith.userservice.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; + +import org.springframework.stereotype.Service; + +@Service +public class UserServiceImpl implements UserService { + + private final UserRepository userRepository; + + @Autowired + public UserServiceImpl(UserRepository userRepository) { + this.userRepository = userRepository; + } + + @Override + public boolean existsByUsername(String username) { + return userRepository.existsByUsername(username); + } + + @Override + public boolean existsByEmail(String email) { + return userRepository.existsByEmail(email); + } + + @Override + public void save(User user) { + userRepository.save(user); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml b/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml index a30b3ae..a975fcf 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml +++ b/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml @@ -2,17 +2,26 @@ Spring: application: name: BMS Monolith datasource: - url: jdbc:mysql://localhost:3306/bms - username: ${DB_USERNAME:root} + url: jdbc:postgresql://localhost:5432/bms + username: ${DB_USERNAME:postgres} password: ${DB_PASSWORD:root} - driver-class-name: com.mysql.cj.jdbc.Driver + driver-class-name: org.postgresql.Driver jpa: properties: hibernate: - dialect: org.hibernate.dialect.MySQLDialect + dialect: org.hibernate.dialect.PostgreSQLDialect hibernate: ddl-auto: update show-sql: true server: servlet: - context-path: /api/v1 \ No newline at end of file + context-path: /api/v1 +app: + jwtSecret: ramdom852 + jwtExpirationMs: 86400000 + +logging: + level: + org: + springframework: + security: DEBUG \ No newline at end of file From 7777b9cd5280e453c8d86f07a08aefb0e455fd62 Mon Sep 17 00:00:00 2001 From: Naresh Darga Date: Tue, 26 Nov 2024 21:10:45 +0530 Subject: [PATCH 3/6] security- changes for user login: changes reverted --- .../exception/GlobalExceptionHandler.java | 11 +++++++---- .../src/main/resources/application.yaml | 19 +++++-------------- 2 files changed, 12 insertions(+), 18 deletions(-) diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java index 0c80f1a..894414e 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java @@ -15,6 +15,12 @@ @ControllerAdvice public class GlobalExceptionHandler { + + @ExceptionHandler(Exception.class) + public ResponseEntity handleGlobalException(Exception ex) { + return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, BMSConstants.UNEXPECTED_ERROR_MESSAGE, BMSConstants.UNEXPECTED_ERROR_CODE); + } + public static ResponseEntity buildErrorResponse(HttpStatus status, String message, String code) { ApiErrorResponse errorResponse = ApiErrorResponse.builder() .message(message) @@ -23,10 +29,7 @@ public static ResponseEntity buildErrorResponse(HttpStatus sta return ResponseEntity.status(status).body(errorResponse); } - @ExceptionHandler(Exception.class) - public ResponseEntity handleGlobalException(Exception ex) { - return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, BMSConstants.UNEXPECTED_ERROR_MESSAGE, BMSConstants.UNEXPECTED_ERROR_CODE); - } + @ExceptionHandler(value = MethodArgumentNotValidException.class) public ResponseEntity MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException exception) { diff --git a/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml b/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml index a975fcf..a30b3ae 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml +++ b/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml @@ -2,26 +2,17 @@ Spring: application: name: BMS Monolith datasource: - url: jdbc:postgresql://localhost:5432/bms - username: ${DB_USERNAME:postgres} + url: jdbc:mysql://localhost:3306/bms + username: ${DB_USERNAME:root} password: ${DB_PASSWORD:root} - driver-class-name: org.postgresql.Driver + driver-class-name: com.mysql.cj.jdbc.Driver jpa: properties: hibernate: - dialect: org.hibernate.dialect.PostgreSQLDialect + dialect: org.hibernate.dialect.MySQLDialect hibernate: ddl-auto: update show-sql: true server: servlet: - context-path: /api/v1 -app: - jwtSecret: ramdom852 - jwtExpirationMs: 86400000 - -logging: - level: - org: - springframework: - security: DEBUG \ No newline at end of file + context-path: /api/v1 \ No newline at end of file From 397fbe06ae12f0468c886ca3ebdb33a2bd65a23b Mon Sep 17 00:00:00 2001 From: rohitnandi12 Date: Sat, 7 Dec 2024 14:11:00 +0530 Subject: [PATCH 4/6] #11 Adds liquibase code for Role,user, etc. Fix UUID issue. Formatting and clean code fixed." --- .../common/entity/BaseAuditingEntity.java | 4 +- .../bms/bms_monolith/common/entity/Event.java | 1 - .../bms_monolith/common/entity/EventShow.java | 4 ++ .../common/entity/SeatTypeInShow.java | 4 ++ .../exception/GlobalExceptionHandler.java | 2 - .../eventservice/dto/SeatInShowResponse.java | 4 +- .../dto/SeatTypeInShowResponse.java | 4 +- .../userservice/common/JwtUtils.java | 5 +- .../userservice/common/RoleDataSeeder.java | 39 +++++++------ .../userservice/common/RoleFactory.java | 8 +-- .../userservice/model/BaseEntity.java | 48 ---------------- .../bms_monolith/userservice/model/Role.java | 18 +++--- .../bms_monolith/userservice/model/User.java | 50 +++++++++-------- .../repository/RoleRepository.java | 2 +- .../repository/UserRepository.java | 3 + .../service/impl/AuthServiceImpl.java | 15 ++--- .../service/impl/UserDetailsImpl.java | 6 +- .../src/main/resources/application.yaml | 10 +++- .../db/changelog/changelog-master.xml | 1 + .../db/changelog/v1.0/add-auth-tables.xml | 55 +++++++++++++++++++ 20 files changed, 155 insertions(+), 128 deletions(-) delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/BaseEntity.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/resources/db/changelog/v1.0/add-auth-tables.xml diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/BaseAuditingEntity.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/BaseAuditingEntity.java index 83b1dd5..af1b843 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/BaseAuditingEntity.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/BaseAuditingEntity.java @@ -31,8 +31,8 @@ public abstract class BaseAuditingEntity { @Id @GeneratedValue(strategy = GenerationType.UUID) - @Column(columnDefinition = "CHAR(36)") - private UUID id; + @Column(columnDefinition = "CHAR(36)", updatable = false, nullable = false) + private String id; @CreatedDate @Column(updatable = false) diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Event.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Event.java index 0c770c9..20bb6b3 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Event.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Event.java @@ -8,7 +8,6 @@ import jakarta.persistence.JoinColumn; import jakarta.persistence.FetchType; import jakarta.persistence.Column; -import jakarta.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/EventShow.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/EventShow.java index b7652a1..b1d2882 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/EventShow.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/EventShow.java @@ -14,7 +14,9 @@ import jakarta.persistence.FetchType; import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; import org.lbcc.bms.bms_monolith.common.enums.Genre; @@ -25,6 +27,8 @@ @Table(name = "event_shows") @Getter @SuperBuilder +@AllArgsConstructor +@NoArgsConstructor public class EventShow extends BaseAuditingEntity { @ElementCollection(targetClass = Genre.class) diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatTypeInShow.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatTypeInShow.java index 581241e..f421aca 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatTypeInShow.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/SeatTypeInShow.java @@ -5,7 +5,9 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.JoinColumn; import jakarta.persistence.Column; +import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; import java.math.BigDecimal; @@ -14,6 +16,8 @@ @Table(name = "seat_type_in_shows") @Getter @SuperBuilder +@AllArgsConstructor +@NoArgsConstructor public class SeatTypeInShow extends BaseAuditingEntity { @ManyToOne diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java index 894414e..f348a1e 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java @@ -29,8 +29,6 @@ public static ResponseEntity buildErrorResponse(HttpStatus sta return ResponseEntity.status(status).body(errorResponse); } - - @ExceptionHandler(value = MethodArgumentNotValidException.class) public ResponseEntity MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException exception) { diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatInShowResponse.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatInShowResponse.java index 6184e9a..0da96b3 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatInShowResponse.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatInShowResponse.java @@ -8,12 +8,12 @@ @Getter public class SeatInShowResponse { - private UUID seatTypeInShowId; + private String seatTypeInShowId; private String bookingStatus; // Constructors, Getters, and Setters - public SeatInShowResponse(UUID seatTypeInShowId, String bookingStatus) { + public SeatInShowResponse(String seatTypeInShowId, String bookingStatus) { this.seatTypeInShowId = seatTypeInShowId; this.bookingStatus = bookingStatus; } diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatTypeInShowResponse.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatTypeInShowResponse.java index c5601d1..c9f9eff 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatTypeInShowResponse.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/eventservice/dto/SeatTypeInShowResponse.java @@ -9,11 +9,11 @@ @Getter public class SeatTypeInShowResponse { - private UUID seatTypeId; + private String seatTypeId; private String seatTypeName; private BigDecimal price; - public SeatTypeInShowResponse(UUID seatTypeId, String seatTypeName, BigDecimal price) { + public SeatTypeInShowResponse(String seatTypeId, String seatTypeName, BigDecimal price) { this.seatTypeId = seatTypeId; this.seatTypeName = seatTypeName; this.price = price; diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/JwtUtils.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/JwtUtils.java index 6533589..9f7e970 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/JwtUtils.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/JwtUtils.java @@ -1,4 +1,3 @@ - package org.lbcc.bms.bms_monolith.userservice.common; import io.jsonwebtoken.*; @@ -18,10 +17,10 @@ public class JwtUtils { private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class); - @Value("${app.jwtSecret}") + @Value("${app.auth:jwt-secret}") private String jwtSecret; - @Value("${app.jwtExpirationMs}") + @Value("${app.auth.jwt-expiration-ms}") private int jwtExpirationMs; public String generateJwtToken(Authentication authentication) { diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleDataSeeder.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleDataSeeder.java index 156e715..a9f1790 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleDataSeeder.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleDataSeeder.java @@ -11,29 +11,32 @@ import java.time.Instant; import java.util.Arrays; import java.util.List; -import java.util.Random; +import java.util.UUID; @Component public class RoleDataSeeder { - @Autowired private RoleRepository roleRepository; + private final RoleRepository roleRepository; - @EventListener - @Transactional - public void LoadRoles(ContextRefreshedEvent event) { + public RoleDataSeeder(RoleRepository roleRepository) { + this.roleRepository = roleRepository; + } + + @EventListener + @Transactional + public void loadRoles(ContextRefreshedEvent event) { - List roles = Arrays.stream(RoleType.values()).toList(); + List roles = Arrays.stream(RoleType.values()).toList(); - for (RoleType erole : roles) { - if (roleRepository.findByName(erole) == null) { - Role role = new Role(); - role.setName(erole); - role.setDescription(erole.name()); - role.setCreatedBy("system"); - role.setCreatedDate(Instant.now()); - role.setLastModifiedDate(Instant.now()); - role.setLastModifiedBy("system"); - roleRepository.save(role); - } + for (RoleType roleType : roles) { + if (roleRepository.findByLabel(roleType) == null) { + Role role = new Role(); + role.setId(UUID.randomUUID().toString()); + role.setLabel(roleType); + role.setDescription(roleType.name()); + role.setCreatedBy("system"); + role.setCreatedDate(Instant.now()); + roleRepository.save(role); + } + } } - } } diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleFactory.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleFactory.java index 25140fd..072430e 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleFactory.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleFactory.java @@ -14,16 +14,16 @@ public class RoleFactory { public Role getInstance(String role) throws RoleNotFoundException { switch (role) { case "admin" -> { - return roleRepository.findByName(RoleType.ADMIN); + return roleRepository.findByLabel(RoleType.ADMIN); } case "user" -> { - return roleRepository.findByName(RoleType.USER); + return roleRepository.findByLabel(RoleType.USER); } case "vendor" -> { - return roleRepository.findByName(RoleType.VENDOR); + return roleRepository.findByLabel(RoleType.VENDOR); } case "guest" -> { - return roleRepository.findByName(RoleType.GUEST); + return roleRepository.findByLabel(RoleType.GUEST); } default -> throw new RoleNotFoundException("No role found for " + role); diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/BaseEntity.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/BaseEntity.java deleted file mode 100644 index 2287e9f..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/BaseEntity.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.lbcc.bms.bms_monolith.userservice.model; - -import jakarta.persistence.Column; -import jakarta.persistence.EntityListeners; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.MappedSuperclass; -import java.time.Instant; -import java.util.UUID; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.experimental.SuperBuilder; -import org.springframework.data.annotation.CreatedBy; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.annotation.LastModifiedBy; -import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -@AllArgsConstructor -@Getter -@MappedSuperclass -@NoArgsConstructor -@Setter -@SuperBuilder -@EntityListeners(AuditingEntityListener.class) -public abstract class BaseEntity { - - - - @CreatedDate - @Column(updatable = false) - private Instant createdDate; - - @LastModifiedDate - @Column(insertable = false) - private Instant lastModifiedDate; - - @CreatedBy - @Column(updatable = false, length = 10) - private String createdBy; - - @LastModifiedBy - @Column(insertable = false, length = 10) - private String lastModifiedBy; -} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/Role.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/Role.java index ae3e77e..5dbaadd 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/Role.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/Role.java @@ -3,21 +3,23 @@ import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Data; +import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; +import org.lbcc.bms.bms_monolith.common.entity.BaseAuditingEntity; import org.lbcc.bms.bms_monolith.userservice.common.RoleType; +@EqualsAndHashCode(callSuper = true) @Data @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "roles") -public class Role extends BaseEntity { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "role_id") - private Long roleId; - @Enumerated(EnumType.STRING) - private RoleType name; +public class Role extends BaseAuditingEntity { - @Column private String description; + @Enumerated(EnumType.STRING) + @Column(nullable = false) + private RoleType label; + + @Column(nullable = false, length = 50) + private String description; } diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/User.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/User.java index 81910d7..2ab5a5b 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/User.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/User.java @@ -1,38 +1,40 @@ package org.lbcc.bms.bms_monolith.userservice.model; import jakarta.persistence.*; -import lombok.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; import org.lbcc.bms.bms_monolith.common.entity.BaseAuditingEntity; -import java.util.ArrayList; import java.util.HashSet; -import java.util.List; import java.util.Set; -@Data @AllArgsConstructor -@NoArgsConstructor -@Builder +@SuperBuilder +@Data @Entity -@Table(name="users") -public class User extends BaseEntity { - +@EqualsAndHashCode(callSuper = true) +@NoArgsConstructor +@Table(name = "users") +public class User extends BaseAuditingEntity { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "user_id") - private Long id; - private String username; - private String email; - private String phone; - private String password; - private boolean enabled = true; + private String username; + private String email; + @Column(columnDefinition = "CHAR(10)") + private String phone; + private String password; + @Builder.Default + @Column(columnDefinition = "TINYINT(1)") + private Boolean isActive = true; - @ManyToMany(fetch = FetchType.EAGER) - @JoinTable( - name = "user_roles", - joinColumns = {@JoinColumn(name = "user_id")}, - inverseJoinColumns = {@JoinColumn(name = "role_id")}) - private Set roles = new HashSet<>(); + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable( + name = "user_roles", + joinColumns = {@JoinColumn(name = "user_id")}, + inverseJoinColumns = {@JoinColumn(name = "role_id")}) + @Builder.Default + private Set roles = new HashSet<>(); } diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/RoleRepository.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/RoleRepository.java index b1d5096..6c8ca49 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/RoleRepository.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/RoleRepository.java @@ -7,5 +7,5 @@ @Repository public interface RoleRepository extends JpaRepository { - Role findByName(RoleType name); + Role findByLabel(RoleType label); } diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/UserRepository.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/UserRepository.java index 081ff0f..40033b8 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/UserRepository.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/UserRepository.java @@ -5,9 +5,12 @@ import org.springframework.stereotype.Repository; import java.util.Optional; + @Repository public interface UserRepository extends JpaRepository { Optional findByEmail(String email); + Boolean existsByUsername(String username); + Boolean existsByEmail(String email); } diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java index df78109..a284de5 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java @@ -22,17 +22,20 @@ @Component public class AuthServiceImpl implements AuthService { - @Autowired - private UserService userService; + private final UserService userService; - private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); @Autowired private RoleFactory roleFactory; + public AuthServiceImpl(UserService userService) { + this.userService = userService; + } + @Override public ResponseEntity signUpUser(SignUpRequestDto signUpRequestDto) - throws UserAlreadyExistsException , RoleNotFoundException { + throws UserAlreadyExistsException, RoleNotFoundException { if (userService.existsByEmail(signUpRequestDto.getEmail())) { throw new UserAlreadyExistsException("Registration Failed: Provided email already exists. Try sign in or provide another email."); } @@ -44,7 +47,6 @@ public ResponseEntity signUpUser(SignUpRequestDto signUpRequestDto) userService.save(user); return ResponseEntity.status(HttpStatus.CREATED).body( ApiResponse.builder() - // .isSuccess(true) .message("User account has been successfully created!") .build() ); @@ -55,13 +57,12 @@ private User createUser(SignUpRequestDto signUpRequestDto) throws RoleNotFoundEx .email(signUpRequestDto.getEmail()) .username(signUpRequestDto.getUserName()) .password(signUpRequestDto.getPassword()) - .enabled(true) .roles(determineRoles(signUpRequestDto.getRoles())) .build(); } private Set determineRoles(Set strRoles) throws RoleNotFoundException { - Set roles = new HashSet<>(); + Set roles = new HashSet<>(); if (strRoles == null) { roles.add(roleFactory.getInstance("user")); diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsImpl.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsImpl.java index a6f1c4c..7a07f3f 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsImpl.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsImpl.java @@ -19,7 +19,7 @@ @Data public class UserDetailsImpl implements UserDetails { @Serial private static final long serialVersionUID = 1L; - private Long id; + private String id; private String username; private String email; @JsonIgnore private String password; @@ -29,7 +29,7 @@ public class UserDetailsImpl implements UserDetails { public static UserDetailsImpl build(User user) { List authorities = user.getRoles().stream() - .map(role -> new SimpleGrantedAuthority(role.getName().name())) + .map(role -> new SimpleGrantedAuthority(role.getLabel().name())) .collect(Collectors.toList()); return new UserDetailsImpl( @@ -38,7 +38,7 @@ public static UserDetailsImpl build(User user) { user.getEmail(), user.getPassword(), authorities, - user.isEnabled()); + user.getIsActive()); } @Override diff --git a/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml b/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml index c63a05b..8f56af0 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml +++ b/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml @@ -1,4 +1,4 @@ -Spring: +spring: application: name: BMS Monolith datasource: @@ -9,7 +9,7 @@ Spring: jpa: properties: hibernate: - dialect: org.hibernate.dialect.MySQLDialect + dialect: org.hibernate.dialect.MySQL8Dialect hibernate: ddl-auto: validate show-sql: true @@ -18,4 +18,8 @@ Spring: enabled: true server: servlet: - context-path: /api/v1 \ No newline at end of file + context-path: /api/v1 +app: + auth: + jwt-secret: ${JWT_SECRET:some_secret} + jwt-expiration-ms: ${JWT_EXPIRATION_MS:50000} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/resources/db/changelog/changelog-master.xml b/book-my-show/backend/java/bms-monolith/src/main/resources/db/changelog/changelog-master.xml index 0bbd586..ba0c725 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/resources/db/changelog/changelog-master.xml +++ b/book-my-show/backend/java/bms-monolith/src/main/resources/db/changelog/changelog-master.xml @@ -7,4 +7,5 @@ + diff --git a/book-my-show/backend/java/bms-monolith/src/main/resources/db/changelog/v1.0/add-auth-tables.xml b/book-my-show/backend/java/bms-monolith/src/main/resources/db/changelog/v1.0/add-auth-tables.xml new file mode 100644 index 0000000..9d0af54 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/resources/db/changelog/v1.0/add-auth-tables.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From 407f4da93353465dab610ed888fd698a58f9a77f Mon Sep 17 00:00:00 2001 From: rohitnandi12 Date: Sat, 7 Dec 2024 15:09:11 +0530 Subject: [PATCH 5/6] #11 Working registration flow. --- .../org/lbcc/bms/bms_monolith/security/WebSecurityConfig.java | 2 +- .../bms_monolith/userservice/service/impl/AuthServiceImpl.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/WebSecurityConfig.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/WebSecurityConfig.java index c0071cd..3568aad 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/WebSecurityConfig.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/WebSecurityConfig.java @@ -27,7 +27,7 @@ @EnableMethodSecurity public class WebSecurityConfig{ - List publicApis = List.of( "/api/auth/**"); + List publicApis = List.of( "/auth/**"); private final AuthEntryPointJwt unauthorizedHandler = new AuthEntryPointJwt(); UserDetailsServiceImpl userDetailsService = new UserDetailsServiceImpl(); diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java index a284de5..747f69e 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java @@ -68,7 +68,7 @@ private Set determineRoles(Set strRoles) throws RoleNotFoundExcept roles.add(roleFactory.getInstance("user")); } else { for (String role : strRoles) { - roles.add(roleFactory.getInstance(role)); + roles.add(roleFactory.getInstance(role.toLowerCase())); } } return roles; From 2806b49bb16c5c2e353a5172365df26792fbf706 Mon Sep 17 00:00:00 2001 From: rohitnandi12 Date: Sat, 7 Dec 2024 19:10:39 +0530 Subject: [PATCH 6/6] #11 Working username password authentication and authorization. --- .../constants/BMSErrorMessageConstants.java | 10 ++ .../constants/BMSSuccessMessageConstants.java | 8 ++ .../entity/RegisteredUser.java} | 16 ++- .../model => common/entity}/Role.java | 5 +- .../common => common/enums}/RoleType.java | 3 +- .../exception/GlobalExceptionHandler.java | 4 +- .../security/AuthTokenFilter.java | 67 ---------- .../security/WebSecurityConfig.java | 88 ------------- .../bootstrap}/RoleDataSeeder.java | 8 +- .../config}/AuthEntryPointJwt.java | 5 +- .../config/JwtAuthenticationFilter.java | 85 +++++++++++++ .../config/SecurityConfiguration.java | 108 ++++++++++++++++ .../controller/LoginController.java | 36 ++++++ .../controller/RegisterController.java | 37 ++++++ .../uesrnamepassword/dto/LogInRequest.java | 8 ++ .../uesrnamepassword/dto/LogInResponse.java | 7 ++ .../uesrnamepassword/dto/SignUpRequest.java} | 11 +- .../uesrnamepassword/dto/SignUpResponse.java | 6 + .../exeception/RoleNotFoundException.java | 7 ++ .../UserAlreadyExistsException.java | 7 ++ .../model/UserDetailsModel.java | 60 +++++++++ .../repository/RegisteredUserRepository.java | 17 +++ .../repository/RoleRepository.java | 6 +- .../service/DaoUserDetailsService.java | 30 +++++ .../uesrnamepassword/service/JwtService.java | 117 ++++++++++++++++++ .../service/LoginService.java | 49 ++++++++ .../service/RegisterService.java | 66 ++++++++++ .../service/RegisteredUserService.java | 27 ++++ .../service/RoleFactoryService.java | 27 ++++ .../userservice/common/JwtUtils.java | 68 ---------- .../userservice/common/RoleFactory.java | 33 ----- .../controller/AuthController.java | 31 ----- .../controller/UserController.java | 18 --- .../exeception/RoleNotFoundException.java | 7 -- .../UserAlreadyExistsException.java | 7 -- .../exeception/UsernameNotFoundException.java | 7 -- .../repository/UserRepository.java | 16 --- .../userservice/service/AuthService.java | 14 --- .../userservice/service/UserService.java | 11 -- .../service/impl/AuthServiceImpl.java | 76 ------------ .../service/impl/UserDetailsImpl.java | 67 ---------- .../service/impl/UserDetailsServiceImpl.java | 27 ---- .../service/impl/UserServiceImpl.java | 34 ----- .../src/main/resources/application.yaml | 5 +- .../db/changelog/v1.0/add-auth-tables.xml | 4 +- 45 files changed, 748 insertions(+), 602 deletions(-) create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/constants/BMSErrorMessageConstants.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/constants/BMSSuccessMessageConstants.java rename book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/{userservice/model/User.java => common/entity/RegisteredUser.java} (76%) rename book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/{userservice/model => common/entity}/Role.java (72%) rename book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/{userservice/common => common/enums}/RoleType.java (56%) delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/AuthTokenFilter.java delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/WebSecurityConfig.java rename book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/{userservice/common => security/uesrnamepassword/bootstrap}/RoleDataSeeder.java (81%) rename book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/{ => uesrnamepassword/config}/AuthEntryPointJwt.java (91%) create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/config/JwtAuthenticationFilter.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/config/SecurityConfiguration.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/controller/LoginController.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/controller/RegisterController.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/dto/LogInRequest.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/dto/LogInResponse.java rename book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/{userservice/common/SignUpRequestDto.java => security/uesrnamepassword/dto/SignUpRequest.java} (69%) create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/dto/SignUpResponse.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/exeception/RoleNotFoundException.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/exeception/UserAlreadyExistsException.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/model/UserDetailsModel.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/repository/RegisteredUserRepository.java rename book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/{userservice => security/uesrnamepassword}/repository/RoleRepository.java (56%) create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/DaoUserDetailsService.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/JwtService.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/LoginService.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/RegisterService.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/RegisteredUserService.java create mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/RoleFactoryService.java delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/JwtUtils.java delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleFactory.java delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/AuthController.java delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/UserController.java delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/RoleNotFoundException.java delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UserAlreadyExistsException.java delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UsernameNotFoundException.java delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/UserRepository.java delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/AuthService.java delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/UserService.java delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsImpl.java delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsServiceImpl.java delete mode 100644 book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserServiceImpl.java diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/constants/BMSErrorMessageConstants.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/constants/BMSErrorMessageConstants.java new file mode 100644 index 0000000..fa5912d --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/constants/BMSErrorMessageConstants.java @@ -0,0 +1,10 @@ +package org.lbcc.bms.bms_monolith.common.constants; + +public final class BMSErrorMessageConstants { + private BMSErrorMessageConstants() { + } + + public static final String UNEXPECTED_ERROR_MESSAGE = "An unexpected error occurred"; + public static final String UNEXPECTED_ERROR_CODE = "UNEXPECTED_ERROR"; + public static final String EVENT_SERVICE_ERROR = "EVENT_SERVICE_ERROR"; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/constants/BMSSuccessMessageConstants.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/constants/BMSSuccessMessageConstants.java new file mode 100644 index 0000000..cfd9fc1 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/constants/BMSSuccessMessageConstants.java @@ -0,0 +1,8 @@ +package org.lbcc.bms.bms_monolith.common.constants; + +public final class BMSSuccessMessageConstants { + private BMSSuccessMessageConstants() { + } + + public static final String EVENT_SUCCESS_MESSAGE = "Events fetched successfully"; +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/User.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/RegisteredUser.java similarity index 76% rename from book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/User.java rename to book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/RegisteredUser.java index 2ab5a5b..2f16836 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/User.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/RegisteredUser.java @@ -1,5 +1,6 @@ -package org.lbcc.bms.bms_monolith.userservice.model; +package org.lbcc.bms.bms_monolith.common.entity; +import com.fasterxml.jackson.annotation.JsonIgnore; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; @@ -7,7 +8,6 @@ import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; -import org.lbcc.bms.bms_monolith.common.entity.BaseAuditingEntity; import java.util.HashSet; import java.util.Set; @@ -18,14 +18,22 @@ @Entity @EqualsAndHashCode(callSuper = true) @NoArgsConstructor -@Table(name = "users") -public class User extends BaseAuditingEntity { +@Table(name = "registered_users") +public class RegisteredUser extends BaseAuditingEntity { + @Column(length = 20) private String username; + + @Column(length = 25) private String email; + @Column(columnDefinition = "CHAR(10)") private String phone; + + @Column(length = 20) + @JsonIgnore private String password; + @Builder.Default @Column(columnDefinition = "TINYINT(1)") private Boolean isActive = true; diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/Role.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Role.java similarity index 72% rename from book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/Role.java rename to book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Role.java index 5dbaadd..ba74d26 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/model/Role.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/entity/Role.java @@ -1,12 +1,11 @@ -package org.lbcc.bms.bms_monolith.userservice.model; +package org.lbcc.bms.bms_monolith.common.entity; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; -import org.lbcc.bms.bms_monolith.common.entity.BaseAuditingEntity; -import org.lbcc.bms.bms_monolith.userservice.common.RoleType; +import org.lbcc.bms.bms_monolith.common.enums.RoleType; @EqualsAndHashCode(callSuper = true) @Data diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleType.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/RoleType.java similarity index 56% rename from book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleType.java rename to book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/RoleType.java index e893a2b..0d64ed4 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleType.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/enums/RoleType.java @@ -1,9 +1,8 @@ -package org.lbcc.bms.bms_monolith.userservice.common; +package org.lbcc.bms.bms_monolith.common.enums; public enum RoleType { GUEST, VENDOR, ADMIN, USER, - } diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java index f348a1e..7080791 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/common/exception/GlobalExceptionHandler.java @@ -2,8 +2,8 @@ import org.lbcc.bms.bms_monolith.common.constants.BMSConstants; import org.lbcc.bms.bms_monolith.common.response.ApiErrorResponse; -import org.lbcc.bms.bms_monolith.userservice.exeception.RoleNotFoundException; -import org.lbcc.bms.bms_monolith.userservice.exeception.UserAlreadyExistsException; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.exeception.RoleNotFoundException; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.exeception.UserAlreadyExistsException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/AuthTokenFilter.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/AuthTokenFilter.java deleted file mode 100644 index 7d2667e..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/AuthTokenFilter.java +++ /dev/null @@ -1,67 +0,0 @@ - -package org.lbcc.bms.bms_monolith.security; - -import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import org.lbcc.bms.bms_monolith.userservice.common.JwtUtils; -import org.lbcc.bms.bms_monolith.userservice.service.impl.UserDetailsServiceImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -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.util.StringUtils; -import org.springframework.web.filter.OncePerRequestFilter; - -import java.io.IOException; - - -public class AuthTokenFilter extends OncePerRequestFilter { - @Autowired - private JwtUtils jwtUtils; - - @Autowired - private UserDetailsServiceImpl userDetailsService; - - private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class); - - @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException { - try { - String jwt = parseJwt(request); - if (jwt != null && jwtUtils.validateJwtToken(jwt)) { - String username = jwtUtils.getUserNameFromJwtToken(jwt); - - UserDetails userDetails = userDetailsService.loadUserByUsername(username); - UsernamePasswordAuthenticationToken authentication = - new UsernamePasswordAuthenticationToken( - userDetails, - null, - userDetails.getAuthorities()); - authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); - - SecurityContextHolder.getContext().setAuthentication(authentication); - } - } catch (Exception e) { - logger.error("Cannot set user authentication: {}", e); - } - - filterChain.doFilter(request, response); - } - - private String parseJwt(HttpServletRequest request) { - String headerAuth = request.getHeader("Authorization"); - - if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) { - return headerAuth.substring(7); - } - - return null; - } -} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/WebSecurityConfig.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/WebSecurityConfig.java deleted file mode 100644 index 3568aad..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/WebSecurityConfig.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.lbcc.bms.bms_monolith.security; - - -import org.lbcc.bms.bms_monolith.userservice.service.impl.UserDetailsServiceImpl; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.dao.DaoAuthenticationProvider; -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.WebSecurityCustomizer; -import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import org.springframework.security.web.util.matcher.AntPathRequestMatcher; -import org.springframework.security.web.util.matcher.RequestMatcher; - -import java.util.List; - - -@Configuration -@EnableMethodSecurity -public class WebSecurityConfig{ - - List publicApis = List.of( "/auth/**"); - - private final AuthEntryPointJwt unauthorizedHandler = new AuthEntryPointJwt(); - UserDetailsServiceImpl userDetailsService = new UserDetailsServiceImpl(); - - @Bean - public AuthTokenFilter authenticationJwtTokenFilter() { - return new AuthTokenFilter(); - } - - @Bean - public DaoAuthenticationProvider authenticationProvider() { - - - DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); - - authProvider.setUserDetailsService(userDetailsService); - authProvider.setPasswordEncoder(passwordEncoder()); - - return authProvider; - } - - @Bean - public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) - throws Exception { - return authConfig.getAuthenticationManager(); - } - - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } - - @Bean - public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - - http.csrf(AbstractHttpConfigurer::disable) - - .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler)) - .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) - - .authorizeHttpRequests(auth -> - auth.requestMatchers(publicApis.stream() - .map(AntPathRequestMatcher::new) - .toArray(RequestMatcher[]::new)).permitAll() - .anyRequest().authenticated() - ); - - http.authenticationProvider(authenticationProvider()); - - http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); - - return http.build(); - } - @Bean - public WebSecurityCustomizer webSecurityCustomizer() { - return (web) -> web.ignoring().requestMatchers(publicApis.toArray(String[]::new)); - } -} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleDataSeeder.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/bootstrap/RoleDataSeeder.java similarity index 81% rename from book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleDataSeeder.java rename to book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/bootstrap/RoleDataSeeder.java index a9f1790..4c40e64 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleDataSeeder.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/bootstrap/RoleDataSeeder.java @@ -1,9 +1,9 @@ -package org.lbcc.bms.bms_monolith.userservice.common; +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.bootstrap; import jakarta.transaction.Transactional; -import org.lbcc.bms.bms_monolith.userservice.model.Role; -import org.lbcc.bms.bms_monolith.userservice.repository.RoleRepository; -import org.springframework.beans.factory.annotation.Autowired; +import org.lbcc.bms.bms_monolith.common.entity.Role; +import org.lbcc.bms.bms_monolith.common.enums.RoleType; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.repository.RoleRepository; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/AuthEntryPointJwt.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/config/AuthEntryPointJwt.java similarity index 91% rename from book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/AuthEntryPointJwt.java rename to book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/config/AuthEntryPointJwt.java index d58801a..de9cd33 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/AuthEntryPointJwt.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/config/AuthEntryPointJwt.java @@ -1,5 +1,4 @@ - -package org.lbcc.bms.bms_monolith.security; +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.config; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.http.HttpServletRequest; @@ -28,7 +27,7 @@ public void commence(HttpServletRequest request, HttpServletResponse response, A response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - final Map body = new HashMap<>(); + final Map body = new HashMap<>(); body.put("status", HttpServletResponse.SC_UNAUTHORIZED); body.put("error", "Unauthorized"); body.put("message", authException.getMessage()); diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/config/JwtAuthenticationFilter.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/config/JwtAuthenticationFilter.java new file mode 100644 index 0000000..3456582 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/config/JwtAuthenticationFilter.java @@ -0,0 +1,85 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.config; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.service.JwtService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.lang.NonNull; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; +import org.springframework.web.servlet.HandlerExceptionResolver; + +import java.util.Optional; + + +@Component +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class); + + private final JwtService jwtService; + private final UserDetailsService userDetailsService; + private final HandlerExceptionResolver handlerExceptionResolver; + + public JwtAuthenticationFilter( + JwtService jwtService, UserDetailsService userDetailsService, + HandlerExceptionResolver handlerExceptionResolver + ) { + this.jwtService = jwtService; + this.userDetailsService = userDetailsService; + this.handlerExceptionResolver = handlerExceptionResolver; + } + + @Override + protected void doFilterInternal( + @NonNull HttpServletRequest request, + @NonNull HttpServletResponse response, + @NonNull FilterChain filterChain + ) { + try { + + final Optional jwt = parseJwt(request); + if (jwt.isEmpty() || !jwtService.validateJwtToken(jwt.get())) { + filterChain.doFilter(request, response); + return; + } + + String username = jwtService.extractUsername(jwt.get()); + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + + if (username != null && authentication == null) { + UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); + + if (jwtService.isTokenValid(jwt.get(), userDetails)) { + UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); + + authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + SecurityContextHolder.getContext().setAuthentication(authToken); + } + } + + filterChain.doFilter(request, response); + } catch (Exception exception) { + handlerExceptionResolver.resolveException(request, response, null, exception); + } + + } + + private Optional parseJwt(HttpServletRequest request) { + String headerAuth = request.getHeader("Authorization"); + + if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) { + return Optional.of(headerAuth.substring(7)); + } + return Optional.empty(); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/config/SecurityConfiguration.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/config/SecurityConfiguration.java new file mode 100644 index 0000000..6e34334 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/config/SecurityConfiguration.java @@ -0,0 +1,108 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +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.configuration.WebSecurityCustomizer; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; +import org.springframework.security.web.util.matcher.RequestMatcher; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import java.util.List; + +@Configuration(proxyBeanMethods = false) +@EnableWebSecurity +@EnableMethodSecurity +public class SecurityConfiguration { + + private final UserDetailsService userDetailsService; + private final AuthEntryPointJwt unauthorizedHandler; + private final JwtAuthenticationFilter jwtAuthenticationFilter; + //TODO: Load this from application properties + List publicApis = List.of("/auth/**"); + + public SecurityConfiguration( + UserDetailsService userDetailsService, AuthEntryPointJwt unauthorizedHandler, + JwtAuthenticationFilter jwtAuthenticationFilter + ) { + this.userDetailsService = userDetailsService; + this.unauthorizedHandler = unauthorizedHandler; + this.jwtAuthenticationFilter = jwtAuthenticationFilter; + } + + @Bean + public BCryptPasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception { + return config.getAuthenticationManager(); + } + + @Bean + public AuthenticationProvider authenticationProvider() { + DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); + + daoAuthenticationProvider.setUserDetailsService(userDetailsService); + daoAuthenticationProvider.setPasswordEncoder(passwordEncoder()); + + return daoAuthenticationProvider; + } + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + + http.csrf(AbstractHttpConfigurer::disable) + .authorizeHttpRequests(authorize -> authorize + .requestMatchers( + publicApis.stream() + .map(AntPathRequestMatcher::new) + .toArray(RequestMatcher[]::new) + ) + .permitAll() + .anyRequest() + .authenticated() + ) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler)) + .authenticationProvider(authenticationProvider()) + .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); + + return http.build(); + } + + @Bean + CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration configuration = new CorsConfiguration(); + + configuration.setAllowedOrigins(List.of("http://localhost:8005")); + configuration.setAllowedMethods(List.of("GET", "POST")); + configuration.setAllowedHeaders(List.of("Authorization", "Content-Type")); + + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + + source.registerCorsConfiguration("/**", configuration); + + return source; + } + + @Bean + public WebSecurityCustomizer webSecurityCustomizer() { + return (web) -> web.ignoring().requestMatchers(publicApis.toArray(String[]::new)); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/controller/LoginController.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/controller/LoginController.java new file mode 100644 index 0000000..da01e2c --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/controller/LoginController.java @@ -0,0 +1,36 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.controller; + +import jakarta.validation.Valid; +import org.lbcc.bms.bms_monolith.common.response.ApiResponse; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.dto.LogInRequest; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.dto.LogInResponse; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.service.LoginService; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/auth/login") +public class LoginController { + + private final LoginService loginService; + + public LoginController(LoginService loginService) { + this.loginService = loginService; + } + + @PostMapping + public ResponseEntity> login( + @RequestBody @Valid LogInRequest logInRequest + ) { + LogInResponse loginResponse = loginService.login(logInRequest); + ApiResponse response = ApiResponse.builder() + .success(true) + .message("Login successful!!") + .data(loginResponse) + .build(); + return ResponseEntity.ok(response); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/controller/RegisterController.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/controller/RegisterController.java new file mode 100644 index 0000000..0a23476 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/controller/RegisterController.java @@ -0,0 +1,37 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.controller; + +import jakarta.validation.Valid; +import org.lbcc.bms.bms_monolith.common.response.ApiResponse; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.dto.SignUpRequest; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.dto.SignUpResponse; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.service.RegisterService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/auth/register") +public class RegisterController { + + private final RegisterService registerService; + + public RegisterController(RegisterService registerService) { + this.registerService = registerService; + } + + @PostMapping + public ResponseEntity> registerUser( + @RequestBody @Valid SignUpRequest signUpRequest + ) { + SignUpResponse signUpUser = registerService.signUpUser(signUpRequest); + ApiResponse response = ApiResponse.builder() + .success(true) + .message("User registered successfully!!") + .data(signUpUser) + .build(); + return ResponseEntity.status(HttpStatus.CREATED).body(response); + } +} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/dto/LogInRequest.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/dto/LogInRequest.java new file mode 100644 index 0000000..d3de372 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/dto/LogInRequest.java @@ -0,0 +1,8 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.dto; + +public record LogInRequest( + //TODO: Add validation + String username, + String password +) { +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/dto/LogInResponse.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/dto/LogInResponse.java new file mode 100644 index 0000000..b37c199 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/dto/LogInResponse.java @@ -0,0 +1,7 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.dto; + +public record LogInResponse( + String token, + long expiresIn +) { +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/SignUpRequestDto.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/dto/SignUpRequest.java similarity index 69% rename from book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/SignUpRequestDto.java rename to book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/dto/SignUpRequest.java index 4080f22..357297c 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/SignUpRequestDto.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/dto/SignUpRequest.java @@ -1,4 +1,4 @@ -package org.lbcc.bms.bms_monolith.userservice.common; +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.dto; import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotBlank; @@ -6,18 +6,17 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -import org.springframework.beans.factory.annotation.Autowired; import java.util.Set; @Data @AllArgsConstructor @NoArgsConstructor -public class SignUpRequestDto { +public class SignUpRequest { @NotBlank(message = "Username is required!") - @Size(min= 3, message = "Username must have atleast 3 characters!") - @Size(max= 20, message = "Username can have have atmost 20 characters!") - private String userName; + @Size(min = 3, message = "Username must have atleast 3 characters!") + @Size(max = 20, message = "Username can have have atmost 20 characters!") + private String username; @Email(message = "Email is not in valid format!") @NotBlank(message = "Email is required!") diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/dto/SignUpResponse.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/dto/SignUpResponse.java new file mode 100644 index 0000000..d49a60d --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/dto/SignUpResponse.java @@ -0,0 +1,6 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.dto; + +public record SignUpResponse( + String username +) { +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/exeception/RoleNotFoundException.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/exeception/RoleNotFoundException.java new file mode 100644 index 0000000..365350e --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/exeception/RoleNotFoundException.java @@ -0,0 +1,7 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.exeception; + +public class RoleNotFoundException extends RuntimeException { + public RoleNotFoundException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/exeception/UserAlreadyExistsException.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/exeception/UserAlreadyExistsException.java new file mode 100644 index 0000000..7be1bd9 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/exeception/UserAlreadyExistsException.java @@ -0,0 +1,7 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.exeception; + +public class UserAlreadyExistsException extends RuntimeException { + public UserAlreadyExistsException(String message) { + super(message); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/model/UserDetailsModel.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/model/UserDetailsModel.java new file mode 100644 index 0000000..632d263 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/model/UserDetailsModel.java @@ -0,0 +1,60 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import org.lbcc.bms.bms_monolith.common.entity.RegisteredUser; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.io.Serial; +import java.util.Collection; +import java.util.stream.Collectors; + +@AllArgsConstructor +@Data +public class UserDetailsModel implements UserDetails { + + @Serial + private static final long serialVersionUID = -4335856020700036116L; + private RegisteredUser registeredUser; + + @Override + public Collection getAuthorities() { + + return registeredUser.getRoles().stream() + .map(role -> new SimpleGrantedAuthority(role.getLabel().name())) + .collect(Collectors.toList()); + } + + @Override + public String getPassword() { + return registeredUser.getPassword(); + } + + @Override + public String getUsername() { + return registeredUser.getUsername(); + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return registeredUser.getIsActive(); + } +} + diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/repository/RegisteredUserRepository.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/repository/RegisteredUserRepository.java new file mode 100644 index 0000000..405421e --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/repository/RegisteredUserRepository.java @@ -0,0 +1,17 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.repository; + +import org.lbcc.bms.bms_monolith.common.entity.RegisteredUser; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface RegisteredUserRepository extends JpaRepository { + + Optional findByUsername(String email); + + Boolean existsByUsername(String username); + + Boolean existsByEmail(String email); +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/RoleRepository.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/repository/RoleRepository.java similarity index 56% rename from book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/RoleRepository.java rename to book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/repository/RoleRepository.java index 6c8ca49..76090fa 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/RoleRepository.java +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/repository/RoleRepository.java @@ -1,7 +1,7 @@ -package org.lbcc.bms.bms_monolith.userservice.repository; +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.repository; -import org.lbcc.bms.bms_monolith.userservice.common.RoleType; -import org.lbcc.bms.bms_monolith.userservice.model.Role; +import org.lbcc.bms.bms_monolith.common.entity.Role; +import org.lbcc.bms.bms_monolith.common.enums.RoleType; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/DaoUserDetailsService.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/DaoUserDetailsService.java new file mode 100644 index 0000000..fc990b9 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/DaoUserDetailsService.java @@ -0,0 +1,30 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.service; + +import org.lbcc.bms.bms_monolith.common.entity.RegisteredUser; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.model.UserDetailsModel; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.repository.RegisteredUserRepository; +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; + +@Service +public class DaoUserDetailsService implements UserDetailsService { + + private final RegisteredUserRepository registeredUserRepository; + + public DaoUserDetailsService(RegisteredUserRepository registeredUserRepository) { + this.registeredUserRepository = registeredUserRepository; + } + + @Override + public UserDetails loadUserByUsername(String username) { + RegisteredUser registeredUser = + registeredUserRepository + .findByUsername(username) + .orElseThrow( + () -> new UsernameNotFoundException("User Not Found with username: " + username)); + + return new UserDetailsModel(registeredUser); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/JwtService.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/JwtService.java new file mode 100644 index 0000000..cdaf6b2 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/JwtService.java @@ -0,0 +1,117 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.service; + +import io.jsonwebtoken.*; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Service; + +import java.security.Key; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +@Service +public class JwtService { + private static final Logger logger = LoggerFactory.getLogger(JwtService.class); + + private final String secretKey; + private final int expirationInMs; + + public JwtService( + @Value("${app.auth.jwt.secret-key}") String secretKey, + @Value("${app.auth.jwt.expiration-in-ms}") int expirationInMs + ) { + this.secretKey = secretKey; + this.expirationInMs = expirationInMs; + } + + public long getDefaultExpirationTime() { + return expirationInMs; + } + + private Key getSignInKey() { + byte[] keyBytes = Decoders.BASE64.decode(secretKey); + return Keys.hmacShaKeyFor(keyBytes); + } + + private Claims extractAllClaims(String token) { + return Jwts + .parserBuilder() + .setSigningKey(getSignInKey()) + .build() + .parseClaimsJws(token) + .getBody(); + } + + public T extractClaim(String token, Function claimsResolver) { + final Claims claims = extractAllClaims(token); + return claimsResolver.apply(claims); + } + + public String generateToken(UserDetails userDetails) { + return generateToken(new HashMap<>(), userDetails); + } + + public String generateToken(Map extraClaims, UserDetails userDetails) { + return buildToken(extraClaims, userDetails, expirationInMs); + } + + private String buildToken( + Map extraClaims, + UserDetails userDetails, + long expiration + ) { + return Jwts + .builder() + .setClaims(extraClaims) + .setSubject(userDetails.getUsername()) + .setIssuedAt(new Date(System.currentTimeMillis())) + .setExpiration(new Date(System.currentTimeMillis() + expiration)) + .signWith(getSignInKey(), SignatureAlgorithm.HS256) + .compact(); + } + + + public String extractUsername(String token) { + return extractClaim(token, Claims::getSubject); + } + + + public boolean isTokenValid(String token, UserDetails userDetails) { + final String username = extractUsername(token); + return (username.equals(userDetails.getUsername())) && !isTokenExpired(token); + } + + private boolean isTokenExpired(String token) { + return extractExpiration(token).before(new Date()); + } + + + private Date extractExpiration(String token) { + return extractClaim(token, Claims::getExpiration); + } + + + public boolean validateJwtToken(String authToken) { + try { + Jwts.parserBuilder().setSigningKey(getSignInKey()).build().parse(authToken); + return true; + } catch (MalformedJwtException e) { + logger.error("Invalid JWT token: {}", e.getMessage()); + } catch (ExpiredJwtException e) { + logger.error("JWT token is expired: {}", e.getMessage()); + } catch (UnsupportedJwtException e) { + logger.error("JWT token is unsupported: {}", e.getMessage()); + } catch (IllegalArgumentException e) { + logger.error("JWT claims string is empty: {}", e.getMessage()); + } + + return false; + } +} + diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/LoginService.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/LoginService.java new file mode 100644 index 0000000..29346a5 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/LoginService.java @@ -0,0 +1,49 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.service; + +import org.lbcc.bms.bms_monolith.common.entity.RegisteredUser; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.dto.LogInRequest; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.dto.LogInResponse; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.model.UserDetailsModel; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.repository.RegisteredUserRepository; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Service +public class LoginService { + + private final JwtService jwtService; + private final AuthenticationManager authenticationManager; + private final RegisteredUserRepository registeredUserRepository; + + public LoginService( + JwtService jwtService, AuthenticationManager authenticationManager, + RegisteredUserRepository registeredUserRepository + ) { + this.jwtService = jwtService; + this.authenticationManager = authenticationManager; + this.registeredUserRepository = registeredUserRepository; + } + + + public LogInResponse login(LogInRequest loginInRequest) { + + authenticationManager.authenticate( + new UsernamePasswordAuthenticationToken( + loginInRequest.username(), + loginInRequest.password() + ) + ); + + RegisteredUser authenticatedUser = registeredUserRepository + .findByUsername(loginInRequest.username()) + .orElseThrow(() -> new UsernameNotFoundException("Username not found!!")); + String jwtToken = jwtService.generateToken(new UserDetailsModel(authenticatedUser)); + + return new LogInResponse( + jwtToken, + jwtService.getDefaultExpirationTime() + ); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/RegisterService.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/RegisterService.java new file mode 100644 index 0000000..601ed06 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/RegisterService.java @@ -0,0 +1,66 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.service; + +import org.lbcc.bms.bms_monolith.common.entity.RegisteredUser; +import org.lbcc.bms.bms_monolith.common.entity.Role; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.dto.SignUpRequest; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.dto.SignUpResponse; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.exeception.RoleNotFoundException; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.exeception.UserAlreadyExistsException; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Component; + +import java.util.HashSet; +import java.util.Set; + +@Component +public class RegisterService { + + private final RegisteredUserService registeredUserService; + private final RoleFactoryService roleFactory; + private final PasswordEncoder passwordEncoder; + + public RegisterService( + RegisteredUserService registeredUserService, RoleFactoryService roleFactory, + PasswordEncoder passwordEncoder + ) { + this.registeredUserService = registeredUserService; + this.roleFactory = roleFactory; + this.passwordEncoder = passwordEncoder; + } + + public SignUpResponse signUpUser(SignUpRequest signUpRequest) + throws UserAlreadyExistsException, RoleNotFoundException { + if (registeredUserService.existsByEmail(signUpRequest.getEmail())) { + throw new UserAlreadyExistsException("Registration Failed: Provided email already exists. Try sign in or provide another email."); + } + if (registeredUserService.existsByUsername(signUpRequest.getUsername())) { + throw new UserAlreadyExistsException("Registration Failed: Provided username already exists. Try sign in or provide another username."); + } + + RegisteredUser registeredUser = createUser(signUpRequest); + registeredUserService.save(registeredUser); + return new SignUpResponse(registeredUser.getUsername()); + } + + private RegisteredUser createUser(SignUpRequest signUpRequest) throws RoleNotFoundException { + return RegisteredUser.builder() + .email(signUpRequest.getEmail()) + .username(signUpRequest.getUsername()) + .password(passwordEncoder.encode(signUpRequest.getPassword())) + .roles(determineRoles(signUpRequest.getRoles())) + .build(); + } + + private Set determineRoles(Set strRoles) throws RoleNotFoundException { + Set roles = new HashSet<>(); + + if (strRoles == null) { + roles.add(roleFactory.getInstance("user")); + } else { + for (String role : strRoles) { + roles.add(roleFactory.getInstance(role.toLowerCase())); + } + } + return roles; + } +} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/RegisteredUserService.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/RegisteredUserService.java new file mode 100644 index 0000000..39d37b5 --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/RegisteredUserService.java @@ -0,0 +1,27 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.service; + +import org.lbcc.bms.bms_monolith.common.entity.RegisteredUser; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.repository.RegisteredUserRepository; +import org.springframework.stereotype.Service; + +@Service +public class RegisteredUserService { + + private final RegisteredUserRepository registeredUserRepository; + + public RegisteredUserService(RegisteredUserRepository registeredUserRepository) { + this.registeredUserRepository = registeredUserRepository; + } + + public boolean existsByUsername(String username) { + return registeredUserRepository.existsByUsername(username); + } + + public boolean existsByEmail(String email) { + return registeredUserRepository.existsByEmail(email); + } + + public void save(RegisteredUser registeredUser) { + registeredUserRepository.save(registeredUser); + } +} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/RoleFactoryService.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/RoleFactoryService.java new file mode 100644 index 0000000..00eba9d --- /dev/null +++ b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/security/uesrnamepassword/service/RoleFactoryService.java @@ -0,0 +1,27 @@ +package org.lbcc.bms.bms_monolith.security.uesrnamepassword.service; + +import org.lbcc.bms.bms_monolith.common.entity.Role; +import org.lbcc.bms.bms_monolith.common.enums.RoleType; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.exeception.RoleNotFoundException; +import org.lbcc.bms.bms_monolith.security.uesrnamepassword.repository.RoleRepository; +import org.springframework.stereotype.Component; + +@Component +public class RoleFactoryService { + + private final RoleRepository roleRepository; + + public RoleFactoryService(RoleRepository roleRepository) { + this.roleRepository = roleRepository; + } + + public Role getInstance(String role) throws RoleNotFoundException { + return switch (role.toLowerCase()) { + case "admin" -> roleRepository.findByLabel(RoleType.ADMIN); + case "user" -> roleRepository.findByLabel(RoleType.USER); + case "vendor" -> roleRepository.findByLabel(RoleType.VENDOR); + case "guest" -> roleRepository.findByLabel(RoleType.GUEST); + default -> throw new RoleNotFoundException("No role found for " + role); + }; + } +} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/JwtUtils.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/JwtUtils.java deleted file mode 100644 index 9f7e970..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/JwtUtils.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.lbcc.bms.bms_monolith.userservice.common; - -import io.jsonwebtoken.*; -import io.jsonwebtoken.io.Decoders; -import io.jsonwebtoken.security.Keys; -import org.lbcc.bms.bms_monolith.userservice.service.impl.UserDetailsImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.security.core.Authentication; -import org.springframework.stereotype.Component; - -import java.security.Key; -import java.util.Date; - -@Component -public class JwtUtils { - private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class); - - @Value("${app.auth:jwt-secret}") - private String jwtSecret; - - @Value("${app.auth.jwt-expiration-ms}") - private int jwtExpirationMs; - - public String generateJwtToken(Authentication authentication) { - - UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal(); - - return Jwts.builder() - .setSubject((userPrincipal.getEmail())) - .setIssuedAt(new Date()) - .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs)) - .signWith(key(), SignatureAlgorithm.HS256) - .compact(); - } - - private Key key() { - return Keys.hmacShaKeyFor(Decoders.BASE64.decode(jwtSecret)); - } - - public String getUserNameFromJwtToken(String token) { - return Jwts.parserBuilder() - .setSigningKey(key()) - .build() - .parseClaimsJws(token) - .getBody() - .getSubject(); - } - - public boolean validateJwtToken(String authToken) { - try { - Jwts.parserBuilder().setSigningKey(key()).build().parse(authToken); - return true; - } catch (MalformedJwtException e) { - logger.error("Invalid JWT token: {}", e.getMessage()); - } catch (ExpiredJwtException e) { - logger.error("JWT token is expired: {}", e.getMessage()); - } catch (UnsupportedJwtException e) { - logger.error("JWT token is unsupported: {}", e.getMessage()); - } catch (IllegalArgumentException e) { - logger.error("JWT claims string is empty: {}", e.getMessage()); - } - - return false; - } -} - diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleFactory.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleFactory.java deleted file mode 100644 index 072430e..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/common/RoleFactory.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.lbcc.bms.bms_monolith.userservice.common; - -import org.lbcc.bms.bms_monolith.userservice.exeception.RoleNotFoundException; -import org.lbcc.bms.bms_monolith.userservice.model.Role; -import org.lbcc.bms.bms_monolith.userservice.repository.RoleRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class RoleFactory { - @Autowired - RoleRepository roleRepository; - - public Role getInstance(String role) throws RoleNotFoundException { - switch (role) { - case "admin" -> { - return roleRepository.findByLabel(RoleType.ADMIN); - } - case "user" -> { - return roleRepository.findByLabel(RoleType.USER); - } - case "vendor" -> { - return roleRepository.findByLabel(RoleType.VENDOR); - } - case "guest" -> { - return roleRepository.findByLabel(RoleType.GUEST); - } - - default -> throw new RoleNotFoundException("No role found for " + role); - } - } - -} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/AuthController.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/AuthController.java deleted file mode 100644 index e88137d..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/AuthController.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.lbcc.bms.bms_monolith.userservice.controller; - -import jakarta.validation.Valid; -import org.lbcc.bms.bms_monolith.common.response.ApiResponse; -import org.lbcc.bms.bms_monolith.userservice.common.SignUpRequestDto; -import org.lbcc.bms.bms_monolith.userservice.exeception.RoleNotFoundException; -import org.lbcc.bms.bms_monolith.userservice.exeception.UserAlreadyExistsException; -import org.lbcc.bms.bms_monolith.userservice.service.AuthService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -@RestController -@CrossOrigin("*") -@RequestMapping("/auth") -public class AuthController { - @Autowired - private AuthService authService; - - @PostMapping("/register") - public ResponseEntity registerUser(@RequestBody @Valid SignUpRequestDto signUpRequestDto) - throws UserAlreadyExistsException, RoleNotFoundException { - return authService.signUpUser(signUpRequestDto); - } - @PostMapping("/login") - public ResponseEntity signIn(@RequestBody @Valid SignUpRequestDto signUpRequestDto) - throws UserAlreadyExistsException, RoleNotFoundException { - return authService.signUpUser(signUpRequestDto); - } - -} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/UserController.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/UserController.java deleted file mode 100644 index 4aa615f..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/controller/UserController.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.lbcc.bms.bms_monolith.userservice.controller; - -import org.lbcc.bms.bms_monolith.common.response.ApiResponse; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/api/users") -public class UserController { - - @GetMapping("/") - public ResponseEntity> Test() { - return ResponseEntity.status(HttpStatus.OK).body(ApiResponse.builder().success(true).message(" jwt token test").build()); - } -} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/RoleNotFoundException.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/RoleNotFoundException.java deleted file mode 100644 index e79aa86..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/RoleNotFoundException.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.lbcc.bms.bms_monolith.userservice.exeception; - -public class RoleNotFoundException extends Exception{ - public RoleNotFoundException(String message) { - super(message); - } -} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UserAlreadyExistsException.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UserAlreadyExistsException.java deleted file mode 100644 index 5b9f596..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UserAlreadyExistsException.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.lbcc.bms.bms_monolith.userservice.exeception; - -public class UserAlreadyExistsException extends Exception{ - public UserAlreadyExistsException(String message) { - super(message); - } -} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UsernameNotFoundException.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UsernameNotFoundException.java deleted file mode 100644 index 5d57ccf..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/exeception/UsernameNotFoundException.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.lbcc.bms.bms_monolith.userservice.exeception; - -public class UsernameNotFoundException extends RuntimeException { - public UsernameNotFoundException(String message) { - super(message); - } -} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/UserRepository.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/UserRepository.java deleted file mode 100644 index 40033b8..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/repository/UserRepository.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.lbcc.bms.bms_monolith.userservice.repository; - -import org.lbcc.bms.bms_monolith.userservice.model.User; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.Optional; - -@Repository -public interface UserRepository extends JpaRepository { - Optional findByEmail(String email); - - Boolean existsByUsername(String username); - - Boolean existsByEmail(String email); -} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/AuthService.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/AuthService.java deleted file mode 100644 index 3d4322a..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/AuthService.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.lbcc.bms.bms_monolith.userservice.service; - -import org.lbcc.bms.bms_monolith.common.response.ApiResponse; -import org.lbcc.bms.bms_monolith.userservice.common.SignUpRequestDto; -import org.lbcc.bms.bms_monolith.userservice.exeception.RoleNotFoundException; -import org.lbcc.bms.bms_monolith.userservice.exeception.UserAlreadyExistsException; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; - - -@Service -public interface AuthService { - ResponseEntity signUpUser(SignUpRequestDto signUpRequestDto) throws UserAlreadyExistsException, RoleNotFoundException, org.lbcc.bms.bms_monolith.userservice.exeception.RoleNotFoundException; -} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/UserService.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/UserService.java deleted file mode 100644 index 3aec886..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/UserService.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.lbcc.bms.bms_monolith.userservice.service; - -import org.lbcc.bms.bms_monolith.userservice.model.User; -import org.springframework.stereotype.Service; - -@Service -public interface UserService { - boolean existsByUsername(String username); - boolean existsByEmail(String email); - void save(User user); -} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java deleted file mode 100644 index 747f69e..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/AuthServiceImpl.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.lbcc.bms.bms_monolith.userservice.service.impl; - -import org.lbcc.bms.bms_monolith.common.response.ApiResponse; -import org.lbcc.bms.bms_monolith.userservice.common.RoleFactory; -import org.lbcc.bms.bms_monolith.userservice.common.SignUpRequestDto; -import org.lbcc.bms.bms_monolith.userservice.exeception.RoleNotFoundException; -import org.lbcc.bms.bms_monolith.userservice.exeception.UserAlreadyExistsException; -import org.lbcc.bms.bms_monolith.userservice.model.Role; -import org.lbcc.bms.bms_monolith.userservice.model.User; -import org.lbcc.bms.bms_monolith.userservice.service.AuthService; -import org.lbcc.bms.bms_monolith.userservice.service.UserService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Component; - -import java.util.HashSet; -import java.util.Set; - -@Component -public class AuthServiceImpl implements AuthService { - - private final UserService userService; - - private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); - - @Autowired - private RoleFactory roleFactory; - - public AuthServiceImpl(UserService userService) { - this.userService = userService; - } - - @Override - public ResponseEntity signUpUser(SignUpRequestDto signUpRequestDto) - throws UserAlreadyExistsException, RoleNotFoundException { - if (userService.existsByEmail(signUpRequestDto.getEmail())) { - throw new UserAlreadyExistsException("Registration Failed: Provided email already exists. Try sign in or provide another email."); - } - if (userService.existsByUsername(signUpRequestDto.getUserName())) { - throw new UserAlreadyExistsException("Registration Failed: Provided username already exists. Try sign in or provide another username."); - } - - User user = createUser(signUpRequestDto); - userService.save(user); - return ResponseEntity.status(HttpStatus.CREATED).body( - ApiResponse.builder() - .message("User account has been successfully created!") - .build() - ); - } - - private User createUser(SignUpRequestDto signUpRequestDto) throws RoleNotFoundException { - return User.builder() - .email(signUpRequestDto.getEmail()) - .username(signUpRequestDto.getUserName()) - .password(signUpRequestDto.getPassword()) - .roles(determineRoles(signUpRequestDto.getRoles())) - .build(); - } - - private Set determineRoles(Set strRoles) throws RoleNotFoundException { - Set roles = new HashSet<>(); - - if (strRoles == null) { - roles.add(roleFactory.getInstance("user")); - } else { - for (String role : strRoles) { - roles.add(roleFactory.getInstance(role.toLowerCase())); - } - } - return roles; - } -} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsImpl.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsImpl.java deleted file mode 100644 index 7a07f3f..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsImpl.java +++ /dev/null @@ -1,67 +0,0 @@ - -package org.lbcc.bms.bms_monolith.userservice.service.impl; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import lombok.AllArgsConstructor; -import lombok.Data; -import org.lbcc.bms.bms_monolith.userservice.model.User; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; - -import java.io.Serial; -import java.util.Collection; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -@AllArgsConstructor -@Data -public class UserDetailsImpl implements UserDetails { - @Serial private static final long serialVersionUID = 1L; - private String id; - private String username; - private String email; - @JsonIgnore private String password; - private Collection authorities; - private boolean enabled; - - public static UserDetailsImpl build(User user) { - List authorities = - user.getRoles().stream() - .map(role -> new SimpleGrantedAuthority(role.getLabel().name())) - .collect(Collectors.toList()); - - return new UserDetailsImpl( - user.getId(), - user.getUsername(), - user.getEmail(), - user.getPassword(), - authorities, - user.getIsActive()); - } - - @Override - public boolean isAccountNonExpired() { - return true; - } - - @Override - public boolean isAccountNonLocked() { - return true; - } - - @Override - public boolean isCredentialsNonExpired() { - return true; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - UserDetailsImpl user = (UserDetailsImpl) o; - return Objects.equals(id, user.id); - } -} - diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsServiceImpl.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsServiceImpl.java deleted file mode 100644 index 209cb3f..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserDetailsServiceImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.lbcc.bms.bms_monolith.userservice.service.impl; - -import jakarta.transaction.Transactional; -import org.lbcc.bms.bms_monolith.userservice.model.User; -import org.lbcc.bms.bms_monolith.userservice.repository.UserRepository; -import org.springframework.beans.factory.annotation.Autowired; -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; - -@Service -public class UserDetailsServiceImpl implements UserDetailsService { - @Autowired UserRepository userRepository; - - @Override - @Transactional - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - User user = - userRepository - .findByEmail(username) - .orElseThrow( - () -> new UsernameNotFoundException("User Not Found with username: " + username)); - - return UserDetailsImpl.build(user); - } -} diff --git a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserServiceImpl.java b/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserServiceImpl.java deleted file mode 100644 index 4946fba..0000000 --- a/book-my-show/backend/java/bms-monolith/src/main/java/org/lbcc/bms/bms_monolith/userservice/service/impl/UserServiceImpl.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.lbcc.bms.bms_monolith.userservice.service.impl; - -import org.lbcc.bms.bms_monolith.userservice.model.User; -import org.lbcc.bms.bms_monolith.userservice.repository.UserRepository; -import org.lbcc.bms.bms_monolith.userservice.service.UserService; -import org.springframework.beans.factory.annotation.Autowired; - -import org.springframework.stereotype.Service; - -@Service -public class UserServiceImpl implements UserService { - - private final UserRepository userRepository; - - @Autowired - public UserServiceImpl(UserRepository userRepository) { - this.userRepository = userRepository; - } - - @Override - public boolean existsByUsername(String username) { - return userRepository.existsByUsername(username); - } - - @Override - public boolean existsByEmail(String email) { - return userRepository.existsByEmail(email); - } - - @Override - public void save(User user) { - userRepository.save(user); - } -} diff --git a/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml b/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml index 8f56af0..ea81d5d 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml +++ b/book-my-show/backend/java/bms-monolith/src/main/resources/application.yaml @@ -21,5 +21,6 @@ server: context-path: /api/v1 app: auth: - jwt-secret: ${JWT_SECRET:some_secret} - jwt-expiration-ms: ${JWT_EXPIRATION_MS:50000} \ No newline at end of file + jwt: + secret-key: ${JWT_SECRET_KEY:ZmxhbWVyb2xsc3RvcHBlZGNyZWFtY29sbGVjdGZhbGxzb2xkaWVydG9uZWdpdmVua24=} + expiration-in-ms: ${JWT_EXPIRATION_IN_MS:50000} \ No newline at end of file diff --git a/book-my-show/backend/java/bms-monolith/src/main/resources/db/changelog/v1.0/add-auth-tables.xml b/book-my-show/backend/java/bms-monolith/src/main/resources/db/changelog/v1.0/add-auth-tables.xml index 9d0af54..c8be503 100644 --- a/book-my-show/backend/java/bms-monolith/src/main/resources/db/changelog/v1.0/add-auth-tables.xml +++ b/book-my-show/backend/java/bms-monolith/src/main/resources/db/changelog/v1.0/add-auth-tables.xml @@ -20,7 +20,7 @@ - + @@ -42,7 +42,7 @@ - +