diff --git a/server/.gitignore b/server/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/server/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/server/build.gradle b/server/build.gradle new file mode 100644 index 0000000..110af72 --- /dev/null +++ b/server/build.gradle @@ -0,0 +1,45 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.5' + id 'io.spring.dependency-management' version '1.1.3' +} + +group = 'com.usatiuk.tjv.y' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-actuator' +// implementation 'org.springframework.boot:spring-boot-starter-data-rest' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.security:spring-security-test' + compileOnly 'org.projectlombok:lombok' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + runtimeOnly 'com.h2database:h2' + runtimeOnly 'org.mariadb.jdbc:mariadb-java-client' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + + implementation 'io.jsonwebtoken:jjwt-api:0.12.3' + runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.12.3' + runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.12.3' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/server/gradle/wrapper/gradle-wrapper.jar b/server/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7f93135 Binary files /dev/null and b/server/gradle/wrapper/gradle-wrapper.jar differ diff --git a/server/gradle/wrapper/gradle-wrapper.properties b/server/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..3fa8f86 --- /dev/null +++ b/server/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/server/gradlew b/server/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/server/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/server/gradlew.bat b/server/gradlew.bat new file mode 100644 index 0000000..6689b85 --- /dev/null +++ b/server/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/server/settings.gradle b/server/settings.gradle new file mode 100644 index 0000000..096502d --- /dev/null +++ b/server/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'server' diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/ServerApplication.java b/server/src/main/java/com/usatiuk/tjv/y/server/ServerApplication.java new file mode 100644 index 0000000..5e4331c --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/ServerApplication.java @@ -0,0 +1,13 @@ +package com.usatiuk.tjv.y.server; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ServerApplication { + + public static void main(String[] args) { + SpringApplication.run(ServerApplication.class, args); + } + +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/controller/PersonController.java b/server/src/main/java/com/usatiuk/tjv/y/server/controller/PersonController.java new file mode 100644 index 0000000..cbaf532 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/controller/PersonController.java @@ -0,0 +1,37 @@ +package com.usatiuk.tjv.y.server.controller; + +import com.usatiuk.tjv.y.server.dto.PersonAuthResponse; +import com.usatiuk.tjv.y.server.dto.PersonLoginRequest; +import com.usatiuk.tjv.y.server.dto.PersonSignupRequest; +import com.usatiuk.tjv.y.server.entity.Person; +import com.usatiuk.tjv.y.server.service.PersonService; +import com.usatiuk.tjv.y.server.service.PersonTokenService; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(value = "/person", produces = MediaType.APPLICATION_JSON_VALUE) +public class PersonController { + private final PersonService personService; + private final PersonTokenService personTokenService; + + public PersonController(PersonService personService, PersonTokenService personTokenService) { + this.personService = personService; + this.personTokenService = personTokenService; + } + + @PostMapping + public PersonAuthResponse signup(@RequestBody PersonSignupRequest signupRequest) { + Person toCreate = new Person(); + toCreate.setUsername(signupRequest.username()) + .setPassword(signupRequest.password()) + .setFullName(signupRequest.fullName()); + + Person created = personService.signup(toCreate); + + return new PersonAuthResponse(created, personTokenService.generateToken(created.getId())); + } +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/controller/PostController.java b/server/src/main/java/com/usatiuk/tjv/y/server/controller/PostController.java new file mode 100644 index 0000000..f4b8663 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/controller/PostController.java @@ -0,0 +1,42 @@ +package com.usatiuk.tjv.y.server.controller; + +import com.usatiuk.tjv.y.server.dto.PostCreate; +import com.usatiuk.tjv.y.server.dto.PostTo; +import com.usatiuk.tjv.y.server.entity.Person; +import com.usatiuk.tjv.y.server.entity.Post; +import com.usatiuk.tjv.y.server.service.PostService; +import jakarta.persistence.EntityManager; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +import java.security.Principal; +import java.util.Optional; + +@RestController +@RequestMapping(value = "/post", produces = MediaType.APPLICATION_JSON_VALUE) +public class PostController { + private final PostService postService; + private final EntityManager entityManager; + + public PostController(PostService postService, EntityManager entityManager) { + this.postService = postService; + this.entityManager = entityManager; + } + + @PostMapping + public PostTo createPost(Principal principal, @RequestBody PostCreate postCreate) { + Post post = new Post(); + post.setAuthor(entityManager.getReference(Person.class, principal.getName())); + post.setText(postCreate.text()); + return new PostTo(postService.create(post)); + } + + @GetMapping + public Iterable readAllOrByAuthor(@RequestParam Optional author) { + if (author.isPresent()) + return postService.readByAuthorId(author.get()); + else + return postService.readAll(); + } + +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/dto/PersonAuthResponse.java b/server/src/main/java/com/usatiuk/tjv/y/server/dto/PersonAuthResponse.java new file mode 100644 index 0000000..706a80a --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/dto/PersonAuthResponse.java @@ -0,0 +1,9 @@ +package com.usatiuk.tjv.y.server.dto; + +import com.usatiuk.tjv.y.server.entity.Person; + +public record PersonAuthResponse(String uuid, String username, String fullName, String token) { + public PersonAuthResponse(Person person, String token) { + this(person.getId(), person.getUsername(), person.getFullName(), token); + } +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/dto/PersonLoginRequest.java b/server/src/main/java/com/usatiuk/tjv/y/server/dto/PersonLoginRequest.java new file mode 100644 index 0000000..f42125f --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/dto/PersonLoginRequest.java @@ -0,0 +1,4 @@ +package com.usatiuk.tjv.y.server.dto; + +public record PersonLoginRequest(String username, String password) { +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/dto/PersonSignupRequest.java b/server/src/main/java/com/usatiuk/tjv/y/server/dto/PersonSignupRequest.java new file mode 100644 index 0000000..60192d2 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/dto/PersonSignupRequest.java @@ -0,0 +1,4 @@ +package com.usatiuk.tjv.y.server.dto; + +public record PersonSignupRequest(String username, String fullName, String password) { +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/dto/PostCreate.java b/server/src/main/java/com/usatiuk/tjv/y/server/dto/PostCreate.java new file mode 100644 index 0000000..a862b73 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/dto/PostCreate.java @@ -0,0 +1,4 @@ +package com.usatiuk.tjv.y.server.dto; + +public record PostCreate(String text) { +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/dto/PostTo.java b/server/src/main/java/com/usatiuk/tjv/y/server/dto/PostTo.java new file mode 100644 index 0000000..6d2cb6c --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/dto/PostTo.java @@ -0,0 +1,9 @@ +package com.usatiuk.tjv.y.server.dto; + +import com.usatiuk.tjv.y.server.entity.Post; + +public record PostTo(Long id, String authorUuid, String text) { + public PostTo(Post post) { + this(post.getId(), post.getAuthor().getUuid(), post.getText()); + } +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/entity/EntityWithId.java b/server/src/main/java/com/usatiuk/tjv/y/server/entity/EntityWithId.java new file mode 100644 index 0000000..2fb5701 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/entity/EntityWithId.java @@ -0,0 +1,5 @@ +package com.usatiuk.tjv.y.server.entity; + +public interface EntityWithId { + ID getId(); +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/entity/Person.java b/server/src/main/java/com/usatiuk/tjv/y/server/entity/Person.java new file mode 100644 index 0000000..13bafc8 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/entity/Person.java @@ -0,0 +1,36 @@ +package com.usatiuk.tjv.y.server.entity; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.Accessors; + +import java.util.Collection; + +@Entity +@Getter +@Setter +@NoArgsConstructor +@ToString +@Accessors(chain = true) +public class Person implements EntityWithId { + @Id + @GeneratedValue(strategy = GenerationType.UUID) + private String uuid; + + @Column(unique = true) + private String username; + + private String fullName; + private String password; + + @OneToMany(mappedBy = "author") + private Collection posts; + + @Override + public String getId() { + return uuid; + } +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/entity/Post.java b/server/src/main/java/com/usatiuk/tjv/y/server/entity/Post.java new file mode 100644 index 0000000..171fed3 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/entity/Post.java @@ -0,0 +1,31 @@ +package com.usatiuk.tjv.y.server.entity; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.Accessors; + +@Entity +@Getter +@Setter +@NoArgsConstructor +@ToString +@Accessors(chain = true) +public class Post implements EntityWithId { + @Id + @GeneratedValue + private Long id; + + @ManyToOne + private Person author; + + @Lob + private String text; + + @Override + public Long getId() { + return id; + } +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/repository/PersonRepository.java b/server/src/main/java/com/usatiuk/tjv/y/server/repository/PersonRepository.java new file mode 100644 index 0000000..2f9456d --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/repository/PersonRepository.java @@ -0,0 +1,7 @@ +package com.usatiuk.tjv.y.server.repository; + +import com.usatiuk.tjv.y.server.entity.Person; +import org.springframework.data.repository.CrudRepository; + +public interface PersonRepository extends CrudRepository { +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/repository/PostRepository.java b/server/src/main/java/com/usatiuk/tjv/y/server/repository/PostRepository.java new file mode 100644 index 0000000..3ae4dc2 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/repository/PostRepository.java @@ -0,0 +1,10 @@ +package com.usatiuk.tjv.y.server.repository; + +import com.usatiuk.tjv.y.server.entity.Post; +import org.springframework.data.repository.CrudRepository; + +import java.util.Collection; + +public interface PostRepository extends CrudRepository { + Collection findByAuthorUuid(String authorUuid); +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/security/JwtRequestFilter.java b/server/src/main/java/com/usatiuk/tjv/y/server/security/JwtRequestFilter.java new file mode 100644 index 0000000..e05f952 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/security/JwtRequestFilter.java @@ -0,0 +1,55 @@ +package com.usatiuk.tjv.y.server.security; + +import com.usatiuk.tjv.y.server.service.PersonTokenService; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.HttpHeaders; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.Optional; + +@Component +public class JwtRequestFilter extends OncePerRequestFilter { + private final PersonTokenService personTokenService; + private final JwtUserDetailsService jwtUserDetailsService; + + public JwtRequestFilter(PersonTokenService personTokenService, JwtUserDetailsService jwtUserDetailsService) { + this.personTokenService = personTokenService; + this.jwtUserDetailsService = jwtUserDetailsService; + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { + String header = request.getHeader(HttpHeaders.AUTHORIZATION); + if (header == null || !header.startsWith("Bearer ")) { + filterChain.doFilter(request, response); + return; + } + + String token = header.substring(7); + Optional userUuid = personTokenService.parseToken(token); + if (userUuid.isEmpty()) { + filterChain.doFilter(request, response); + return; + } + + UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(userUuid.get()); + + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( + userDetails, null, userDetails.getAuthorities()); + authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + + SecurityContextHolder.getContext().setAuthentication(authentication); + filterChain.doFilter(request, response); + } + +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/security/JwtUser.java b/server/src/main/java/com/usatiuk/tjv/y/server/security/JwtUser.java new file mode 100644 index 0000000..2bea894 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/security/JwtUser.java @@ -0,0 +1,14 @@ +package com.usatiuk.tjv.y.server.security; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.User; + +import java.util.Collection; + +public class JwtUser extends User { + + public JwtUser(String uuid, String hash, + Collection authorities) { + super(uuid, hash, authorities); + } +} \ No newline at end of file diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/security/JwtUserDetailsService.java b/server/src/main/java/com/usatiuk/tjv/y/server/security/JwtUserDetailsService.java new file mode 100644 index 0000000..31baca5 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/security/JwtUserDetailsService.java @@ -0,0 +1,32 @@ +package com.usatiuk.tjv.y.server.security; + +import com.usatiuk.tjv.y.server.entity.Person; +import com.usatiuk.tjv.y.server.service.PersonService; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +@Service +public class JwtUserDetailsService implements UserDetailsService { + private final PersonService personService; + + public JwtUserDetailsService(PersonService personService) { + this.personService = personService; + } + + @Override + public UserDetails loadUserByUsername(String uuid) { + Optional person = personService.readById(uuid); + if (!person.isPresent()) throw new UsernameNotFoundException("User with UUID " + uuid + " not found"); + List roles = + Collections.singletonList(new SimpleGrantedAuthority(UserRoles.ROLE_USER.name())); + return new JwtUser(uuid, person.get().getPassword(), roles); + } + +} \ No newline at end of file diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/security/PasswordEncoderConfig.java b/server/src/main/java/com/usatiuk/tjv/y/server/security/PasswordEncoderConfig.java new file mode 100644 index 0000000..bcb27a1 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/security/PasswordEncoderConfig.java @@ -0,0 +1,14 @@ +package com.usatiuk.tjv.y.server.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class PasswordEncoderConfig { + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/security/UserRoles.java b/server/src/main/java/com/usatiuk/tjv/y/server/security/UserRoles.java new file mode 100644 index 0000000..6d6e837 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/security/UserRoles.java @@ -0,0 +1,5 @@ +package com.usatiuk.tjv.y.server.security; + +public enum UserRoles { + ROLE_USER, ROLE_ADMIN +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/security/WebSecurityConfig.java b/server/src/main/java/com/usatiuk/tjv/y/server/security/WebSecurityConfig.java new file mode 100644 index 0000000..a27c745 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/security/WebSecurityConfig.java @@ -0,0 +1,41 @@ +package com.usatiuk.tjv.y.server.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +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.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher; +import org.springframework.web.servlet.handler.HandlerMappingIntrospector; + +import static org.springframework.security.config.Customizer.withDefaults; + +@Configuration +@EnableWebSecurity +public class WebSecurityConfig { + private final JwtRequestFilter jwtRequestFilter; + + public WebSecurityConfig(JwtRequestFilter jwtRequestFilter) { + this.jwtRequestFilter = jwtRequestFilter; + } + + @Bean + MvcRequestMatcher.Builder mvc(HandlerMappingIntrospector introspector) { + return new MvcRequestMatcher.Builder(introspector); + } + + @Bean + public SecurityFilterChain configure(HttpSecurity http, MvcRequestMatcher.Builder mvc) throws Exception { + return http.cors(withDefaults()) + .csrf((csrf) -> csrf.disable()) + .authorizeHttpRequests((authorize) -> authorize + .requestMatchers(mvc.pattern("/person")).permitAll() + .anyRequest().hasAuthority(UserRoles.ROLE_USER.name())) + .sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class) + .build(); + } + +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/service/CrudService.java b/server/src/main/java/com/usatiuk/tjv/y/server/service/CrudService.java new file mode 100644 index 0000000..5aba0b8 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/service/CrudService.java @@ -0,0 +1,18 @@ +package com.usatiuk.tjv.y.server.service; + +import com.usatiuk.tjv.y.server.entity.EntityWithId; + +import java.io.Serializable; +import java.util.Optional; + +public interface CrudService, ID extends Serializable> { + T create(T e); + + Optional readById(ID id); + + Iterable readAll(); + + void update(ID id, T e); + + void deleteById(ID id); +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/service/CrudServiceImpl.java b/server/src/main/java/com/usatiuk/tjv/y/server/service/CrudServiceImpl.java new file mode 100644 index 0000000..4e5c861 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/service/CrudServiceImpl.java @@ -0,0 +1,40 @@ +package com.usatiuk.tjv.y.server.service; + +import com.usatiuk.tjv.y.server.entity.EntityWithId; +import org.springframework.data.repository.CrudRepository; + +import java.io.Serializable; +import java.util.Optional; + +public abstract class CrudServiceImpl, ID extends Serializable> + implements CrudService { + @Override + public T create(T e) { + if (e == null || (e.getId() != null && getRepository().existsById(e.getId()))) + throw new IllegalArgumentException(); + + return getRepository().save(e); + } + + @Override + public Optional readById(ID id) { + return getRepository().findById(id); + } + + @Override + public Iterable readAll() { + return getRepository().findAll(); + } + + @Override + public void update(ID id, T e) { + + } + + @Override + public void deleteById(ID id) { + getRepository().deleteById(id); + } + + protected abstract CrudRepository getRepository(); +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/service/PersonService.java b/server/src/main/java/com/usatiuk/tjv/y/server/service/PersonService.java new file mode 100644 index 0000000..fd401a4 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/service/PersonService.java @@ -0,0 +1,7 @@ +package com.usatiuk.tjv.y.server.service; + +import com.usatiuk.tjv.y.server.entity.Person; + +public interface PersonService extends CrudService { + Person signup(Person person); +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/service/PersonServiceImpl.java b/server/src/main/java/com/usatiuk/tjv/y/server/service/PersonServiceImpl.java new file mode 100644 index 0000000..05fe146 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/service/PersonServiceImpl.java @@ -0,0 +1,30 @@ +package com.usatiuk.tjv.y.server.service; + +import com.usatiuk.tjv.y.server.entity.Person; +import com.usatiuk.tjv.y.server.repository.PersonRepository; +import org.springframework.data.repository.CrudRepository; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +@Service +public class PersonServiceImpl extends CrudServiceImpl implements PersonService { + private final PersonRepository personRepository; + private final PasswordEncoder passwordEncoder; + + public PersonServiceImpl(PersonRepository personRepository, + PasswordEncoder passwordEncoder) { + this.personRepository = personRepository; + this.passwordEncoder = passwordEncoder; + } + + @Override + protected CrudRepository getRepository() { + return personRepository; + } + + @Override + public Person signup(Person person) { + person.setPassword(passwordEncoder.encode(person.getPassword())); + return create(person); + } +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/service/PersonTokenService.java b/server/src/main/java/com/usatiuk/tjv/y/server/service/PersonTokenService.java new file mode 100644 index 0000000..081bbb1 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/service/PersonTokenService.java @@ -0,0 +1,9 @@ +package com.usatiuk.tjv.y.server.service; + +import java.util.Optional; + +public interface PersonTokenService { + String generateToken(String personUuid); + + Optional parseToken(String token); +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/service/PersonTokenServiceImpl.java b/server/src/main/java/com/usatiuk/tjv/y/server/service/PersonTokenServiceImpl.java new file mode 100644 index 0000000..b1716ee --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/service/PersonTokenServiceImpl.java @@ -0,0 +1,49 @@ +package com.usatiuk.tjv.y.server.service; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.JwtException; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.io.Encoders; +import io.jsonwebtoken.security.Keys; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import javax.crypto.SecretKey; +import java.time.Duration; +import java.time.Instant; +import java.util.Date; +import java.util.Optional; + +@Service +public class PersonTokenServiceImpl implements PersonTokenService { + private static final Duration JWT_EXPIRY = Duration.ofMinutes(20); + + private final SecretKey key; + + public PersonTokenServiceImpl(@Value("${jwt.secret}") String secret) { + // FIXME: + this.key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(Encoders.BASE64.encode(secret.getBytes()))); + } + + @Override + public String generateToken(String personUuid) { + Instant now = Instant.now(); + return Jwts.builder() + .subject(personUuid) + .expiration(Date.from(now.plus(JWT_EXPIRY))) + .signWith(key, Jwts.SIG.HS512) + .compact(); + } + + @Override + public Optional parseToken(String token) { + try { + Claims claims = Jwts.parser().verifyWith(key).build().parseSignedClaims(token).getPayload(); + if (claims.getExpiration().before(new Date())) return Optional.empty(); + return Optional.of(claims.getSubject()); + } catch (JwtException ex) { + return Optional.empty(); + } + } +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/service/PostService.java b/server/src/main/java/com/usatiuk/tjv/y/server/service/PostService.java new file mode 100644 index 0000000..2e126c6 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/service/PostService.java @@ -0,0 +1,9 @@ +package com.usatiuk.tjv.y.server.service; + +import com.usatiuk.tjv.y.server.entity.Post; + +import java.util.Collection; + +public interface PostService extends CrudService { + Collection readByAuthorId(String authorUuid); +} diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/service/PostServiceImpl.java b/server/src/main/java/com/usatiuk/tjv/y/server/service/PostServiceImpl.java new file mode 100644 index 0000000..f75d4b5 --- /dev/null +++ b/server/src/main/java/com/usatiuk/tjv/y/server/service/PostServiceImpl.java @@ -0,0 +1,27 @@ +package com.usatiuk.tjv.y.server.service; + +import com.usatiuk.tjv.y.server.entity.Post; +import com.usatiuk.tjv.y.server.repository.PostRepository; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Service; + +import java.util.Collection; + +@Service +public class PostServiceImpl extends CrudServiceImpl implements PostService { + private final PostRepository postRepository; + + public PostServiceImpl(PostRepository postRepository) { + this.postRepository = postRepository; + } + + @Override + protected CrudRepository getRepository() { + return postRepository; + } + + @Override + public Collection readByAuthorId(String authorId) { + return postRepository.findByAuthorUuid(authorId); + } +} diff --git a/server/src/main/resources/application.properties b/server/src/main/resources/application.properties new file mode 100644 index 0000000..9f3f1b6 --- /dev/null +++ b/server/src/main/resources/application.properties @@ -0,0 +1 @@ +jwt.secret=JKLASJKLASJKLJHKLDFAHJKFDSHJKFJHKDSHJKFHJKSDFJHKSDJHKFJHKS98346783467899782345jkhgsdoigh938g \ No newline at end of file diff --git a/server/src/test/java/com/usatiuk/tjv/y/server/ServerApplicationTests.java b/server/src/test/java/com/usatiuk/tjv/y/server/ServerApplicationTests.java new file mode 100644 index 0000000..f9db275 --- /dev/null +++ b/server/src/test/java/com/usatiuk/tjv/y/server/ServerApplicationTests.java @@ -0,0 +1,13 @@ +package com.usatiuk.tjv.y.server; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ServerApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/server/src/test/java/com/usatiuk/tjv/y/server/controller/PersonControllerTest.java b/server/src/test/java/com/usatiuk/tjv/y/server/controller/PersonControllerTest.java new file mode 100644 index 0000000..3612457 --- /dev/null +++ b/server/src/test/java/com/usatiuk/tjv/y/server/controller/PersonControllerTest.java @@ -0,0 +1,38 @@ +package com.usatiuk.tjv.y.server.controller; + +import com.usatiuk.tjv.y.server.dto.PersonAuthResponse; +import com.usatiuk.tjv.y.server.dto.PersonSignupRequest; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.test.web.server.LocalServerPort; + + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class PersonControllerTest { + @LocalServerPort + private int port; + + @Autowired + private TestRestTemplate restTemplate; + + private String addr; + + @BeforeEach + void beforeEach() { + addr = "http://localhost:" + port; + } + + @Test + void shouldSignUp() { + var response = restTemplate.postForObject(addr + "/person", + new PersonSignupRequest("name", "full name", "pass"), PersonAuthResponse.class); + + Assertions.assertNotNull(response); + Assertions.assertEquals(response.username(), "name"); + Assertions.assertEquals(response.fullName(), "full name"); + } +} diff --git a/server/src/test/java/com/usatiuk/tjv/y/server/controller/PostControllerTest.java b/server/src/test/java/com/usatiuk/tjv/y/server/controller/PostControllerTest.java new file mode 100644 index 0000000..86a1738 --- /dev/null +++ b/server/src/test/java/com/usatiuk/tjv/y/server/controller/PostControllerTest.java @@ -0,0 +1,71 @@ +package com.usatiuk.tjv.y.server.controller; + +import com.usatiuk.tjv.y.server.dto.PersonAuthResponse; +import com.usatiuk.tjv.y.server.dto.PersonSignupRequest; +import com.usatiuk.tjv.y.server.dto.PostCreate; +import com.usatiuk.tjv.y.server.dto.PostTo; +import com.usatiuk.tjv.y.server.service.PostService; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; + +import java.util.Collections; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class PostControllerTest { + @LocalServerPort + private int port; + @Autowired + private TestRestTemplate restTemplate; + + @Autowired + private PostService postService; + + private String addr; + private PersonAuthResponse personAuth; + + @BeforeEach + void beforeEach() { + addr = "http://localhost:" + port; + + // Signup a user + var response = restTemplate.postForObject(addr + "/person", + new PersonSignupRequest("name", "full name", "pass"), PersonAuthResponse.class); + + personAuth = response; + } + + @Test + void shouldNotCreatePostWithoutAuth() { + var response = restTemplate.postForObject(addr + "/post", + new PostCreate("test text"), PostTo.class); + + Assertions.assertNull(response); + Assertions.assertEquals(postService.readAll().spliterator().estimateSize(), 0); + } + + @Test + void shouldCreatePost() { + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + personAuth.token()); + var entity = new HttpEntity<>(new PostCreate("test text"), headers); + + var response = restTemplate.exchange(addr + "/post", HttpMethod.POST, + entity, PostTo.class); + + PostTo reponsePostTo = response.getBody(); + + Assertions.assertNotNull(response); + Assertions.assertEquals(reponsePostTo.text(), "test text"); + Assertions.assertEquals(reponsePostTo.authorUuid(), personAuth.uuid()); + } +}