diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..30cf57e --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,10 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Ignored default folder with query files +/queries/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..89ee753 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..f41b834 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/TaskManager-Project/.gitattributes b/TaskManager-Project/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/TaskManager-Project/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/TaskManager-Project/.gitignore b/TaskManager-Project/.gitignore new file mode 100644 index 0000000..667aaef --- /dev/null +++ b/TaskManager-Project/.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/TaskManager-Project/.mvn/wrapper/maven-wrapper.properties b/TaskManager-Project/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..8dea6c2 --- /dev/null +++ b/TaskManager-Project/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.12/apache-maven-3.9.12-bin.zip diff --git a/TaskManager-Project/ReadMe.md b/TaskManager-Project/ReadMe.md new file mode 100644 index 0000000..6af0261 --- /dev/null +++ b/TaskManager-Project/ReadMe.md @@ -0,0 +1,292 @@ +# TaskManagerAPI-Project + +A Spring Boot task manager application with user registration, HTTP Basic authentication, PostgreSQL persistence, REST APIs, and a simple browser-based frontend for managing tasks. + +This project is designed for Spring Boot beginners who want to learn by building a real, practical application. It introduces common backend concepts step by step, including REST APIs, authentication, database persistence, service layers, repositories, and a simple frontend connection. The goal is to help new learners understand how different parts of a Spring Boot project work together in a friendly and hands-on way. + +## Features + +- User registration with unique usernames +- Password encryption using BCrypt +- Stateless HTTP Basic authentication +- Create, read, update, and delete tasks +- Assign tasks to registered users +- Filter task list by username +- PostgreSQL database integration +- Static frontend pages for login, registration, and task management +- Client-side validation for task forms and credentials + +## Tech Stack + +- Java 21 +- Spring Boot 4.0.3 +- Spring Web MVC +- Spring Security +- Spring Data JPA +- PostgreSQL +- Lombok +- Maven +- HTML, CSS, JavaScript + +## Project Structure + +```text +TaskManager-Project-master/ +├── pom.xml +├── mvnw +├── mvnw.cmd +├── src/ +│ ├── main/ +│ │ ├── java/com/TaskManagerAPIProject/TaskManagerAPI_Project/ +│ │ │ ├── TaskManagerApiProjectApplication.java +│ │ │ ├── PasswordDecryptAndEncrypt.java +│ │ │ ├── configration/ +│ │ │ │ └── config.java +│ │ │ ├── controller/ +│ │ │ │ ├── taskController.java +│ │ │ │ └── userController.java +│ │ │ ├── model/ +│ │ │ │ ├── Task.java +│ │ │ │ ├── user.java +│ │ │ │ ├── UserPrinciple.java +│ │ │ │ └── dto/ +│ │ │ ├── Repository/ +│ │ │ │ ├── taskRepo.java +│ │ │ │ └── UserRepo.java +│ │ │ └── service/ +│ │ │ ├── taskService.java +│ │ │ ├── userService.java +│ │ │ ├── userDetailService.java +│ │ │ └── DtoService.java +│ │ └── resources/ +│ │ ├── application.properties +│ │ └── static/ +│ │ ├── index.html +│ │ ├── task-ui.html +│ │ ├── styles.css +│ │ ├── login.js +│ │ └── app.js +│ └── test/ +│ └── java/ +└── README.md +Requirements +Before running the project, install: + +Java 21 +PostgreSQL +Maven, or use the included Maven wrapper +Database Configuration +The application reads PostgreSQL settings from environment variables. + +Required variables: + +DB_URL=jdbc:postgresql://localhost:5432/taskmanager +DB_USERNAME=your_postgres_username +DB_PASSWORD=your_postgres_password +Example database creation: + +CREATE DATABASE taskmanager; +The project uses: + +spring.jpa.hibernate.ddl-auto=update +This allows Hibernate to create or update database tables automatically. + +Running the Application +On Windows: + +mvnw.cmd spring-boot:run +On macOS/Linux: + +./mvnw spring-boot:run +The application starts at: + +http://localhost:8080 +Frontend Pages +Open the login and registration page: + +http://localhost:8080/ +After login, the dashboard opens: + +http://localhost:8080/task-ui.html +The frontend stores the Basic Auth header and username in browser sessionStorage. + +Authentication +The app uses Spring Security with HTTP Basic authentication. + +Public routes: + +GET / +GET /index.html +GET /task-ui.html +GET /styles.css +GET /login.js +GET /app.js +GET /register +POST /register +Protected routes: + +GET /task +GET /task/{id} +POST /task +PUT /task +DELETE /task/{id} +API Endpoints +Register User +POST /register +Request body: + +{ + "username": "john", + "password": "1234" +} +Response: + +Registered +Notes: + +Username is trimmed and converted to lowercase. +Password is encrypted before saving. +Duplicate usernames return a conflict error. +View All Users +GET /register +Response: + +[ + { + "id": 1, + "username": "john", + "password": "encrypted_password" + } +] +Get Tasks By Username +GET /task?username=john +Requires Basic Auth. + +Response: + +[ + { + "title": "Complete project", + "description": "Finish task manager API", + "priority": "High", + "dueDate": "2026-04-20" + } +] +Get Task By ID +GET /task/1 +Requires Basic Auth. + +Response: + +{ + "id": 1, + "title": "Complete project", + "description": "Finish task manager API", + "priority": "High", + "dueDate": "2026-04-20", + "createdAt": "2026-04-18" +} +Create Task +POST /task?username=john +Requires Basic Auth. + +Request body: + +{ + "title": "Complete project", + "description": "Finish task manager API", + "priority": "High", + "dueDate": "2026-04-20" +} +Response: + +Inserted +Update Task +PUT /task +Requires Basic Auth. + +Request body: + +{ + "id": 1, + "title": "Complete project update", + "description": "Update task details", + "priority": "Medium", + "dueDate": "2026-04-25" +} +Response: + +Updated +Delete Task +DELETE /task/1 +Requires Basic Auth. + +Response: + +Deleted +Task Model +{ + "id": 1, + "title": "Task title", + "description": "Task description", + "priority": "High", + "dueDate": "2026-04-20", + "createdAt": "2026-04-18", + "assignedTo": { + "id": 1, + "username": "john" + } +} +User Model +{ + "id": 1, + "username": "john", + "password": "encrypted_password" +} +Example cURL Commands +Register a user: + +curl -X POST http://localhost:8080/register \ + -H "Content-Type: application/json" \ + -d "{\"username\":\"john\",\"password\":\"1234\"}" +Create a task: + +curl -X POST "http://localhost:8080/task?username=john" \ + -u john:1234 \ + -H "Content-Type: application/json" \ + -d "{\"title\":\"Learn Spring Boot\",\"description\":\"Build task manager API\",\"priority\":\"High\",\"dueDate\":\"2026-04-20\"}" +Get user tasks: + +curl "http://localhost:8080/task?username=john" \ + -u john:1234 +Update a task: + +curl -X PUT http://localhost:8080/task \ + -u john:1234 \ + -H "Content-Type: application/json" \ + -d "{\"id\":1,\"title\":\"Updated task\",\"description\":\"Updated description\",\"priority\":\"Medium\",\"dueDate\":\"2026-04-25\"}" +Delete a task: + +curl -X DELETE http://localhost:8080/task/1 \ + -u john:1234 +Testing +Run tests with: + +mvnw.cmd test +On macOS/Linux: + +./mvnw test +Notes +createdAt is set automatically when a task is created. +Usernames are stored in lowercase. +Tasks are linked to users through the assignedTo relationship. +The application uses stateless sessions, so each protected API request must include authentication. +Database credentials should be provided through environment variables, not hardcoded. +Future Improvements +Add JWT authentication +Add task status field +Add pagination for task lists +Hide passwords from user listing responses +Add stronger backend validation +Add role-based authorization +Add unit and integration tests for controllers and services diff --git a/TaskManager-Project/mvnw b/TaskManager-Project/mvnw new file mode 100644 index 0000000..bd8896b --- /dev/null +++ b/TaskManager-Project/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/TaskManager-Project/mvnw.cmd b/TaskManager-Project/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/TaskManager-Project/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/TaskManager-Project/pom.xml b/TaskManager-Project/pom.xml new file mode 100644 index 0000000..ac6485c --- /dev/null +++ b/TaskManager-Project/pom.xml @@ -0,0 +1,109 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.0.3 + + + com.TaskManagerAPIProject + TaskManagerAPI-Project + 0.0.1-SNAPSHOT + TaskManagerAPI-Project + Demo project for Spring Boot + + + + + + + + + + + + + + + 21 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-webmvc + + + + org.springframework.boot + spring-boot-starter-security + + + + + + + + + + + + org.postgresql + postgresql + runtime + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-data-jpa-test + test + + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/PasswordDecryptAndEncrypt.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/PasswordDecryptAndEncrypt.java new file mode 100644 index 0000000..bc1852a --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/PasswordDecryptAndEncrypt.java @@ -0,0 +1,14 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project; + +import org.springframework.stereotype.Component; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +@Component +public class PasswordDecryptAndEncrypt { + + public String passwordEncoder(String password){ + BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12); + return encoder.encode(password); + } + +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/Repository/UserRepo.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/Repository/UserRepo.java new file mode 100644 index 0000000..052b051 --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/Repository/UserRepo.java @@ -0,0 +1,13 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.Repository; + +import com.TaskManagerAPIProject.TaskManagerAPI_Project.model.user; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import org.springframework.web.bind.annotation.RequestParam; + +@Repository +public interface UserRepo extends JpaRepository { + user findByUsername(String username); + + +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/Repository/taskRepo.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/Repository/taskRepo.java new file mode 100644 index 0000000..d011f9d --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/Repository/taskRepo.java @@ -0,0 +1,14 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.Repository; + +import com.TaskManagerAPIProject.TaskManagerAPI_Project.model.Task; +import com.TaskManagerAPIProject.TaskManagerAPI_Project.model.dto.response.TaskTitleAndDecsResponse; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface taskRepo extends JpaRepository { + List findByAssignedToUsername(String username); + +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/TaskManagerApiProjectApplication.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/TaskManagerApiProjectApplication.java new file mode 100644 index 0000000..970f5a5 --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/TaskManagerApiProjectApplication.java @@ -0,0 +1,13 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class TaskManagerApiProjectApplication { + + public static void main(String[] args) { + SpringApplication.run(TaskManagerApiProjectApplication.class, args); + } + +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/configration/config.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/configration/config.java new file mode 100644 index 0000000..202d16d --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/configration/config.java @@ -0,0 +1,58 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.configration; + +import com.TaskManagerAPIProject.TaskManagerAPI_Project.service.userDetailService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.Customizer; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +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; + +@Configuration +@EnableWebSecurity +public class config { + + @Autowired + private userDetailService userDetailService; + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(12); + } + + @Bean + public AuthenticationProvider authenticationProvider(){ + DaoAuthenticationProvider provider = new DaoAuthenticationProvider(userDetailService); + provider.setPasswordEncoder(passwordEncoder()); + return provider; + } + + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http){ + + http + .csrf(csrf -> csrf.disable()) + .authorizeHttpRequests(auth -> + auth + .requestMatchers("/", "/index.html", "/task-ui.html", "/styles.css", "/login.js", "/app.js").permitAll() + .requestMatchers("/register").permitAll() + .anyRequest().authenticated() + ) + .httpBasic(Customizer.withDefaults()) + .sessionManagement(session -> + session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); + + return http.build(); + + } + + +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/controller/taskController.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/controller/taskController.java new file mode 100644 index 0000000..6733910 --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/controller/taskController.java @@ -0,0 +1,55 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.controller; + +import com.TaskManagerAPIProject.TaskManagerAPI_Project.model.Task; +import com.TaskManagerAPIProject.TaskManagerAPI_Project.model.dto.response.TaskTitleAndDecsResponse; +import com.TaskManagerAPIProject.TaskManagerAPI_Project.service.DtoService; +import com.TaskManagerAPIProject.TaskManagerAPI_Project.service.taskService; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +public class taskController { + @Autowired + private taskService service; + + @Autowired + private DtoService DtoService; + + + @GetMapping("/task") + public ResponseEntity> getAllTask(@RequestParam String username){ + List tasks = service.getAllTask(username); + return ResponseEntity.ok(tasks); + } + + @GetMapping("task/{id}") + public ResponseEntity getTask(@PathVariable int id){ + + Task task = service.getTask(id); + return ResponseEntity.ok(task); + } + + @PostMapping("/task") + public ResponseEntity insertTask(@RequestBody Task task, @RequestParam String username ){ + service.InsertTask(task, username); + return new ResponseEntity<>("Inserted", HttpStatus.CREATED); + } + + @PutMapping("task") + public ResponseEntity updateTask(@RequestBody Task task){ + service.updateOrInsertTask(task); + return new ResponseEntity<>("Updated", HttpStatus.OK); + } + + @DeleteMapping("task/{id}") + public ResponseEntity DeleteTask(@PathVariable int id){ + service.deleteTask(id); + return new ResponseEntity<>("Deleted", HttpStatus.OK); + } +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/controller/userController.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/controller/userController.java new file mode 100644 index 0000000..50f4223 --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/controller/userController.java @@ -0,0 +1,34 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.controller; + +import com.TaskManagerAPIProject.TaskManagerAPI_Project.model.user; +import com.TaskManagerAPIProject.TaskManagerAPI_Project.service.userService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +public class userController { + + @Autowired + private userService service; + + @GetMapping("/register") + public ResponseEntity> ViewAllUsers(){ + List user = service.ViewAllUsers(); + return new ResponseEntity<>(user, HttpStatus.OK); + } + + @PostMapping("/register") + public ResponseEntity RegisterUser(@RequestBody user user) { + service.RegisterUser(user); + return new ResponseEntity<>("Registered", HttpStatus.OK); + } + + +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/Task.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/Task.java new file mode 100644 index 0000000..76dca52 --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/Task.java @@ -0,0 +1,42 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.model; + + +import jakarta.persistence.*; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; + +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "tasks") +public class Task { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + private String title; + private String description; + private String priority; + + @JsonFormat(pattern = "yyyy-MM-dd") + private LocalDate dueDate; + + private LocalDate createdAt; + + @ManyToOne + @JoinColumn(name = "assigned_user_id") + private user assignedTo; + + @PrePersist + protected void onCreatedAt(){ + this.createdAt = LocalDate.now(); + } + + + + +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/UserPrinciple.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/UserPrinciple.java new file mode 100644 index 0000000..0d7215e --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/UserPrinciple.java @@ -0,0 +1,52 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.model; + +import org.jspecify.annotations.Nullable; +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; + +public class UserPrinciple implements UserDetails { + private user user; + + public UserPrinciple(user user){ + this.user = user; + } + + @Override + public Collection getAuthorities() { + return Collections.singleton(new SimpleGrantedAuthority("USER")); + } + + @Override + public @Nullable String getPassword() { + return user.getPassword(); + } + + @Override + public String getUsername() { + return user.getUsername(); + } + + @Override + public boolean isAccountNonExpired() { + return UserDetails.super.isAccountNonExpired(); + } + + @Override + public boolean isAccountNonLocked() { + return UserDetails.super.isAccountNonLocked(); + } + + @Override + public boolean isCredentialsNonExpired() { + return UserDetails.super.isCredentialsNonExpired(); + } + + @Override + public boolean isEnabled() { + return UserDetails.super.isEnabled(); + } +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/dto/request/CreateTask.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/dto/request/CreateTask.java new file mode 100644 index 0000000..5d9eb1a --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/dto/request/CreateTask.java @@ -0,0 +1,13 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.model.dto.request; + +import java.time.LocalDate; + +public class CreateTask { + private String title; + private String description; + private String priority; + private LocalDate dueDate; + + + +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/dto/request/TaskFilter.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/dto/request/TaskFilter.java new file mode 100644 index 0000000..2996654 --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/dto/request/TaskFilter.java @@ -0,0 +1,4 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.model.dto.request; + +public class TaskFilter { +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/dto/request/TaskTitleAndDescRequest.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/dto/request/TaskTitleAndDescRequest.java new file mode 100644 index 0000000..20afe54 --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/dto/request/TaskTitleAndDescRequest.java @@ -0,0 +1,4 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.model.dto.request; + +public record TaskTitleAndDescRequest() { +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/dto/request/UpdateTask.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/dto/request/UpdateTask.java new file mode 100644 index 0000000..3284235 --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/dto/request/UpdateTask.java @@ -0,0 +1,5 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.model.dto.request; + +public class UpdateTask { + +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/dto/response/TaskTitleAndDecsResponse.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/dto/response/TaskTitleAndDecsResponse.java new file mode 100644 index 0000000..3a4c4bd --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/dto/response/TaskTitleAndDecsResponse.java @@ -0,0 +1,13 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.model.dto.response; + +import com.fasterxml.jackson.annotation.JsonFormat; + +import java.time.LocalDate; + +public record TaskTitleAndDecsResponse( + String title, + String description, + String priority, + LocalDate dueDate +) { +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/user.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/user.java new file mode 100644 index 0000000..558226e --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/model/user.java @@ -0,0 +1,32 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Entity +@Data +@AllArgsConstructor +@NoArgsConstructor +@Table(name = "users") +public class user { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + @Column(unique = true, nullable = false) + private String username; + private String password; + + @JsonIgnore + @OneToMany(mappedBy = "assignedTo") + private List tasks; + + + +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/service/DtoService.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/service/DtoService.java new file mode 100644 index 0000000..2fdee7e --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/service/DtoService.java @@ -0,0 +1,32 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.service; + +import com.TaskManagerAPIProject.TaskManagerAPI_Project.Repository.taskRepo; +import com.TaskManagerAPIProject.TaskManagerAPI_Project.model.Task; +import com.TaskManagerAPIProject.TaskManagerAPI_Project.model.dto.response.TaskTitleAndDecsResponse; +import jakarta.websocket.server.ServerEndpoint; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class DtoService { + @Autowired + private taskRepo repo; + + + public List getAllTask(){ + List getTask = repo.findAll(); + + List response = new ArrayList<>(); + + for(Task t : getTask){ + response.add(new TaskTitleAndDecsResponse(t.getTitle(), t.getDescription(), t.getPriority(), t.getDueDate())); + + } + + return response; + + } +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/service/taskService.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/service/taskService.java new file mode 100644 index 0000000..30e65e2 --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/service/taskService.java @@ -0,0 +1,67 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.service; + + +import com.TaskManagerAPIProject.TaskManagerAPI_Project.Repository.UserRepo; +import com.TaskManagerAPIProject.TaskManagerAPI_Project.Repository.taskRepo; +import com.TaskManagerAPIProject.TaskManagerAPI_Project.model.Task; +import com.TaskManagerAPIProject.TaskManagerAPI_Project.model.dto.response.TaskTitleAndDecsResponse; +import com.TaskManagerAPIProject.TaskManagerAPI_Project.model.user; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; + +@Service +public class taskService { + + @Autowired + private taskRepo taskRepo; + + @Autowired + private UserRepo userRepo; + + public List getAllTask(String username){ + return taskRepo.findByAssignedToUsername(username.trim().toLowerCase()); + } + + public Task getTask(int id){ + return taskRepo.findById(id) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + + } + + public void InsertTask(Task task, String username){ + user assignUser = userRepo.findByUsername(username.trim().toLowerCase()); + + if(assignUser == null){ + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"); + } + + task.setAssignedTo(assignUser); + + taskRepo.save(task); + + } + + public void updateOrInsertTask(Task task) { + + // This check is for when updating the task. + if(task.getId() != null) + { + taskRepo.findById(task.getId()) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND,"task not found with id" + task.getId())); + } + + taskRepo.save(task); + } + + + public void deleteTask(int id){ + taskRepo.findById(id) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + taskRepo.deleteById(id); + + } +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/service/userDetailService.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/service/userDetailService.java new file mode 100644 index 0000000..cc58778 --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/service/userDetailService.java @@ -0,0 +1,29 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.service; + +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; + +import com.TaskManagerAPIProject.TaskManagerAPI_Project.Repository.UserRepo; +import com.TaskManagerAPIProject.TaskManagerAPI_Project.model.UserPrinciple; +import com.TaskManagerAPIProject.TaskManagerAPI_Project.model.user; + +@Service +public class userDetailService implements UserDetailsService { + + @Autowired + private UserRepo userRepo; + + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + user user = userRepo.findByUsername(username); + + if(user == null) + throw new UsernameNotFoundException("NOT FOUND"); + + return new UserPrinciple(user); + } +} diff --git a/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/service/userService.java b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/service/userService.java new file mode 100644 index 0000000..4a01bdd --- /dev/null +++ b/TaskManager-Project/src/main/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/service/userService.java @@ -0,0 +1,42 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project.service; + +import com.TaskManagerAPIProject.TaskManagerAPI_Project.PasswordDecryptAndEncrypt; +import com.TaskManagerAPIProject.TaskManagerAPI_Project.Repository.UserRepo; +import com.TaskManagerAPIProject.TaskManagerAPI_Project.model.user; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; + +@Service +public class userService { + + @Autowired + private UserRepo repo; + @Autowired + private PasswordDecryptAndEncrypt passwordDecryptAndEncrypt = new PasswordDecryptAndEncrypt(); + + + + public List ViewAllUsers() { + return repo.findAll(); + + } + + public void RegisterUser(user user) { + user.setUsername(user.getUsername().trim().toLowerCase()); + + if(repo.findByUsername(user.getUsername()) != null) + { + throw new ResponseStatusException(HttpStatus.CONFLICT, "Username already exists. Please choose another one."); + } + + user.setPassword(passwordDecryptAndEncrypt.passwordEncoder(user.getPassword())); + repo.save(user); + } + + + +} diff --git a/TaskManager-Project/src/main/resources/application.properties b/TaskManager-Project/src/main/resources/application.properties new file mode 100644 index 0000000..ffa458b --- /dev/null +++ b/TaskManager-Project/src/main/resources/application.properties @@ -0,0 +1,12 @@ +spring.application.name=TaskManagerAPI-Project + +spring.datasource.url=${DB_URL} +spring.datasource.username=${DB_USERNAME} +spring.datasource.password=${DB_PASSWORD} +spring.datasource.driver-class-name=org.postgresql.Driver + +spring.jpa.hibernate.ddl-auto = update +spring.jpa.show-sql=true + + +server.error.include-message=always diff --git a/TaskManager-Project/src/main/resources/static/app.js b/TaskManager-Project/src/main/resources/static/app.js new file mode 100644 index 0000000..f047aa7 --- /dev/null +++ b/TaskManager-Project/src/main/resources/static/app.js @@ -0,0 +1,328 @@ +(function () { + const authHeader = sessionStorage.getItem("taskflow.auth"); + const currentUser = sessionStorage.getItem("taskflow.user"); + + if (!authHeader || !currentUser) { + window.location.href = "/"; + return; + } + + const currentUserEl = document.getElementById("currentUser"); + const messageEl = document.getElementById("dashboardMessage"); + const resultsEl = document.getElementById("results"); + const taskCountEl = document.getElementById("taskCount"); + const loadTasksBtn = document.getElementById("loadTasksBtn"); + const fetchTaskBtn = document.getElementById("fetchTaskBtn"); + + currentUserEl.textContent = currentUser; + + function showMessage(text, isError) { + messageEl.textContent = text; + messageEl.className = `inline-message compact-message ${isError ? "error" : "success"}`; + } + + function setButtonLoading(button, isLoading, loadingText) { + if (!button) { + return; + } + + if (isLoading) { + if (!button.dataset.defaultText) { + button.dataset.defaultText = button.textContent; + } + button.disabled = true; + button.textContent = loadingText; + return; + } + + button.disabled = false; + button.textContent = button.dataset.defaultText || button.textContent; + } + + function normalizeText(value) { + return String(value || "").trim(); + } + + function isPositiveInteger(value) { + return /^\d+$/.test(String(value)) && Number(value) > 0; + } + + function isValidDateInput(value) { + if (!value) { + return true; + } + + if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) { + return false; + } + + const parsedDate = new Date(`${value}T00:00:00`); + return !Number.isNaN(parsedDate.getTime()) && parsedDate.toISOString().slice(0, 10) === value; + } + + function validateTitle(title) { + if (!title) { + throw new Error("Title is required."); + } + + if (title.length < 3) { + throw new Error("Title must be at least 3 characters long."); + } + + if (title.length > 100) { + throw new Error("Title must be 100 characters or fewer."); + } + } + + function validateDescription(description) { + if (description.length > 500) { + throw new Error("Description must be 500 characters or fewer."); + } + } + + function validateDueDate(dueDate) { + if (!isValidDateInput(dueDate)) { + throw new Error("Enter a valid due date."); + } + } + + function validateTaskId(taskId, actionLabel) { + if (!isPositiveInteger(taskId)) { + throw new Error(`Enter a valid task ID to ${actionLabel}.`); + } + } + + function validateTaskPayload(payload, requireId) { + validateTitle(payload.title); + validateDescription(payload.description); + validateDueDate(payload.dueDate); + + if (requireId) { + validateTaskId(payload.id, "update"); + } + } + + function badgeClass(priority) { + const value = (priority || "").toLowerCase(); + if (value === "high") return "high"; + if (value === "medium") return "medium"; + if (value === "low") return "low"; + return "none"; + } + + function escapeHtml(value) { + return String(value ?? "") + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); + } + + async function apiRequest(url, options) { + const response = await fetch(url, { + ...options, + headers: { + Authorization: authHeader, + ...(options && options.body ? { "Content-Type": "application/json" } : {}) + } + }); + + const raw = await response.text(); + let payload = null; + + try { + payload = raw ? JSON.parse(raw) : null; + } catch (error) { + payload = raw; + } + + if (!response.ok) { + throw new Error(typeof payload === "string" && payload ? payload : "Request failed."); + } + + return payload; + } + + function renderEmpty(message) { + taskCountEl.textContent = "No tasks loaded yet."; + resultsEl.innerHTML = ` +
+
+

