diff --git a/back-end/.gitignore b/back-end/.gitignore new file mode 100644 index 00000000..549e00a2 --- /dev/null +++ b/back-end/.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/back-end/.mvn/wrapper/maven-wrapper.properties b/back-end/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..8f96f52c --- /dev/null +++ b/back-end/.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 +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip diff --git a/back-end/mvnw b/back-end/mvnw new file mode 100644 index 00000000..d7c358e5 --- /dev/null +++ b/back-end/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 +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,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/back-end/mvnw.cmd b/back-end/mvnw.cmd new file mode 100644 index 00000000..6f779cff --- /dev/null +++ b/back-end/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 https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,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/back-end/pom.xml b/back-end/pom.xml new file mode 100644 index 00000000..d61c79d0 --- /dev/null +++ b/back-end/pom.xml @@ -0,0 +1,82 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.3.0 + + + com.example + demo + 0.0.1-SNAPSHOT + demo + Demo project for Spring Boot + + 21 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-mail + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + com.mysql + mysql-connector-j + runtime + + + org.projectlombok + lombok + true + + + com.sun.mail + jakarta.mail + 2.0.1 + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/back-end/src/main/java/com/example/demo/DemoApplication.java b/back-end/src/main/java/com/example/demo/DemoApplication.java new file mode 100644 index 00000000..64b538a1 --- /dev/null +++ b/back-end/src/main/java/com/example/demo/DemoApplication.java @@ -0,0 +1,13 @@ +package com.example.demo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DemoApplication { + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } + +} diff --git a/back-end/src/main/java/com/example/demo/appuser/AppUser.java b/back-end/src/main/java/com/example/demo/appuser/AppUser.java new file mode 100644 index 00000000..5dbbd72f --- /dev/null +++ b/back-end/src/main/java/com/example/demo/appuser/AppUser.java @@ -0,0 +1,91 @@ +package com.example.demo.appuser; + +import jakarta.persistence.*; +import lombok.*; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +@Getter +@Setter +@EqualsAndHashCode +@NoArgsConstructor +@Entity + +public class AppUser implements UserDetails { + + @SequenceGenerator( + name = "member_sequence", + sequenceName = "member_sequence", + allocationSize = 1 + ) + @Id + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "member_sequence" + ) + private Long id; + @Getter + private String firstName; + @Getter + private String lastName; + private String email; + private String password; + @Enumerated(EnumType.STRING) + private AppUserRole appUserRole; + private Boolean locked = false; + private Boolean enabled = false; + + public AppUser( String firstName, + String lastName, + String email, + String password, + AppUserRole appUserRole) { + this.firstName = firstName; + this.lastName = lastName; + this.email = email; + this.password = password; + this.appUserRole = appUserRole; + } + + @Override + public Collection getAuthorities() { + SimpleGrantedAuthority authority = new SimpleGrantedAuthority(appUserRole.name()); + return Collections.singletonList(authority); + } + + @Override + public String getPassword() { + return password; + } + + @Override + public String getUsername() { + return email; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return !locked; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return enabled; + } + +} diff --git a/back-end/src/main/java/com/example/demo/appuser/AppUserRepository.java b/back-end/src/main/java/com/example/demo/appuser/AppUserRepository.java new file mode 100644 index 00000000..8e3c4ce6 --- /dev/null +++ b/back-end/src/main/java/com/example/demo/appuser/AppUserRepository.java @@ -0,0 +1,21 @@ +package com.example.demo.appuser; + + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.stereotype.Repository; +import java.util.Optional; + +@Repository +@Transactional(readOnly = true) +public interface AppUserRepository extends JpaRepository { + Optional findByEmail(String email); + + @Transactional + @Modifying + @Query("UPDATE AppUser a " + + "SET a.enabled = TRUE WHERE a.email = ?1") + int enableAppUser(String email); +} diff --git a/back-end/src/main/java/com/example/demo/appuser/AppUserRole.java b/back-end/src/main/java/com/example/demo/appuser/AppUserRole.java new file mode 100644 index 00000000..fdd4d83f --- /dev/null +++ b/back-end/src/main/java/com/example/demo/appuser/AppUserRole.java @@ -0,0 +1,5 @@ +package com.example.demo.appuser; + +public enum AppUserRole { + USER, ADMIN; +} diff --git a/back-end/src/main/java/com/example/demo/appuser/AppUserService.java b/back-end/src/main/java/com/example/demo/appuser/AppUserService.java new file mode 100644 index 00000000..57decc35 --- /dev/null +++ b/back-end/src/main/java/com/example/demo/appuser/AppUserService.java @@ -0,0 +1,70 @@ +package com.example.demo.appuser; + +import com.example.demo.registration.token.ConfirmationToken; +import com.example.demo.registration.token.ConfirmationTokenService; +import lombok.AllArgsConstructor; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.UUID; +import java.util.Optional; + +// Interface specifically for spring security +@Service +@AllArgsConstructor +public class AppUserService implements UserDetailsService { + + private final static String USER_NOT_FOUND_MSG = "user with email %s not found"; + + private final AppUserRepository appUserRepository; + private final BCryptPasswordEncoder bCryptPasswordEncoder; + private final ConfirmationTokenService confirmationTokenService; + + + @Override + public UserDetails loadUserByUsername(String email) + throws UsernameNotFoundException { + return appUserRepository.findByEmail(email) + .orElseThrow(() -> + new UsernameNotFoundException( + String.format(USER_NOT_FOUND_MSG, email))); + } + + public Optional getUserByEmail(String email) { + return appUserRepository.findByEmail(email); + } + + public String signUpUser(AppUser appUser) { + boolean userExists = appUserRepository.findByEmail(appUser.getEmail()) + .isPresent(); + + if (userExists) { + throw new IllegalStateException("Email already exists"); + } + + String encodePassword = bCryptPasswordEncoder.encode(appUser.getPassword()); + + appUser.setPassword(encodePassword); + appUserRepository.save(appUser); + + String token = UUID.randomUUID().toString(); + ConfirmationToken confirmationToken = new ConfirmationToken( + token, + LocalDateTime.now(), + LocalDateTime.now().plusMinutes(15), + appUser + ); + + confirmationTokenService.saveConfirmationToken(confirmationToken); + // TODO: SEND EMAIL + return token; + } + + public int enableAppUser(String email) { + return appUserRepository.enableAppUser(email); + } +} diff --git a/back-end/src/main/java/com/example/demo/config/WebConfig.java b/back-end/src/main/java/com/example/demo/config/WebConfig.java new file mode 100644 index 00000000..ac9d9828 --- /dev/null +++ b/back-end/src/main/java/com/example/demo/config/WebConfig.java @@ -0,0 +1,19 @@ +package com.example.demo.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedOrigins("http://localhost:5173") + .allowCredentials(true) + .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") + .allowedHeaders("*"); + } + +} diff --git a/back-end/src/main/java/com/example/demo/email/EmailSender.java b/back-end/src/main/java/com/example/demo/email/EmailSender.java new file mode 100644 index 00000000..3b2c58b1 --- /dev/null +++ b/back-end/src/main/java/com/example/demo/email/EmailSender.java @@ -0,0 +1,5 @@ +package com.example.demo.email; + +public interface EmailSender { + void send(String to, String email); +} diff --git a/back-end/src/main/java/com/example/demo/email/EmailService.java b/back-end/src/main/java/com/example/demo/email/EmailService.java new file mode 100644 index 00000000..3eff24c4 --- /dev/null +++ b/back-end/src/main/java/com/example/demo/email/EmailService.java @@ -0,0 +1,38 @@ +package com.example.demo.email; + +import jakarta.mail.MessagingException; +import jakarta.mail.internet.MimeMessage; +import lombok.AllArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + + +@Service +@AllArgsConstructor +public class EmailService implements EmailSender{ + + private final static Logger LOGGER = LoggerFactory + .getLogger(EmailService.class); + + private final JavaMailSender mailSender; + + @Override + @Async + public void send(String to, String email) { + try { + MimeMessage mimeMessage = mailSender.createMimeMessage(); + MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "utf-8"); + helper.setText(email, true); + helper.setTo(to); + helper.setSubject("Confirm your email"); + helper.setFrom("cycleuop@gmail.com"); + } catch (MessagingException e) { + LOGGER.error("failed to send email", e); + throw new IllegalStateException("failed to send email"); + } + } +} diff --git a/back-end/src/main/java/com/example/demo/registration/EmailValidator.java b/back-end/src/main/java/com/example/demo/registration/EmailValidator.java new file mode 100644 index 00000000..085cbe0b --- /dev/null +++ b/back-end/src/main/java/com/example/demo/registration/EmailValidator.java @@ -0,0 +1,14 @@ +package com.example.demo.registration; + +import org.springframework.stereotype.Service; + +import java.util.function.Predicate; + +@Service +public class EmailValidator implements Predicate { + @Override + public boolean test(String s) { +// TODO: Regex to validate email + return true; + } +} diff --git a/back-end/src/main/java/com/example/demo/registration/LoginDTO.java b/back-end/src/main/java/com/example/demo/registration/LoginDTO.java new file mode 100644 index 00000000..a6ac9309 --- /dev/null +++ b/back-end/src/main/java/com/example/demo/registration/LoginDTO.java @@ -0,0 +1,37 @@ +package com.example.demo.registration; + +import lombok.*; + +@Data +// Login Data Transfer Object +public class LoginDTO { + private String email; + private String password; + + public LoginDTO() { + } + + public LoginDTO(String email, String password) { + this.email = email; + this.password = password; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getEmail() { + return email; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getPassword() { + return password; + } + + +} + diff --git a/back-end/src/main/java/com/example/demo/registration/LoginResponse.java b/back-end/src/main/java/com/example/demo/registration/LoginResponse.java new file mode 100644 index 00000000..f471a6e4 --- /dev/null +++ b/back-end/src/main/java/com/example/demo/registration/LoginResponse.java @@ -0,0 +1,15 @@ +package com.example.demo.registration; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class LoginResponse { + private String token; + private String message; + +} diff --git a/back-end/src/main/java/com/example/demo/registration/RegistrationController.java b/back-end/src/main/java/com/example/demo/registration/RegistrationController.java new file mode 100644 index 00000000..8a813862 --- /dev/null +++ b/back-end/src/main/java/com/example/demo/registration/RegistrationController.java @@ -0,0 +1,29 @@ +package com.example.demo.registration; + +import lombok.AllArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping(path = "api/v1/registration") +@AllArgsConstructor +public class RegistrationController { + + private final RegistrationService registrationService; + + @PostMapping + public String register(@RequestBody RegistrationRequest request) { + return registrationService.register(request); + } + + @GetMapping("confirm") + public String confirm(@RequestParam("token") String token) { + return registrationService.confirmToken(token); + } + + @PostMapping("/login") + public ResponseEntity loginUser(@RequestBody LoginDTO loginDTO) { + LoginResponse loginResponse = registrationService.loginUser(loginDTO); + return ResponseEntity.ok(loginResponse); + } +} diff --git a/back-end/src/main/java/com/example/demo/registration/RegistrationRequest.java b/back-end/src/main/java/com/example/demo/registration/RegistrationRequest.java new file mode 100644 index 00000000..b56561aa --- /dev/null +++ b/back-end/src/main/java/com/example/demo/registration/RegistrationRequest.java @@ -0,0 +1,18 @@ +package com.example.demo.registration; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.ToString; + +@Getter +@AllArgsConstructor +@EqualsAndHashCode +@ToString +public class RegistrationRequest { + private final String firstName; + private final String lastName; + private final String email; + private final String password; + +} diff --git a/back-end/src/main/java/com/example/demo/registration/RegistrationService.java b/back-end/src/main/java/com/example/demo/registration/RegistrationService.java new file mode 100644 index 00000000..7b955223 --- /dev/null +++ b/back-end/src/main/java/com/example/demo/registration/RegistrationService.java @@ -0,0 +1,85 @@ +package com.example.demo.registration; + +import com.example.demo.appuser.AppUser; +import com.example.demo.appuser.AppUserRole; +import com.example.demo.appuser.AppUserService; +import com.example.demo.email.EmailSender; +import com.example.demo.registration.token.ConfirmationToken; +import com.example.demo.registration.token.ConfirmationTokenService; +import lombok.AllArgsConstructor; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.Optional; + +@Service +@AllArgsConstructor +public class RegistrationService { + + private final AppUserService appUserService; + private final EmailValidator emailValidator; + private final ConfirmationTokenService confirmationTokenService; + private final EmailSender emailSender; + + public String register(RegistrationRequest request) { + boolean isValidEmail = emailValidator.test(request.getEmail()); + + if (!isValidEmail) { + throw new IllegalStateException("Email is not valid"); + } + + String token = appUserService.signUpUser( + new AppUser(request.getFirstName(), + request.getLastName(), + request.getEmail(), + request.getPassword(), + AppUserRole.USER) + ); + String link = "localhost:8080/api/v1/registration/confirm?token=" + token; +// emailSender.send(request.getEmail(), +// buildEmail(request.getFirstName(), link)); + return token; + } + + + @Transactional + public String confirmToken(String token) { + ConfirmationToken confirmationToken = confirmationTokenService + .getToken(token) + .orElseThrow(() -> new IllegalStateException("Token not found")); + + if (confirmationToken.getConfirmedAt() != null) { + throw new IllegalStateException("Email already confirmed"); + } + + LocalDateTime expiredAt = confirmationToken.getExpiresAt(); + + if (expiredAt.isBefore(LocalDateTime.now())) { + throw new IllegalStateException("Token is expired"); + } + confirmationTokenService.setConfirmedAt(token); + appUserService.enableAppUser( + confirmationToken.getAppUser().getEmail() + ); + return "Confirmed!"; + } + + public LoginResponse loginUser(LoginDTO loginDTO) { + Optional optionalAppUser = appUserService.getUserByEmail(loginDTO.getEmail()); + + if (optionalAppUser.isEmpty()) { + return new LoginResponse(null, "User not found"); + } + + AppUser appUser = optionalAppUser.get(); + + if (appUser.getPassword().equals(loginDTO.getPassword())) { + return new LoginResponse(null, "Incorrect Email and Password not match"); + } else { + return new LoginResponse("dummy-token", "Login Success"); + } + } +} + diff --git a/back-end/src/main/java/com/example/demo/registration/token/ConfirmationToken.java b/back-end/src/main/java/com/example/demo/registration/token/ConfirmationToken.java new file mode 100644 index 00000000..2e28269e --- /dev/null +++ b/back-end/src/main/java/com/example/demo/registration/token/ConfirmationToken.java @@ -0,0 +1,55 @@ +package com.example.demo.registration.token; + +import com.example.demo.appuser.AppUser; +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@NoArgsConstructor +@Entity +public class ConfirmationToken { + + @SequenceGenerator( + name = "confirmation_token_sequence", + sequenceName = "confirmation_token_sequence", + allocationSize = 1 + ) + @Id + @GeneratedValue( + strategy = GenerationType.SEQUENCE, + generator = "confirmation_token_sequence" + ) + + private Long id; + @Column(nullable = false) + private String token; + + @Column(nullable = false) + private LocalDateTime createdAt; + + @Column(nullable = false) + private LocalDateTime expiresAt; + + private LocalDateTime confirmedAt; + + @ManyToOne //Because application user can have many application tokens + @JoinColumn(nullable = false, + name = "app_user_id" + ) + private AppUser appUser; + + public ConfirmationToken(String token, + LocalDateTime createdAt, + LocalDateTime expiredAt, + AppUser appUser) { + this.token = token; + this.createdAt = createdAt; + this.expiresAt = expiredAt; + this.appUser = appUser; + } +} diff --git a/back-end/src/main/java/com/example/demo/registration/token/ConfirmationTokenRepository.java b/back-end/src/main/java/com/example/demo/registration/token/ConfirmationTokenRepository.java new file mode 100644 index 00000000..a139cc8e --- /dev/null +++ b/back-end/src/main/java/com/example/demo/registration/token/ConfirmationTokenRepository.java @@ -0,0 +1,25 @@ +package com.example.demo.registration.token; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.Optional; + +@Repository +@Transactional(readOnly = true) +public interface ConfirmationTokenRepository extends + JpaRepository { + + Optional findByToken(String token); + + @Transactional + @Modifying + @Query("update ConfirmationToken c " + + "SET c.confirmedAt = ?2 " + + "WHERE c.token = ?1") + int updateConfirmedAt(String token, LocalDateTime confirmedAt); +} diff --git a/back-end/src/main/java/com/example/demo/registration/token/ConfirmationTokenService.java b/back-end/src/main/java/com/example/demo/registration/token/ConfirmationTokenService.java new file mode 100644 index 00000000..4ff2fc19 --- /dev/null +++ b/back-end/src/main/java/com/example/demo/registration/token/ConfirmationTokenService.java @@ -0,0 +1,26 @@ +package com.example.demo.registration.token; + +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.Optional; + +@Service +@AllArgsConstructor +public class ConfirmationTokenService { + private final ConfirmationTokenRepository confirmationTokenRepository; + + public void saveConfirmationToken(ConfirmationToken token) { + confirmationTokenRepository.save(token); + } + + public Optional getToken(String token) { + return confirmationTokenRepository.findByToken(token); + } + + public int setConfirmedAt(String token) { + return confirmationTokenRepository.updateConfirmedAt( + token, LocalDateTime.now()); + } +} diff --git a/back-end/src/main/java/com/example/demo/security/PasswordEncoder.java b/back-end/src/main/java/com/example/demo/security/PasswordEncoder.java new file mode 100644 index 00000000..b4f42918 --- /dev/null +++ b/back-end/src/main/java/com/example/demo/security/PasswordEncoder.java @@ -0,0 +1,14 @@ +package com.example.demo.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +@Configuration +public class PasswordEncoder { + + @Bean + public BCryptPasswordEncoder bCryptPasswordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/back-end/src/main/java/com/example/demo/security/config/WebSecurityConfig.java b/back-end/src/main/java/com/example/demo/security/config/WebSecurityConfig.java new file mode 100644 index 00000000..668a9240 --- /dev/null +++ b/back-end/src/main/java/com/example/demo/security/config/WebSecurityConfig.java @@ -0,0 +1,51 @@ +package com.example.demo.security.config; + +import com.example.demo.appuser.AppUserService; +import lombok.AllArgsConstructor; +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.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; + +import static org.springframework.security.config.Customizer.withDefaults; + +@Configuration +@AllArgsConstructor +@EnableWebSecurity +public class WebSecurityConfig { + + private final AppUserService appUserService; + private final BCryptPasswordEncoder bCryptPasswordEncoder; + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http + .csrf(AbstractHttpConfigurer::disable) + .authorizeHttpRequests(authz -> authz + .requestMatchers("/api/v*/registration/**") + .permitAll() + .anyRequest().authenticated() + ) + .formLogin(withDefaults()); + return http.build(); + } + + @Bean + public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { + return authenticationConfiguration.getAuthenticationManager(); + } + + @Bean + public DaoAuthenticationProvider daoAuthenticationProvider() { + DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); + provider.setPasswordEncoder(bCryptPasswordEncoder); + provider.setUserDetailsService(appUserService); + return provider; + } +} diff --git a/back-end/src/main/resources/application.yml b/back-end/src/main/resources/application.yml new file mode 100644 index 00000000..cc76e69f --- /dev/null +++ b/back-end/src/main/resources/application.yml @@ -0,0 +1,38 @@ +#configurtion +server: + error: + include-message: always + include-binding-errors: always + +spring: + datasource: + url: jdbc:mysql://localhost:3306/cycle + password: + username: root + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + hibernate: + ddl-auto: create-drop + properties: + hibernate: + dialect: org.hibernate.dialect.MySQLDialect + format_sql: true + show-sql: true + + mail: + host: localhost + port: 1025 + username: hello + password: hello + + properties: + mail: + smtp: + ssl: + trust: "*" + auth: true + starttls: + enable: true + connection timeout: 5000 + timeout: 3000 + write timeout: 5000 diff --git a/back-end/src/test/java/com/example/demo/DemoApplicationTests.java b/back-end/src/test/java/com/example/demo/DemoApplicationTests.java new file mode 100644 index 00000000..2778a6a7 --- /dev/null +++ b/back-end/src/test/java/com/example/demo/DemoApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.demo; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class DemoApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/front-end/package-lock.json b/front-end/package-lock.json index 30254fd2..20bc3c39 100644 --- a/front-end/package-lock.json +++ b/front-end/package-lock.json @@ -13,6 +13,7 @@ "@fortawesome/free-regular-svg-icons": "^6.5.2", "@fortawesome/free-solid-svg-icons": "^6.5.2", "@fortawesome/react-fontawesome": "^0.2.2", + "axios": "^1.7.2", "react": "^18.2.0", "react-dom": "^18.2.0", "react-leaflet": "^4.2.1", @@ -1535,6 +1536,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, "node_modules/available-typed-arrays": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", @@ -1550,6 +1556,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/axios": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.2.tgz", + "integrity": "sha512-2A8QhOMrbomlDuiLeK9XibIBzuHeRcqqNOHp0Cyp5EoJ1IFDh+XZH3A6BkXtv0K4gFGCI0Y4BM7B1wOEi0Rmgw==", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -1675,6 +1691,17 @@ "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", "dev": true }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/commander": { "version": "2.20.3", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", @@ -1905,6 +1932,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/doctrine": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", @@ -2516,6 +2551,25 @@ "integrity": "sha512-X8cqMLLie7KsNUDSdzeN8FYK9rEt4Dt67OsG/DNGnYTSDBG4uFAJFBnUeiV+zCVAvwFy56IjM9sH51jVaEhNxw==", "dev": true }, + "node_modules/follow-redirects": { + "version": "1.15.6", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.6.tgz", + "integrity": "sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, "node_modules/for-each": { "version": "0.3.3", "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", @@ -2525,6 +2579,19 @@ "is-callable": "^1.1.3" } }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -3358,6 +3425,25 @@ "yallist": "^3.0.2" } }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", @@ -3679,6 +3765,11 @@ "react-is": "^16.13.1" } }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", diff --git a/front-end/package.json b/front-end/package.json index 332dcc91..c82d999a 100644 --- a/front-end/package.json +++ b/front-end/package.json @@ -15,6 +15,7 @@ "@fortawesome/free-regular-svg-icons": "^6.5.2", "@fortawesome/free-solid-svg-icons": "^6.5.2", "@fortawesome/react-fontawesome": "^0.2.2", + "axios": "^1.7.2", "react": "^18.2.0", "react-dom": "^18.2.0", "react-leaflet": "^4.2.1", diff --git a/front-end/src/Pages/Login.jsx b/front-end/src/Pages/Login.jsx index 5f626b07..910613d3 100644 --- a/front-end/src/Pages/Login.jsx +++ b/front-end/src/Pages/Login.jsx @@ -1,9 +1,88 @@ +import React, { useState } from "react"; +import { useNavigate } from 'react-router-dom'; +import axios from "axios"; +import style from './Login.module.css'; +import cylcleLogo from '../assets/CYCLE-logo.png'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { faEye, faEyeSlash } from '@fortawesome/free-solid-svg-icons'; // Import specific icons + function Login() { - return( - <> -