No tasks to show

+

${escapeHtml(message)}

+
+
+ `; + } + + function renderTasks(tasks) { + if (!Array.isArray(tasks) || tasks.length === 0) { + renderEmpty("Load tasks from the dashboard to see them here."); + return; + } + + taskCountEl.textContent = `${tasks.length} task${tasks.length === 1 ? "" : "s"} loaded`; + resultsEl.innerHTML = tasks.map(function (task) { + const title = task.title || "Untitled task"; + const description = task.description || task.Description || "No description provided."; + const dueDate = task.dueDate || "No due date"; + const priority = task.priority || "Not set"; + + return ` +
+
+

${escapeHtml(title)}

+ ${escapeHtml(priority)} +
+

${escapeHtml(description)}

+
+ Due: ${escapeHtml(dueDate)} + ID: ${escapeHtml(task.id ?? "-")} +
+
+ `; + }).join(""); + } + + function getCreatePayload() { + const payload = { + title: normalizeText(document.getElementById("createTitle").value), + description: normalizeText(document.getElementById("createDescription").value), + priority: document.getElementById("createPriority").value || null, + dueDate: document.getElementById("createDueDate").value || null + }; + + validateTaskPayload(payload, false); + return payload; + } + + function getUpdatePayload() { + const taskId = normalizeText(document.getElementById("updateTaskId").value); + const payload = { + id: Number(taskId), + title: normalizeText(document.getElementById("updateTitle").value), + description: normalizeText(document.getElementById("updateDescription").value), + priority: document.getElementById("updatePriority").value || null, + dueDate: document.getElementById("updateDueDate").value || null + }; + + validateTaskId(taskId, "update"); + validateTaskPayload(payload, true); + return payload; + } + + function fillUpdateForm(task) { + document.getElementById("updateTaskId").value = task.id ?? ""; + document.getElementById("updateTitle").value = task.title ?? ""; + document.getElementById("updateDescription").value = task.description ?? task.Description ?? ""; + document.getElementById("updatePriority").value = task.priority ?? ""; + document.getElementById("updateDueDate").value = task.dueDate ?? ""; + } + + async function loadTasks() { + setButtonLoading(loadTasksBtn, true, "Loading..."); + + try { + const tasks = await apiRequest(`/task?username=${encodeURIComponent(currentUser)}`, {}); + renderTasks(tasks); + showMessage("Tasks loaded successfully.", false); + } catch (error) { + renderEmpty("Unable to load tasks. Please try again."); + showMessage(error.message, true); + } finally { + setButtonLoading(loadTasksBtn, false); + } + } + + loadTasksBtn.addEventListener("click", loadTasks); + + document.getElementById("createTaskForm").addEventListener("submit", async function (event) { + event.preventDefault(); + const submitButton = event.target.querySelector('button[type="submit"]'); + + try { + setButtonLoading(submitButton, true, "Creating..."); + const payload = getCreatePayload(); + await apiRequest(`/task?username=${encodeURIComponent(currentUser)}`, { + method: "POST", + body: JSON.stringify(payload) + }); + showMessage("Task created successfully.", false); + event.target.reset(); + await loadTasks(); + } catch (error) { + showMessage(error.message, true); + } finally { + setButtonLoading(submitButton, false); + } + }); + + fetchTaskBtn.addEventListener("click", async function () { + const taskId = normalizeText(document.getElementById("updateTaskId").value); + + try { + setButtonLoading(fetchTaskBtn, true, "Loading..."); + validateTaskId(taskId, "fetch"); + const task = await apiRequest(`/task/${taskId}`, {}); + fillUpdateForm(task); + renderTasks([task]); + showMessage(`Task ${taskId} loaded into the update section.`, false); + } catch (error) { + showMessage(error.message, true); + } finally { + setButtonLoading(fetchTaskBtn, false); + } + }); + + document.getElementById("updateTaskForm").addEventListener("submit", async function (event) { + event.preventDefault(); + const submitButton = event.target.querySelector('button[type="submit"]'); + + try { + setButtonLoading(submitButton, true, "Updating..."); + const payload = getUpdatePayload(); + await apiRequest("/task", { + method: "PUT", + body: JSON.stringify(payload) + }); + showMessage("Task updated successfully.", false); + await loadTasks(); + } catch (error) { + showMessage(error.message, true); + } finally { + setButtonLoading(submitButton, false); + } + }); + + document.getElementById("deleteTaskForm").addEventListener("submit", async function (event) { + event.preventDefault(); + const submitButton = event.target.querySelector('button[type="submit"]'); + + const taskId = normalizeText(document.getElementById("deleteTaskId").value); + + try { + setButtonLoading(submitButton, true, "Deleting..."); + validateTaskId(taskId, "delete"); + await apiRequest(`/task/${taskId}`, { + method: "DELETE" + }); + showMessage(`Task ${taskId} deleted successfully.`, false); + event.target.reset(); + await loadTasks(); + } catch (error) { + showMessage(error.message, true); + } finally { + setButtonLoading(submitButton, false); + } + }); + + document.getElementById("logoutBtn").addEventListener("click", function () { + sessionStorage.removeItem("taskflow.auth"); + sessionStorage.removeItem("taskflow.user"); + window.location.href = "/"; + }); + + renderEmpty("Sign in and load tasks to start managing your work."); + loadTasks(); +})(); diff --git a/TaskManager-Project/src/main/resources/static/index.html b/TaskManager-Project/src/main/resources/static/index.html new file mode 100644 index 0000000..f6e4765 --- /dev/null +++ b/TaskManager-Project/src/main/resources/static/index.html @@ -0,0 +1,95 @@ + + + + + + TaskFlow Login + + + + + + +
+ + + +
+ + + + diff --git a/TaskManager-Project/src/main/resources/static/login.js b/TaskManager-Project/src/main/resources/static/login.js new file mode 100644 index 0000000..af9d140 --- /dev/null +++ b/TaskManager-Project/src/main/resources/static/login.js @@ -0,0 +1,185 @@ +(function () { + const form = document.getElementById("loginForm"); + const registerForm = document.getElementById("registerForm"); + const messageEl = document.getElementById("loginMessage"); + const registerMessageEl = document.getElementById("registerMessage"); + const usernameEl = document.getElementById("username"); + const passwordEl = document.getElementById("password"); + const registerUsernameEl = document.getElementById("registerUsername"); + const registerPasswordEl = document.getElementById("registerPassword"); + const togglePasswordBtn = document.getElementById("togglePasswordBtn"); + const toggleRegisterPasswordBtn = document.getElementById("toggleRegisterPasswordBtn"); + + function setMessage(target, text, isError) { + target.textContent = text; + target.className = `inline-message ${isError ? "error" : "success"}`; + } + + function showMessage(text, isError) { + setMessage(messageEl, text, isError); + } + + function showRegisterMessage(text, isError) { + setMessage(registerMessageEl, text, isError); + } + + function extractErrorMessage(rawText, fallbackMessage) { + if (!rawText) { + return fallbackMessage; + } + + const normalized = rawText.trim(); + + try { + const parsed = JSON.parse(normalized); + if (parsed && typeof parsed.message === "string" && parsed.message.trim()) { + return parsed.message.trim(); + } + if (parsed && typeof parsed.error === "string" && parsed.error.trim()) { + return parsed.error.trim(); + } + } catch (error) { + // Keep the raw text when the response is not JSON. + } + + return normalized; + } + + function mapRegisterErrorMessage(message) { + const normalized = String(message || "").toLowerCase(); + + if (normalized.includes("username already exists")) { + return "Username already exists. Please choose another one."; + } + + if (normalized.includes("conflict")) { + return "Username already exists. Please choose another one."; + } + + return message || "Registration failed. Please try again."; + } + + function setButtonLoading(button, isLoading, loadingText) { + if (isLoading) { + if (!button.dataset.defaultText) { + button.dataset.defaultText = button.textContent; + } + button.disabled = true; + button.textContent = loadingText; + return; + } + + button.disabled = false; + button.textContent = button.dataset.defaultText || button.textContent; + } + + function validateCredentials(username, password) { + if (!username || !password) { + throw new Error("Please enter both username and password."); + } + + if (username.length < 3) { + throw new Error("Username must be at least 3 characters long."); + } + + if (password.length < 4) { + throw new Error("Password must be at least 4 characters long."); + } + } + + async function tryLogin(username, password) { + const authHeader = "Basic " + btoa(username + ":" + password); + const normalizedUsername = username.trim().toLowerCase(); + const response = await fetch(`/task?username=${encodeURIComponent(normalizedUsername)}`, { + headers: { + Authorization: authHeader + } + }); + + if (!response.ok) { + const detail = await response.text(); + throw new Error(detail || "Login failed. Please check your username and password."); + } + + sessionStorage.setItem("taskflow.auth", authHeader); + sessionStorage.setItem("taskflow.user", normalizedUsername); + } + + async function registerUser(username, password) { + const response = await fetch("/register", { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ + username: username, + password: password + }) + }); + + const detail = await response.text(); + + if (!response.ok) { + const errorMessage = extractErrorMessage(detail, "Registration failed. Please try a different username."); + throw new Error(mapRegisterErrorMessage(errorMessage)); + } + } + + togglePasswordBtn.addEventListener("click", function () { + const showingPassword = passwordEl.type === "text"; + passwordEl.type = showingPassword ? "password" : "text"; + togglePasswordBtn.textContent = showingPassword ? "Show" : "Hide"; + togglePasswordBtn.setAttribute("aria-label", showingPassword ? "Show password" : "Hide password"); + }); + + toggleRegisterPasswordBtn.addEventListener("click", function () { + const showingPassword = registerPasswordEl.type === "text"; + registerPasswordEl.type = showingPassword ? "password" : "text"; + toggleRegisterPasswordBtn.textContent = showingPassword ? "Show" : "Hide"; + toggleRegisterPasswordBtn.setAttribute("aria-label", showingPassword ? "Show register password" : "Hide register password"); + }); + + form.addEventListener("submit", async function (event) { + event.preventDefault(); + + const username = usernameEl.value.trim(); + const password = passwordEl.value; + + const button = document.getElementById("loginBtn"); + + try { + validateCredentials(username, password); + setButtonLoading(button, true, "Signing in..."); + await tryLogin(username, password); + showMessage("Login successful. Opening your dashboard...", false); + window.location.href = "/task-ui.html"; + } catch (error) { + showMessage(error.message, true); + } finally { + setButtonLoading(button, false); + } + }); + + registerForm.addEventListener("submit", async function (event) { + event.preventDefault(); + + const username = registerUsernameEl.value.trim(); + const password = registerPasswordEl.value; + const button = document.getElementById("registerBtn"); + + try { + validateCredentials(username, password); + setButtonLoading(button, true, "Registering..."); + await registerUser(username, password); + showRegisterMessage("User registered successfully. You can sign in now.", false); + registerForm.reset(); + registerPasswordEl.type = "password"; + toggleRegisterPasswordBtn.textContent = "Show"; + toggleRegisterPasswordBtn.setAttribute("aria-label", "Show register password"); + } catch (error) { + showRegisterMessage(error.message, true); + } finally { + setButtonLoading(button, false); + } + }); +})(); diff --git a/TaskManager-Project/src/main/resources/static/styles.css b/TaskManager-Project/src/main/resources/static/styles.css new file mode 100644 index 0000000..a96d907 --- /dev/null +++ b/TaskManager-Project/src/main/resources/static/styles.css @@ -0,0 +1,580 @@ +:root { + --bg-main: #f3efe7; + --bg-soft: #fbf8f3; + --bg-panel: rgba(255, 255, 255, 0.82); + --bg-panel-strong: #ffffff; + --bg-dark: #13232f; + --ink: #14202b; + --muted: #5d6a72; + --line: rgba(20, 32, 43, 0.12); + --line-strong: rgba(20, 32, 43, 0.18); + --accent: #0f766e; + --accent-strong: #0b5f58; + --accent-soft: rgba(15, 118, 110, 0.12); + --danger: #b8463b; + --danger-soft: rgba(184, 70, 59, 0.12); + --shadow: 0 24px 70px rgba(19, 35, 47, 0.12); + --radius-xl: 28px; + --radius-lg: 22px; + --radius-md: 16px; + --radius-sm: 12px; +} + +* { + box-sizing: border-box; +} + +html, body { + margin: 0; + min-height: 100%; +} + +body { + font-family: "Manrope", sans-serif; + color: var(--ink); + background: + radial-gradient(circle at top left, rgba(15, 118, 110, 0.18), transparent 28%), + radial-gradient(circle at bottom right, rgba(190, 154, 93, 0.18), transparent 24%), + linear-gradient(180deg, #f6f1e8 0%, #f1f5f4 100%); +} + +h1, h2, h3, strong { + font-family: "Space Grotesk", sans-serif; + margin: 0; +} + +p { + margin: 0; +} + +button, input, select, textarea { + font: inherit; +} + +.login-body, +.dashboard-body { + padding: 32px; +} + +.login-shell { + min-height: calc(100vh - 64px); + display: grid; + grid-template-columns: 1.1fr 0.9fr; + gap: 28px; + align-items: stretch; +} + +.login-hero, +.login-card, +.panel-card, +.results-panel, +.dashboard-topbar { + backdrop-filter: blur(16px); + background: var(--bg-panel); + border: 1px solid rgba(255, 255, 255, 0.65); + box-shadow: var(--shadow); +} + +.login-hero { + border-radius: var(--radius-xl); + padding: 48px; + display: flex; + flex-direction: column; + justify-content: space-between; + position: relative; + overflow: hidden; +} + +.login-hero::after { + content: ""; + position: absolute; + inset: auto -40px -40px auto; + width: 220px; + height: 220px; + border-radius: 50%; + background: radial-gradient(circle, rgba(15, 118, 110, 0.24), transparent 68%); +} + +.brand-badge, +.section-eyebrow { + display: inline-flex; + width: fit-content; + padding: 7px 12px; + border-radius: 999px; + background: rgba(20, 32, 43, 0.06); + border: 1px solid rgba(20, 32, 43, 0.08); + color: var(--muted); + font-size: 0.78rem; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.login-hero h1 { + font-size: clamp(2.6rem, 4vw, 4.4rem); + line-height: 1.02; + max-width: 10ch; + margin: 18px 0 16px; +} + +.login-hero p { + max-width: 560px; + color: var(--muted); + font-size: 1.02rem; + line-height: 1.75; +} + +.hero-stats { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 16px; + margin-top: 36px; +} + +.hero-stats article { + padding: 18px; + background: rgba(255, 255, 255, 0.56); + border: 1px solid rgba(20, 32, 43, 0.08); + border-radius: var(--radius-lg); +} + +.hero-stats span { + display: block; + color: var(--muted); + font-size: 0.82rem; + margin-bottom: 8px; +} + +.hero-stats strong { + font-size: 1.02rem; +} + +.login-card { + border-radius: var(--radius-xl); + padding: 18px; + position: relative; + overflow: hidden; +} + +.card-glow { + position: absolute; + inset: 0; + background: + linear-gradient(135deg, rgba(15, 118, 110, 0.14), transparent 40%), + linear-gradient(315deg, rgba(19, 35, 47, 0.08), transparent 38%); +} + +.login-card-content { + position: relative; + z-index: 1; + border-radius: calc(var(--radius-xl) - 8px); + background: rgba(255, 255, 255, 0.8); + border: 1px solid rgba(255, 255, 255, 0.5); + height: 100%; + padding: 36px; + display: flex; + flex-direction: column; + justify-content: center; +} + +.login-card-content h2, +.card-header h2, +.results-toolbar h2, +.dashboard-topbar h1 { + font-size: 1.8rem; + letter-spacing: -0.04em; +} + +.section-copy, +.card-copy, +.results-copy, +.topbar-copy { + color: var(--muted); + line-height: 1.65; + margin-top: 10px; +} + +.form-stack { + display: flex; + flex-direction: column; + gap: 16px; + margin-top: 26px; +} + +.compact-form { + margin-top: 18px; +} + +.form-divider { + margin: 26px 0 0; + display: flex; + align-items: center; + gap: 12px; + color: var(--muted); + font-size: 0.82rem; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.08em; +} + +.form-divider::before, +.form-divider::after { + content: ""; + height: 1px; + flex: 1; + background: var(--line); +} + +.input-stack { + display: flex; + flex-direction: column; + gap: 8px; +} + +.input-stack span { + font-size: 0.9rem; + font-weight: 700; + color: var(--ink); +} + +.input-stack input, +.input-stack select, +.input-stack textarea { + width: 100%; + padding: 14px 16px; + border-radius: var(--radius-sm); + border: 1px solid var(--line); + background: rgba(255, 255, 255, 0.85); + color: var(--ink); + outline: none; + transition: border-color 0.18s ease, box-shadow 0.18s ease, transform 0.18s ease; +} + +.password-field { + position: relative; +} + +.password-field input { + padding-right: 84px; +} + +.password-toggle { + position: absolute; + top: 50%; + right: 10px; + transform: translateY(-50%); + border: none; + background: rgba(20, 32, 43, 0.06); + color: var(--ink); + border-radius: 999px; + padding: 8px 12px; + font-size: 0.84rem; + font-weight: 800; + cursor: pointer; + transition: background 0.18s ease, transform 0.18s ease; +} + +.password-toggle:hover { + background: rgba(15, 118, 110, 0.12); +} + +.password-toggle:focus-visible { + outline: 2px solid rgba(15, 118, 110, 0.35); + outline-offset: 2px; +} + +.input-stack textarea { + resize: vertical; + min-height: 108px; +} + +.input-stack input:focus, +.input-stack select:focus, +.input-stack textarea:focus { + border-color: rgba(15, 118, 110, 0.55); + box-shadow: 0 0 0 4px rgba(15, 118, 110, 0.12); + transform: translateY(-1px); +} + +.primary-btn, +.secondary-btn, +.danger-btn { + border: none; + border-radius: 999px; + padding: 14px 22px; + font-weight: 800; + cursor: pointer; + transition: transform 0.18s ease, box-shadow 0.18s ease, opacity 0.18s ease; +} + +.primary-btn:hover, +.secondary-btn:hover, +.danger-btn:hover { + transform: translateY(-1px); +} + +.primary-btn:disabled, +.secondary-btn:disabled, +.danger-btn:disabled { + cursor: not-allowed; + opacity: 0.7; + transform: none; + box-shadow: none; +} + +.secondary-btn:not(:disabled) { + box-shadow: 0 10px 22px rgba(20, 32, 43, 0.07); +} + +.primary-btn { + background: linear-gradient(135deg, var(--accent), var(--accent-strong)); + color: #ffffff; + box-shadow: 0 16px 28px rgba(15, 118, 110, 0.22); +} + +.secondary-btn { + background: rgba(20, 32, 43, 0.06); + color: var(--ink); + border: 1px solid rgba(20, 32, 43, 0.08); +} + +.danger-btn { + background: linear-gradient(135deg, var(--danger), #94362e); + color: #ffffff; + box-shadow: 0 16px 28px rgba(184, 70, 59, 0.2); +} + +.wide-btn { + width: 100%; +} + +.inline-message { + display: none; + margin-top: 18px; + padding: 12px 14px; + border-radius: var(--radius-sm); + font-size: 0.92rem; + line-height: 1.55; +} + +.inline-message.success { + display: block; + background: var(--accent-soft); + color: var(--accent-strong); + border: 1px solid rgba(15, 118, 110, 0.2); +} + +.inline-message.error { + display: block; + background: var(--danger-soft); + color: var(--danger); + border: 1px solid rgba(184, 70, 59, 0.2); +} + +.dashboard-shell { + display: flex; + flex-direction: column; + gap: 24px; +} + +.dashboard-topbar { + border-radius: var(--radius-xl); + padding: 28px 32px; + display: flex; + justify-content: space-between; + gap: 18px; + align-items: center; +} + +.topbar-actions { + display: flex; + align-items: center; + gap: 14px; +} + +.user-pill { + padding: 14px 18px; + background: rgba(255, 255, 255, 0.7); + border: 1px solid var(--line); + border-radius: 18px; +} + +.user-pill-label { + display: block; + color: var(--muted); + font-size: 0.8rem; + margin-bottom: 4px; +} + +.dashboard-grid { + display: grid; + grid-template-columns: 400px 1fr; + gap: 24px; +} + +.control-panel { + display: flex; + flex-direction: column; + gap: 18px; +} + +.panel-card, +.results-panel { + border-radius: var(--radius-xl); + padding: 24px; +} + +.card-header, +.results-toolbar { + display: flex; + justify-content: space-between; + gap: 16px; + align-items: flex-start; +} + +.dual-field { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 14px; +} + +.danger-card { + border-color: rgba(184, 70, 59, 0.18); +} + +.compact-message { + width: min(320px, 100%); + margin-top: 0; +} + +.task-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); + gap: 18px; + margin-top: 26px; +} + +.task-card { + background: var(--bg-panel-strong); + border: 1px solid var(--line); + border-radius: 24px; + padding: 22px; + box-shadow: 0 16px 28px rgba(20, 32, 43, 0.06); + display: flex; + flex-direction: column; + gap: 14px; +} + +.task-card-top, +.task-card-meta { + display: flex; + justify-content: space-between; + gap: 12px; + align-items: flex-start; +} + +.task-card h3 { + font-size: 1.08rem; + line-height: 1.3; +} + +.task-card p { + color: var(--muted); + line-height: 1.6; +} + +.badge { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 7px 12px; + border-radius: 999px; + font-size: 0.76rem; + font-weight: 800; + text-transform: uppercase; + letter-spacing: 0.06em; + white-space: nowrap; +} + +.badge.high { + background: rgba(184, 70, 59, 0.12); + color: var(--danger); +} + +.badge.medium { + background: rgba(201, 133, 31, 0.14); + color: #9b6400; +} + +.badge.low { + background: rgba(15, 118, 110, 0.12); + color: var(--accent-strong); +} + +.badge.none { + background: rgba(20, 32, 43, 0.08); + color: var(--muted); +} + +.task-meta-text { + color: var(--muted); + font-size: 0.88rem; +} + +.empty-state { + min-height: 360px; + display: grid; + place-items: center; + text-align: center; + padding: 32px; + border: 1px dashed var(--line-strong); + border-radius: 24px; + background: rgba(255, 255, 255, 0.4); +} + +.empty-state div:first-child { + max-width: 380px; +} + +@media (max-width: 1100px) { + .login-shell, + .dashboard-grid { + grid-template-columns: 1fr; + } + + .dashboard-topbar, + .card-header, + .results-toolbar { + flex-direction: column; + } +} + +@media (max-width: 720px) { + .login-body, + .dashboard-body { + padding: 18px; + } + + .login-hero, + .login-card-content, + .panel-card, + .results-panel, + .dashboard-topbar { + padding: 22px; + } + + .hero-stats, + .dual-field { + grid-template-columns: 1fr; + } + + .topbar-actions { + width: 100%; + flex-direction: column; + align-items: stretch; + } + + .compact-message { + width: 100%; + } +} diff --git a/TaskManager-Project/src/main/resources/static/task-ui.html b/TaskManager-Project/src/main/resources/static/task-ui.html new file mode 100644 index 0000000..e6184fb --- /dev/null +++ b/TaskManager-Project/src/main/resources/static/task-ui.html @@ -0,0 +1,152 @@ + + + + + + TaskFlow Dashboard + + + + + + +
+
+
+
TaskFlow Dashboard
+

Task management workspace

+

View every task after login and manage each action in its own professional section.

+
+ +
+
+ Signed in as + User +
+ +
+
+ +
+ + +
+
+
+
Overview
+

Task list

+

No tasks loaded yet.

+
+
+
+ +
+
+
+
+ + + + diff --git a/TaskManager-Project/src/test/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/TaskManagerApiProjectApplicationTests.java b/TaskManager-Project/src/test/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/TaskManagerApiProjectApplicationTests.java new file mode 100644 index 0000000..7a24ebf --- /dev/null +++ b/TaskManager-Project/src/test/java/com/TaskManagerAPIProject/TaskManagerAPI_Project/TaskManagerApiProjectApplicationTests.java @@ -0,0 +1,13 @@ +package com.TaskManagerAPIProject.TaskManagerAPI_Project; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class TaskManagerApiProjectApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/java-for-everybody.iml b/java-for-everybody.iml new file mode 100644 index 0000000..b107a2d --- /dev/null +++ b/java-for-everybody.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file