Login

- + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [showPassword, setShowPassword] = useState(false); + const navigate = useNavigate(); + + const togglePasswordVisibility = () => { + setShowPassword(!showPassword); + }; + + async function login(event) { + event.preventDefault(); + try { + await axios.post("http://localhost:8080/api/v1/registration/login", { + email: email, + password: password, + }).then((res) => { + console.log(res.data); + + if (res.data.message === "Email not exits") { + alert("Email not exits"); + } else if (res.data.message === "Login Success") { + navigate('/'); + } else { + alert("Login Failed! Invalid credentials!"); + } + }, fail => { + console.error(fail); // Error! + }); + } catch (err) { + alert(err); + } + } + + return ( +
+
+ Cycle Logo +
+
+
+
+ + setEmail(event.target.value)} + /> +
+ +
+ +
+ setPassword(event.target.value)} + /> +
+ + + +
+
+
+ + +
+
+
+
+
); - } - - export default Login; \ No newline at end of file +} + +export default Login; diff --git a/front-end/src/Pages/Login.module.css b/front-end/src/Pages/Login.module.css new file mode 100644 index 00000000..64f19139 --- /dev/null +++ b/front-end/src/Pages/Login.module.css @@ -0,0 +1,86 @@ +.LoginCard { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 50px 50px; + width: 300px; + height: 280px; + margin: auto; + border: 1px solid hsl(0, 0%, 80%); + margin-top: 20px; + margin-bottom: 40px; + border-radius: 10px; + box-shadow: #00448d; +} + +.LoginCard input { + width: 290px; + height: 45px; + padding: 10px; + margin-bottom: 20px; + background-color: #e3f0f6; + color: black; + border: 1px solid #dddddd; + border-radius: 4px; + box-sizing: border-box; +} + +.LoginCard button { + padding: 2px 4px; + display: flex; + align-items: center; + justify-content: center; + margin: auto; + margin-top: 10px; + margin-bottom: 20px; + background-color: #00448d; + color: #ffffff; + border: none; + border-radius: 4px; + cursor: pointer; + transition: background-color 0.3s ease; + width: 120px; + height: 42px; + font-weight: 600; + text-decoration: none; +} + +.LoginCard button:hover { + background-color: #0056b3; + color: #ffffff; +} + +.CycleLogo { + width: 250px; + margin-bottom: 0; + margin-top: 0; +} + +.input-group { + position: relative; + display: flex; + align-items: center; +} + + +.input-group-append { + position: absolute; + right: 10px; + height: 100%; + display: flex; + margin-bottom: 20px; + align-items: center; + justify-content: center; + padding: 10px 10px; +} + +.input-group-text { + background: transparent; + border: none; + cursor: pointer; +} + +.input-group-text .svg-inline--fa { + margin: 0; +} \ No newline at end of file diff --git a/front-end/vite.config.js b/front-end/vite.config.js index 5a33944a..ac1d8ec0 100644 --- a/front-end/vite.config.js +++ b/front-end/vite.config.js @@ -1,7 +1,16 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' -// https://vitejs.dev/config/ + export default defineConfig({ plugins: [react()], -}) + server: { + proxy: { + '/api': { + target: 'http://localhost:8080/error?continue', + changeOrigin: true, + secure: false, + }, + }, + }, +});