init
This commit is contained in:
commit
8583b57406
37
.gitignore
vendored
Normal file
37
.gitignore
vendored
Normal file
@ -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/
|
BIN
access-refresh-token-keys/access-token-private.key
Normal file
BIN
access-refresh-token-keys/access-token-private.key
Normal file
Binary file not shown.
BIN
access-refresh-token-keys/access-token-public.key
Normal file
BIN
access-refresh-token-keys/access-token-public.key
Normal file
Binary file not shown.
BIN
access-refresh-token-keys/refresh-token-private.key
Normal file
BIN
access-refresh-token-keys/refresh-token-private.key
Normal file
Binary file not shown.
BIN
access-refresh-token-keys/refresh-token-public.key
Normal file
BIN
access-refresh-token-keys/refresh-token-public.key
Normal file
Binary file not shown.
33
build.gradle
Normal file
33
build.gradle
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
plugins {
|
||||||
|
id 'java'
|
||||||
|
id 'org.springframework.boot' version '3.0.1'
|
||||||
|
id 'io.spring.dependency-management' version '1.1.0'
|
||||||
|
}
|
||||||
|
|
||||||
|
group = 'com.s477603'
|
||||||
|
version = '0.0.1-SNAPSHOT'
|
||||||
|
sourceCompatibility = '17'
|
||||||
|
|
||||||
|
configurations {
|
||||||
|
compileOnly {
|
||||||
|
extendsFrom annotationProcessor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||||
|
compileOnly 'org.projectlombok:lombok'
|
||||||
|
runtimeOnly 'com.mysql:mysql-connector-j'
|
||||||
|
annotationProcessor 'org.projectlombok:lombok'
|
||||||
|
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.named('test') {
|
||||||
|
useJUnitPlatform()
|
||||||
|
}
|
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
240
gradlew
vendored
Executable file
240
gradlew
vendored
Executable file
@ -0,0 +1,240 @@
|
|||||||
|
#!/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/master/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
|
||||||
|
|
||||||
|
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||||
|
|
||||||
|
APP_NAME="Gradle"
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
|
||||||
|
# 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"'
|
||||||
|
|
||||||
|
# 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
|
||||||
|
which java >/dev/null 2>&1 || 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
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
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
|
||||||
|
|
||||||
|
# Collect all arguments for the java command;
|
||||||
|
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||||
|
# shell script including quotes and variable substitutions, so put them in
|
||||||
|
# double quotes to make sure that they get re-expanded; and
|
||||||
|
# * put everything else in single quotes, so that it's not re-expanded.
|
||||||
|
|
||||||
|
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" "$@"
|
91
gradlew.bat
vendored
Normal file
91
gradlew.bat
vendored
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
@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=.
|
||||||
|
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
|
1
settings.gradle
Normal file
1
settings.gradle
Normal file
@ -0,0 +1 @@
|
|||||||
|
rootProject.name = 'movies'
|
31
src/main/java/com/s477603/movies/MoviesApplication.java
Normal file
31
src/main/java/com/s477603/movies/MoviesApplication.java
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
package com.s477603.movies;
|
||||||
|
|
||||||
|
import com.s477603.movies.document.Movie;
|
||||||
|
import com.s477603.movies.service.IMDBService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.boot.CommandLineRunner;
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
@Slf4j
|
||||||
|
public class MoviesApplication {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(MoviesApplication.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
PasswordEncoder passwordEncoder() {
|
||||||
|
return new BCryptPasswordEncoder();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
RestTemplate restTemplate() {
|
||||||
|
return new RestTemplate();
|
||||||
|
}
|
||||||
|
}
|
12
src/main/java/com/s477603/movies/document/AverageRate.java
Normal file
12
src/main/java/com/s477603/movies/document/AverageRate.java
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
package com.s477603.movies.document;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class AverageRate {
|
||||||
|
private Integer movieId;
|
||||||
|
private String title;
|
||||||
|
private String posterPath;
|
||||||
|
private Double rateAvg;
|
||||||
|
private Integer rateCount;
|
||||||
|
}
|
21
src/main/java/com/s477603/movies/document/Movie.java
Normal file
21
src/main/java/com/s477603/movies/document/Movie.java
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
package com.s477603.movies.document;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class Movie {
|
||||||
|
private String poster_path;
|
||||||
|
private Boolean adult;
|
||||||
|
private String overview;
|
||||||
|
private String release_date;
|
||||||
|
private Integer[] genre_ids;
|
||||||
|
private Integer id;
|
||||||
|
private String original_title;
|
||||||
|
private String original_language;
|
||||||
|
private String title;
|
||||||
|
private String backdrop_path;
|
||||||
|
private Number popularity;
|
||||||
|
private Integer vote_count;
|
||||||
|
private Boolean video;
|
||||||
|
private String vote_average;
|
||||||
|
}
|
@ -0,0 +1,11 @@
|
|||||||
|
package com.s477603.movies.document;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class MoviesCommonResponse {
|
||||||
|
private Integer page;
|
||||||
|
private Integer total_results;
|
||||||
|
private Integer total_pages;
|
||||||
|
private Movie[] results;
|
||||||
|
}
|
15
src/main/java/com/s477603/movies/document/RateRecord.java
Normal file
15
src/main/java/com/s477603/movies/document/RateRecord.java
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
package com.s477603.movies.document;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class RateRecord {
|
||||||
|
private String id;
|
||||||
|
private String userId;
|
||||||
|
private String username;
|
||||||
|
private Integer movieId;
|
||||||
|
private String title;
|
||||||
|
private String posterPath;
|
||||||
|
private Integer rate;
|
||||||
|
private String creationDate;
|
||||||
|
}
|
49
src/main/java/com/s477603/movies/document/User.java
Normal file
49
src/main/java/com/s477603/movies/document/User.java
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
package com.s477603.movies.document;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.NonNull;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Collections;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class User implements UserDetails {
|
||||||
|
private String id;
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||||
|
return Collections.EMPTY_LIST;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isAccountNonExpired() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isAccountNonLocked() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isCredentialsNonExpired() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isEnabled() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.s477603.movies.document;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class WatchlistRecord {
|
||||||
|
private String id;
|
||||||
|
private String userId;
|
||||||
|
private Integer movieId;
|
||||||
|
private String title;
|
||||||
|
private String posterPath;
|
||||||
|
private Boolean watched;
|
||||||
|
private Date creationDate;
|
||||||
|
}
|
11
src/main/java/com/s477603/movies/dto/LoginDTO.java
Normal file
11
src/main/java/com/s477603/movies/dto/LoginDTO.java
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package com.s477603.movies.dto;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public class LoginDTO {
|
||||||
|
private String username;
|
||||||
|
private String password;
|
||||||
|
}
|
12
src/main/java/com/s477603/movies/dto/RateDTO.java
Normal file
12
src/main/java/com/s477603/movies/dto/RateDTO.java
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
package com.s477603.movies.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class RateDTO {
|
||||||
|
private Integer movieId;
|
||||||
|
private Integer rate;
|
||||||
|
private String title;
|
||||||
|
private String posterPath;
|
||||||
|
|
||||||
|
}
|
11
src/main/java/com/s477603/movies/dto/SignupDTO.java
Normal file
11
src/main/java/com/s477603/movies/dto/SignupDTO.java
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package com.s477603.movies.dto;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public class SignupDTO {
|
||||||
|
private String username;
|
||||||
|
private String password;
|
||||||
|
}
|
16
src/main/java/com/s477603/movies/dto/TokenDTO.java
Normal file
16
src/main/java/com/s477603/movies/dto/TokenDTO.java
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
package com.s477603.movies.dto;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class TokenDTO {
|
||||||
|
private String userId;
|
||||||
|
private String accessToken;
|
||||||
|
private String refreshToken;
|
||||||
|
}
|
19
src/main/java/com/s477603/movies/dto/UserDTO.java
Normal file
19
src/main/java/com/s477603/movies/dto/UserDTO.java
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
package com.s477603.movies.dto;
|
||||||
|
|
||||||
|
import com.s477603.movies.document.User;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Builder
|
||||||
|
@Data
|
||||||
|
public class UserDTO {
|
||||||
|
private String id;
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
public static UserDTO from(User user) {
|
||||||
|
return UserDTO.builder()
|
||||||
|
.id(user.getId())
|
||||||
|
.username(user.getUsername())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
25
src/main/java/com/s477603/movies/dto/WatchlistRecordDTO.java
Normal file
25
src/main/java/com/s477603/movies/dto/WatchlistRecordDTO.java
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
package com.s477603.movies.dto;
|
||||||
|
|
||||||
|
import com.s477603.movies.document.Movie;
|
||||||
|
import com.s477603.movies.document.User;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Builder
|
||||||
|
@Data
|
||||||
|
public class WatchlistRecordDTO {
|
||||||
|
private Integer movieId;
|
||||||
|
private String title;
|
||||||
|
private String posterPath;
|
||||||
|
private String userId;
|
||||||
|
private Boolean watched;
|
||||||
|
|
||||||
|
public static WatchlistRecordDTO from(Movie movie, User user) {
|
||||||
|
return WatchlistRecordDTO.builder()
|
||||||
|
.movieId(movie.getId())
|
||||||
|
.title(movie.getTitle())
|
||||||
|
.posterPath(movie.getPoster_path())
|
||||||
|
.userId(user.getId())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,64 @@
|
|||||||
|
package com.s477603.movies.repository;
|
||||||
|
|
||||||
|
import com.s477603.movies.document.AverageRate;
|
||||||
|
import com.s477603.movies.document.RateRecord;
|
||||||
|
import com.s477603.movies.dto.RateDTO;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.jdbc.core.BeanPropertyRowMapper;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public class RatesRepository {
|
||||||
|
@Autowired
|
||||||
|
JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
public RateRecord getRateByMovieIdAndUserId(Integer movieId, String userId) {
|
||||||
|
return jdbcTemplate.queryForObject("SELECT user_id, movie_id, title, poster_path, username, rates.id, rate, creation_date FROM rates INNER JOIN users ON rates.user_id = users.id WHERE movie_id = ? AND user_id = ? LIMIT 1",
|
||||||
|
BeanPropertyRowMapper.newInstance(RateRecord.class), movieId, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public RateRecord save(String userId, RateDTO rateDTO) {
|
||||||
|
jdbcTemplate.update("INSERT INTO rates (user_id, movie_id, title, poster_path, rate) VALUES (?, ?, ?, ?, ?)",
|
||||||
|
userId, rateDTO.getMovieId(), rateDTO.getTitle(), rateDTO.getPosterPath(), rateDTO.getRate());
|
||||||
|
|
||||||
|
return getRateByMovieIdAndUserId(rateDTO.getMovieId(), userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public RateRecord update(String userId, RateDTO rateDTO) {
|
||||||
|
jdbcTemplate.update("UPDATE rates SET rate = ? WHERE user_id = ? AND movie_id = ?",
|
||||||
|
rateDTO.getRate(), userId, rateDTO.getMovieId());
|
||||||
|
|
||||||
|
return getRateByMovieIdAndUserId(rateDTO.getMovieId(), userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public RateRecord[] findAllByUserId(String userId) {
|
||||||
|
return jdbcTemplate.query("SELECT user_id, movie_id, title, poster_path, username, rates.id, rate, creation_date FROM rates INNER JOIN users ON rates.user_id = users.id WHERE user_id = ?",
|
||||||
|
BeanPropertyRowMapper.newInstance(RateRecord.class), userId).toArray(new RateRecord[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public RateRecord[] findAllByMovieId(Integer movieId) {
|
||||||
|
return jdbcTemplate.query("SELECT user_id, movie_id, title, poster_path, username, rates.id, rate, creation_date FROM rates INNER JOIN users ON rates.user_id = users.id WHERE movie_id = ?",
|
||||||
|
BeanPropertyRowMapper.newInstance(RateRecord.class), movieId).toArray(new RateRecord[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public RateRecord[] getAll() {
|
||||||
|
return jdbcTemplate.query("SELECT user_id, movie_id, title, poster_path, username, rates.id, rate, creation_date FROM rates INNER JOIN users ON rates.user_id = users.id",
|
||||||
|
BeanPropertyRowMapper.newInstance(RateRecord.class)).toArray(new RateRecord[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public AverageRate[] getMoviesWithAverageRate() {
|
||||||
|
return jdbcTemplate.query("SELECT movie_id, title, poster_path, AVG(rate) AS `rate_avg`, COUNT(rate) AS `rate_count` FROM rates GROUP BY movie_id, title, poster_path ORDER BY `rate_avg` DESC",
|
||||||
|
BeanPropertyRowMapper.newInstance(AverageRate.class)).toArray(new AverageRate[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public AverageRate getMovieWithAverageRate(Integer movieId) {
|
||||||
|
return jdbcTemplate.queryForObject("SELECT movie_id, title, poster_path, AVG(rate) AS `rate_avg`, COUNT(rate) AS `rate_count` FROM rates WHERE movie_id = ? GROUP BY movie_id, title, poster_path LIMIT 1",
|
||||||
|
BeanPropertyRowMapper.newInstance(AverageRate.class), movieId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean exists(String userId, Integer movieId) {
|
||||||
|
return jdbcTemplate.queryForObject("SELECT EXISTS(SELECT 1 FROM rates WHERE user_id = ? AND movie_id = ?)",
|
||||||
|
Boolean.class, userId, movieId);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.s477603.movies.repository;
|
||||||
|
|
||||||
|
import com.s477603.movies.document.User;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.jdbc.core.BeanPropertyRowMapper;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public class UserRepository {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
public void save(User user) {
|
||||||
|
jdbcTemplate.update("INSERT INTO users (username, password, id) VALUES (?, ?, ?)",
|
||||||
|
user.getUsername(), user.getPassword(), user.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<User> findByUsername(String username) {
|
||||||
|
return Optional.ofNullable(jdbcTemplate.queryForObject("SELECT * FROM users WHERE username = ?",
|
||||||
|
BeanPropertyRowMapper.newInstance(User.class), username));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<User> findById(String id) {
|
||||||
|
return Optional.ofNullable(jdbcTemplate.queryForObject("SELECT * FROM users WHERE id = ?",
|
||||||
|
BeanPropertyRowMapper.newInstance(User.class), id));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean existsByUsername(String username) {
|
||||||
|
return jdbcTemplate.queryForObject("SELECT EXISTS(SELECT 1 FROM users WHERE username = ?)",
|
||||||
|
Boolean.class, username);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,46 @@
|
|||||||
|
package com.s477603.movies.repository;
|
||||||
|
|
||||||
|
import com.s477603.movies.document.Movie;
|
||||||
|
import com.s477603.movies.document.WatchlistRecord;
|
||||||
|
import com.s477603.movies.dto.WatchlistRecordDTO;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.jdbc.core.BeanPropertyRowMapper;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public class WatchlistRepository {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
public void save(WatchlistRecordDTO watchlistRecordDTO) {
|
||||||
|
jdbcTemplate.update("INSERT INTO watchlist (user_id, movie_id, title, poster_path) VALUES (?, ?, ?, ?)",
|
||||||
|
watchlistRecordDTO.getUserId(), watchlistRecordDTO.getMovieId(), watchlistRecordDTO.getTitle(), watchlistRecordDTO.getPosterPath());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete(WatchlistRecordDTO watchlistRecordDTO) {
|
||||||
|
jdbcTemplate.update("DELETE FROM watchlist WHERE movie_id = ? AND user_id = ?",
|
||||||
|
watchlistRecordDTO.getMovieId(), watchlistRecordDTO.getUserId());
|
||||||
|
}
|
||||||
|
|
||||||
|
public WatchlistRecord[] findAllByUserId(String userId) {
|
||||||
|
return jdbcTemplate.query("SELECT * FROM watchlist WHERE user_id = ?",
|
||||||
|
BeanPropertyRowMapper.newInstance(WatchlistRecord.class), userId).toArray(new WatchlistRecord[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean exists(WatchlistRecordDTO watchlistRecordDTO) {
|
||||||
|
return jdbcTemplate.queryForObject("SELECT EXISTS(SELECT 1 FROM watchlist WHERE user_id = ? AND movie_id = ?)",
|
||||||
|
Boolean.class, watchlistRecordDTO.getUserId(), watchlistRecordDTO.getMovieId());
|
||||||
|
}
|
||||||
|
|
||||||
|
public WatchlistRecord toggleWatched(WatchlistRecordDTO watchlistRecordDTO) {
|
||||||
|
jdbcTemplate.update("UPDATE watchlist SET watched = NOT watched WHERE user_id = ? AND movie_id = ?",
|
||||||
|
watchlistRecordDTO.getUserId(), watchlistRecordDTO.getMovieId());
|
||||||
|
|
||||||
|
return jdbcTemplate.queryForObject("SELECT * FROM watchlist WHERE user_id = ? AND movie_id = ?",
|
||||||
|
BeanPropertyRowMapper.newInstance(WatchlistRecord.class), watchlistRecordDTO.getUserId(), watchlistRecordDTO.getMovieId());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.s477603.movies.security;
|
||||||
|
|
||||||
|
import com.s477603.movies.document.User;
|
||||||
|
import org.springframework.core.convert.converter.Converter;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.oauth2.jwt.Jwt;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class JwtToUserConverter implements Converter<Jwt, UsernamePasswordAuthenticationToken> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public UsernamePasswordAuthenticationToken convert(Jwt jwt) {
|
||||||
|
User user = new User();
|
||||||
|
user.setId(jwt.getSubject());
|
||||||
|
|
||||||
|
return new UsernamePasswordAuthenticationToken(user, jwt, Collections.EMPTY_LIST);
|
||||||
|
}
|
||||||
|
}
|
127
src/main/java/com/s477603/movies/security/KeyUtils.java
Normal file
127
src/main/java/com/s477603/movies/security/KeyUtils.java
Normal file
@ -0,0 +1,127 @@
|
|||||||
|
package com.s477603.movies.security;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.core.env.Environment;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.security.*;
|
||||||
|
import java.security.interfaces.RSAPrivateKey;
|
||||||
|
import java.security.interfaces.RSAPublicKey;
|
||||||
|
import java.security.spec.EncodedKeySpec;
|
||||||
|
import java.security.spec.InvalidKeySpecException;
|
||||||
|
import java.security.spec.PKCS8EncodedKeySpec;
|
||||||
|
import java.security.spec.X509EncodedKeySpec;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@Slf4j
|
||||||
|
public class KeyUtils {
|
||||||
|
@Autowired
|
||||||
|
Environment environment;
|
||||||
|
|
||||||
|
@Value("${access-token.private}")
|
||||||
|
private String accessTokenPrivateKeyPath;
|
||||||
|
|
||||||
|
@Value("${access-token.public}")
|
||||||
|
private String accessTokenPublicKeyPath;
|
||||||
|
|
||||||
|
@Value("${refresh-token.private}")
|
||||||
|
private String refreshTokenPrivateKeyPath;
|
||||||
|
|
||||||
|
@Value("${refresh-token.public}")
|
||||||
|
private String refreshTokenPublicKeyPath;
|
||||||
|
|
||||||
|
private KeyPair _accessTokenKeyPair;
|
||||||
|
private KeyPair _refreshTokenKeyPair;
|
||||||
|
|
||||||
|
private KeyPair getAccessTokenKeyPair() {
|
||||||
|
if (Objects.isNull(_accessTokenKeyPair)) {
|
||||||
|
_accessTokenKeyPair = getKeyPair(accessTokenPublicKeyPath, accessTokenPrivateKeyPath);
|
||||||
|
}
|
||||||
|
return _accessTokenKeyPair;
|
||||||
|
}
|
||||||
|
|
||||||
|
private KeyPair getRefreshTokenKeyPair() {
|
||||||
|
if (Objects.isNull(_refreshTokenKeyPair)) {
|
||||||
|
_refreshTokenKeyPair = getKeyPair(refreshTokenPublicKeyPath, refreshTokenPrivateKeyPath);
|
||||||
|
}
|
||||||
|
return _refreshTokenKeyPair;
|
||||||
|
}
|
||||||
|
|
||||||
|
private KeyPair getKeyPair(String publicKeyPath, String privateKeyPath) {
|
||||||
|
KeyPair keyPair;
|
||||||
|
|
||||||
|
File publicKeyFile = new File(publicKeyPath);
|
||||||
|
File privateKeyFile = new File(privateKeyPath);
|
||||||
|
|
||||||
|
if (publicKeyFile.exists() && privateKeyFile.exists()) {
|
||||||
|
log.info("loading keys from file: {}, {}", publicKeyPath, privateKeyPath);
|
||||||
|
try {
|
||||||
|
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||||
|
|
||||||
|
byte[] publicKeyBytes = Files.readAllBytes(publicKeyFile.toPath());
|
||||||
|
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
|
||||||
|
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
|
||||||
|
|
||||||
|
byte[] privateKeyBytes = Files.readAllBytes(privateKeyFile.toPath());
|
||||||
|
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
|
||||||
|
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
|
||||||
|
|
||||||
|
keyPair = new KeyPair(publicKey, privateKey);
|
||||||
|
return keyPair;
|
||||||
|
} catch (NoSuchAlgorithmException | IOException | InvalidKeySpecException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (Arrays.stream(environment.getActiveProfiles()).anyMatch(s -> s.equals("prod"))) {
|
||||||
|
throw new RuntimeException("public and private keys don't exist");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
File directory = new File("access-refresh-token-keys");
|
||||||
|
if (!directory.exists()) {
|
||||||
|
directory.mkdirs();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
log.info("Generating new public and private keys: {}, {}", publicKeyPath, privateKeyPath);
|
||||||
|
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
|
||||||
|
keyPairGenerator.initialize(2048);
|
||||||
|
keyPair = keyPairGenerator.generateKeyPair();
|
||||||
|
try (FileOutputStream fos = new FileOutputStream(publicKeyPath)) {
|
||||||
|
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyPair.getPublic().getEncoded());
|
||||||
|
fos.write(keySpec.getEncoded());
|
||||||
|
}
|
||||||
|
|
||||||
|
try (FileOutputStream fos = new FileOutputStream(privateKeyPath)) {
|
||||||
|
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyPair.getPrivate().getEncoded());
|
||||||
|
fos.write(keySpec.getEncoded());
|
||||||
|
}
|
||||||
|
} catch (NoSuchAlgorithmException | IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
return keyPair;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public RSAPublicKey getAccessTokenPublicKey() {
|
||||||
|
return (RSAPublicKey) getAccessTokenKeyPair().getPublic();
|
||||||
|
};
|
||||||
|
public RSAPrivateKey getAccessTokenPrivateKey() {
|
||||||
|
return (RSAPrivateKey) getAccessTokenKeyPair().getPrivate();
|
||||||
|
};
|
||||||
|
public RSAPublicKey getRefreshTokenPublicKey() {
|
||||||
|
return (RSAPublicKey) getRefreshTokenKeyPair().getPublic();
|
||||||
|
};
|
||||||
|
public RSAPrivateKey getRefreshTokenPrivateKey() {
|
||||||
|
return (RSAPrivateKey) getRefreshTokenKeyPair().getPrivate();
|
||||||
|
};
|
||||||
|
}
|
@ -0,0 +1,87 @@
|
|||||||
|
package com.s477603.movies.security;
|
||||||
|
|
||||||
|
import com.s477603.movies.document.User;
|
||||||
|
import com.s477603.movies.dto.TokenDTO;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.security.authentication.BadCredentialsException;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.oauth2.jwt.Jwt;
|
||||||
|
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
|
||||||
|
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
||||||
|
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.text.MessageFormat;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class TokenGenerator {
|
||||||
|
@Autowired
|
||||||
|
JwtEncoder accessTokenEncoder;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
@Qualifier("jwtRefreshTokenEncoder")
|
||||||
|
JwtEncoder refreshTokenEncoder;
|
||||||
|
|
||||||
|
private String createAccessToken(Authentication authentication) {
|
||||||
|
User user = (User) authentication.getPrincipal();
|
||||||
|
Instant now = Instant.now();
|
||||||
|
|
||||||
|
JwtClaimsSet claimsSet = JwtClaimsSet.builder()
|
||||||
|
.issuer("myApp")
|
||||||
|
.issuedAt(now)
|
||||||
|
.expiresAt(now.plus(2, ChronoUnit.HOURS))
|
||||||
|
.subject(user.getId())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
return accessTokenEncoder.encode(JwtEncoderParameters.from(claimsSet)).getTokenValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String createRefreshToken(Authentication authentication) {
|
||||||
|
User user = (User) authentication.getPrincipal();
|
||||||
|
Instant now = Instant.now();
|
||||||
|
|
||||||
|
JwtClaimsSet claimsSet = JwtClaimsSet.builder()
|
||||||
|
.issuer("myApp")
|
||||||
|
.issuedAt(now)
|
||||||
|
.expiresAt(now.plus(30, ChronoUnit.DAYS))
|
||||||
|
.subject(user.getId())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
return refreshTokenEncoder.encode(JwtEncoderParameters.from(claimsSet)).getTokenValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public TokenDTO createToken(Authentication authentication) {
|
||||||
|
if (!(authentication.getPrincipal() instanceof User user)) {
|
||||||
|
throw new BadCredentialsException(
|
||||||
|
MessageFormat.format("principal {0} is not of User type", authentication.getPrincipal().getClass())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
TokenDTO tokenDTO = new TokenDTO();
|
||||||
|
tokenDTO.setUserId(user.getId());
|
||||||
|
tokenDTO.setAccessToken(createAccessToken(authentication));
|
||||||
|
|
||||||
|
String refreshToken;
|
||||||
|
if (authentication.getCredentials() instanceof Jwt jwt) {
|
||||||
|
Instant now = Instant.now();
|
||||||
|
Instant expiresAt = jwt.getExpiresAt();
|
||||||
|
Duration duration = Duration.between(now, expiresAt);
|
||||||
|
long daysUntilExpired = duration.toDays();
|
||||||
|
if (daysUntilExpired < 7) {
|
||||||
|
refreshToken = createRefreshToken(authentication);
|
||||||
|
} else {
|
||||||
|
refreshToken = jwt.getTokenValue();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
refreshToken = createRefreshToken(authentication);
|
||||||
|
}
|
||||||
|
tokenDTO.setRefreshToken(refreshToken);
|
||||||
|
|
||||||
|
return tokenDTO;
|
||||||
|
}
|
||||||
|
}
|
127
src/main/java/com/s477603/movies/security/WebSecurity.java
Normal file
127
src/main/java/com/s477603/movies/security/WebSecurity.java
Normal file
@ -0,0 +1,127 @@
|
|||||||
|
package com.s477603.movies.security;
|
||||||
|
|
||||||
|
import com.nimbusds.jose.jwk.JWK;
|
||||||
|
import com.nimbusds.jose.jwk.JWKSet;
|
||||||
|
import com.nimbusds.jose.jwk.RSAKey;
|
||||||
|
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
|
||||||
|
import com.nimbusds.jose.jwk.source.JWKSource;
|
||||||
|
import com.nimbusds.jose.proc.SecurityContext;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.Primary;
|
||||||
|
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||||
|
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||||
|
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
||||||
|
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
|
||||||
|
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
|
||||||
|
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider;
|
||||||
|
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint;
|
||||||
|
import org.springframework.security.oauth2.server.resource.web.access.BearerTokenAccessDeniedHandler;
|
||||||
|
import org.springframework.security.provisioning.UserDetailsManager;
|
||||||
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
import org.springframework.web.cors.CorsConfiguration;
|
||||||
|
import org.springframework.web.cors.CorsConfigurationSource;
|
||||||
|
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||||
|
@Slf4j
|
||||||
|
public class WebSecurity {
|
||||||
|
@Autowired
|
||||||
|
JwtToUserConverter jwtToUserConverter;
|
||||||
|
@Autowired
|
||||||
|
KeyUtils keyUtils;
|
||||||
|
@Autowired
|
||||||
|
PasswordEncoder passwordEncoder;
|
||||||
|
@Autowired
|
||||||
|
UserDetailsManager userDetailsManager;
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||||
|
http
|
||||||
|
.authorizeHttpRequests((authorize) -> authorize
|
||||||
|
.requestMatchers("/api/auth/*").permitAll()
|
||||||
|
.requestMatchers("/api/movies/trending").permitAll()
|
||||||
|
.anyRequest().authenticated()
|
||||||
|
)
|
||||||
|
.csrf().disable()
|
||||||
|
.cors().configurationSource(request -> {
|
||||||
|
CorsConfiguration cors = new CorsConfiguration();
|
||||||
|
cors.setAllowedOrigins(List.of("http://localhost:3000"));
|
||||||
|
cors.setAllowedMethods(List.of("GET","POST", "PUT", "DELETE", "OPTIONS"));
|
||||||
|
cors.setAllowedHeaders(List.of("*"));
|
||||||
|
return cors;
|
||||||
|
}).and()
|
||||||
|
.httpBasic().disable()
|
||||||
|
.oauth2ResourceServer((oauth2) ->
|
||||||
|
oauth2.jwt((jwt) -> jwt.jwtAuthenticationConverter(jwtToUserConverter))
|
||||||
|
)
|
||||||
|
.sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||||
|
.exceptionHandling((exceptions) -> exceptions
|
||||||
|
.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
|
||||||
|
.accessDeniedHandler(new BearerTokenAccessDeniedHandler())
|
||||||
|
);
|
||||||
|
return http.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@Primary
|
||||||
|
JwtDecoder jwtAccessTokenDecoder() {
|
||||||
|
return NimbusJwtDecoder.withPublicKey(keyUtils.getAccessTokenPublicKey()).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@Primary
|
||||||
|
JwtEncoder jwtAccessTokenEncoder() {
|
||||||
|
JWK jwk = new RSAKey
|
||||||
|
.Builder(keyUtils.getAccessTokenPublicKey())
|
||||||
|
.privateKey(keyUtils.getAccessTokenPrivateKey())
|
||||||
|
.build();
|
||||||
|
JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk));
|
||||||
|
return new NimbusJwtEncoder(jwks);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@Qualifier("jwtRefreshTokenDecoder")
|
||||||
|
JwtDecoder jwtRefreshTokenDecoder() {
|
||||||
|
return NimbusJwtDecoder.withPublicKey(keyUtils.getRefreshTokenPublicKey()).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@Qualifier("jwtRefreshTokenEncoder")
|
||||||
|
JwtEncoder jwtRefreshTokenEncoder() {
|
||||||
|
JWK jwk = new RSAKey
|
||||||
|
.Builder(keyUtils.getRefreshTokenPublicKey())
|
||||||
|
.privateKey(keyUtils.getRefreshTokenPrivateKey())
|
||||||
|
.build();
|
||||||
|
JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk));
|
||||||
|
return new NimbusJwtEncoder(jwks);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@Qualifier("jwtRefreshTokenAuthProvider")
|
||||||
|
JwtAuthenticationProvider jwtRefreshTokenAuthProvider() {
|
||||||
|
JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwtRefreshTokenDecoder());
|
||||||
|
provider.setJwtAuthenticationConverter(jwtToUserConverter);
|
||||||
|
return provider;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
DaoAuthenticationProvider daoAuthenticationProvider() {
|
||||||
|
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
|
||||||
|
provider.setPasswordEncoder(passwordEncoder);
|
||||||
|
provider.setUserDetailsService(userDetailsManager);
|
||||||
|
return provider;
|
||||||
|
}
|
||||||
|
}
|
50
src/main/java/com/s477603/movies/service/IMDBService.java
Normal file
50
src/main/java/com/s477603/movies/service/IMDBService.java
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
package com.s477603.movies.service;
|
||||||
|
|
||||||
|
import com.s477603.movies.document.Movie;
|
||||||
|
import com.s477603.movies.document.MoviesCommonResponse;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public final class IMDBService {
|
||||||
|
@Value("${tmdb.api-key}")
|
||||||
|
private String apiKey;
|
||||||
|
private final String BASE_URL = "https://api.themoviedb.org/3";
|
||||||
|
|
||||||
|
private String createUrl(String path) {
|
||||||
|
String apiSuffix;
|
||||||
|
if (path.contains("?")) {
|
||||||
|
apiSuffix = "&api_key=" + apiKey;
|
||||||
|
} else {
|
||||||
|
apiSuffix = "?api_key=" + apiKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
return BASE_URL + path + apiSuffix + "&language=pl-PL";
|
||||||
|
}
|
||||||
|
private final RestTemplate restTemplate;
|
||||||
|
public IMDBService(RestTemplate restTemplate) {
|
||||||
|
this.restTemplate = restTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MoviesCommonResponse getTrending(int page) {
|
||||||
|
ResponseEntity<MoviesCommonResponse> exchange = restTemplate.exchange(createUrl("/movie/popular?page=%d".formatted(page)), HttpMethod.GET, null, MoviesCommonResponse.class);
|
||||||
|
return exchange.getBody();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Movie getMovieById(int id) {
|
||||||
|
ResponseEntity<Movie> exchange = restTemplate.exchange(createUrl("/movie/%d".formatted(id)), HttpMethod.GET, null, Movie.class);
|
||||||
|
|
||||||
|
if (!exchange.getStatusCode().is2xxSuccessful()) {
|
||||||
|
throw new RuntimeException("Movie not found");
|
||||||
|
}
|
||||||
|
return exchange.getBody();
|
||||||
|
}
|
||||||
|
|
||||||
|
public MoviesCommonResponse searchMovies(String query, int page) {
|
||||||
|
ResponseEntity<MoviesCommonResponse> exchange = restTemplate.exchange(createUrl("/search/movie?query=%s&page=%o".formatted(query, page)), HttpMethod.GET, null, MoviesCommonResponse.class);
|
||||||
|
return exchange.getBody();
|
||||||
|
}
|
||||||
|
}
|
55
src/main/java/com/s477603/movies/service/UserManager.java
Normal file
55
src/main/java/com/s477603/movies/service/UserManager.java
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
package com.s477603.movies.service;
|
||||||
|
|
||||||
|
import com.s477603.movies.repository.UserRepository;
|
||||||
|
import com.s477603.movies.document.User;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.security.provisioning.UserDetailsManager;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.text.MessageFormat;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class UserManager implements UserDetailsManager {
|
||||||
|
@Autowired
|
||||||
|
UserRepository userRepository;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void createUser(UserDetails user) {
|
||||||
|
((User) user).setPassword(passwordEncoder.encode(user.getPassword()));
|
||||||
|
((User) user).setId(UUID.randomUUID().toString());
|
||||||
|
userRepository.save((User) user);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void updateUser(UserDetails user) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void deleteUser(String username) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void changePassword(String oldPassword, String newPassword) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean userExists(String username) {
|
||||||
|
return userRepository.existsByUsername(username);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||||
|
return userRepository.findByUsername(username)
|
||||||
|
.orElseThrow(() -> new UsernameNotFoundException(MessageFormat.format("username {0} not found", username)));
|
||||||
|
}
|
||||||
|
}
|
61
src/main/java/com/s477603/movies/web/AuthController.java
Normal file
61
src/main/java/com/s477603/movies/web/AuthController.java
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
package com.s477603.movies.web;
|
||||||
|
|
||||||
|
import com.s477603.movies.document.User;
|
||||||
|
import com.s477603.movies.dto.LoginDTO;
|
||||||
|
import com.s477603.movies.dto.SignupDTO;
|
||||||
|
import com.s477603.movies.dto.TokenDTO;
|
||||||
|
import com.s477603.movies.security.TokenGenerator;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthenticationToken;
|
||||||
|
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider;
|
||||||
|
import org.springframework.security.provisioning.UserDetailsManager;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.text.MessageFormat;
|
||||||
|
import java.util.Collections;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/auth")
|
||||||
|
public class AuthController {
|
||||||
|
@Autowired
|
||||||
|
UserDetailsManager userDetailsManager;
|
||||||
|
@Autowired
|
||||||
|
TokenGenerator tokenGenerator;
|
||||||
|
@Autowired
|
||||||
|
DaoAuthenticationProvider daoAuthenticationProvider;
|
||||||
|
@Autowired
|
||||||
|
@Qualifier("jwtRefreshTokenAuthProvider")
|
||||||
|
JwtAuthenticationProvider jwtRefreshTokenAuthProvider;
|
||||||
|
|
||||||
|
@PostMapping("/register")
|
||||||
|
public ResponseEntity register(@RequestBody SignupDTO signupDTO) {
|
||||||
|
User user = new User(signupDTO.getUsername(), signupDTO.getPassword());
|
||||||
|
if (userDetailsManager.userExists(user.getUsername())) {
|
||||||
|
return ResponseEntity.badRequest().body("Username already exists");
|
||||||
|
}
|
||||||
|
userDetailsManager.createUser(user);
|
||||||
|
|
||||||
|
Authentication authentication = UsernamePasswordAuthenticationToken.authenticated(user, signupDTO.getPassword(), Collections.EMPTY_LIST);
|
||||||
|
|
||||||
|
return ResponseEntity.ok(tokenGenerator.createToken(authentication));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/login")
|
||||||
|
public ResponseEntity login(@RequestBody LoginDTO loginDTO) {
|
||||||
|
Authentication authentication = daoAuthenticationProvider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated((loginDTO.getUsername()), loginDTO.getPassword()));
|
||||||
|
|
||||||
|
return ResponseEntity.ok(tokenGenerator.createToken(authentication));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/token")
|
||||||
|
public ResponseEntity token(@RequestBody TokenDTO tokenDTO) {
|
||||||
|
Authentication authentication = jwtRefreshTokenAuthProvider.authenticate(new BearerTokenAuthenticationToken(tokenDTO.getRefreshToken()));
|
||||||
|
|
||||||
|
return ResponseEntity.ok(tokenGenerator.createToken(authentication));
|
||||||
|
}
|
||||||
|
}
|
63
src/main/java/com/s477603/movies/web/MoviesController.java
Normal file
63
src/main/java/com/s477603/movies/web/MoviesController.java
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
package com.s477603.movies.web;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.s477603.movies.document.Movie;
|
||||||
|
import com.s477603.movies.document.MoviesCommonResponse;
|
||||||
|
import com.s477603.movies.service.IMDBService;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/movies")
|
||||||
|
public class MoviesController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
IMDBService imdbService;
|
||||||
|
|
||||||
|
@GetMapping("/trending")
|
||||||
|
public ResponseEntity trending(@RequestParam(name = "page", defaultValue = "1") int page) {
|
||||||
|
MoviesCommonResponse trending = imdbService.getTrending(page);
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
final HttpHeaders httpHeaders = new HttpHeaders();
|
||||||
|
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
|
||||||
|
try {
|
||||||
|
return new ResponseEntity<String>(mapper.writeValueAsString(trending.getResults()), httpHeaders, HttpStatus.OK);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/search")
|
||||||
|
public ResponseEntity search(@RequestParam(name = "query") String query, @RequestParam(name = "page", defaultValue = "1") int page) {
|
||||||
|
MoviesCommonResponse search = imdbService.searchMovies(query, page);
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
final HttpHeaders httpHeaders = new HttpHeaders();
|
||||||
|
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
|
||||||
|
try {
|
||||||
|
return new ResponseEntity<String>(mapper.writeValueAsString(search.getResults()), httpHeaders, HttpStatus.OK);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/movie/{id}")
|
||||||
|
public ResponseEntity movie(@PathVariable int id) {
|
||||||
|
Movie movie = imdbService.getMovieById(id);
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
final HttpHeaders httpHeaders = new HttpHeaders();
|
||||||
|
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
|
||||||
|
try {
|
||||||
|
return new ResponseEntity<String>(mapper.writeValueAsString(movie), httpHeaders, HttpStatus.OK);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
51
src/main/java/com/s477603/movies/web/RatesController.java
Normal file
51
src/main/java/com/s477603/movies/web/RatesController.java
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
package com.s477603.movies.web;
|
||||||
|
|
||||||
|
import com.s477603.movies.document.User;
|
||||||
|
import com.s477603.movies.dto.RateDTO;
|
||||||
|
import com.s477603.movies.repository.RatesRepository;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/rates")
|
||||||
|
public class RatesController {
|
||||||
|
@Autowired
|
||||||
|
RatesRepository ratesRepository;
|
||||||
|
|
||||||
|
|
||||||
|
@GetMapping("/all")
|
||||||
|
public ResponseEntity getAll() {
|
||||||
|
return ResponseEntity.ok(ratesRepository.getAll());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/save")
|
||||||
|
public ResponseEntity save(@AuthenticationPrincipal User user, @RequestBody RateDTO rateDTO) {
|
||||||
|
if (ratesRepository.exists(user.getId(), rateDTO.getMovieId())) {
|
||||||
|
return ResponseEntity.ok(ratesRepository.update(user.getId(), rateDTO));
|
||||||
|
} else {
|
||||||
|
return ResponseEntity.ok(ratesRepository.save(user.getId(), rateDTO));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/user/{userId}")
|
||||||
|
public ResponseEntity getAllByUserId(@PathVariable String userId) {
|
||||||
|
return ResponseEntity.ok(ratesRepository.findAllByUserId(userId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/movie/{movieId}")
|
||||||
|
public ResponseEntity getAllByMovieId(@PathVariable Integer movieId) {
|
||||||
|
return ResponseEntity.ok(ratesRepository.findAllByMovieId(movieId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/average")
|
||||||
|
public ResponseEntity getMoviesWithAverageRate() {
|
||||||
|
return ResponseEntity.ok(ratesRepository.getMoviesWithAverageRate());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/average/{movieId}")
|
||||||
|
public ResponseEntity getAverageRateByMovieId(@PathVariable Integer movieId) {
|
||||||
|
return ResponseEntity.ok(ratesRepository.getMovieWithAverageRate(movieId));
|
||||||
|
}
|
||||||
|
}
|
26
src/main/java/com/s477603/movies/web/UserController.java
Normal file
26
src/main/java/com/s477603/movies/web/UserController.java
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
package com.s477603.movies.web;
|
||||||
|
|
||||||
|
import com.s477603.movies.document.User;
|
||||||
|
import com.s477603.movies.dto.UserDTO;
|
||||||
|
import com.s477603.movies.repository.UserRepository;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/users")
|
||||||
|
public class UserController {
|
||||||
|
@Autowired
|
||||||
|
UserRepository userRepository;
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
@PreAuthorize("#user.id == #id")
|
||||||
|
public ResponseEntity user(@AuthenticationPrincipal User user, @PathVariable String id) {
|
||||||
|
return ResponseEntity.ok(UserDTO.from(userRepository.findById(id).orElseThrow()));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,55 @@
|
|||||||
|
package com.s477603.movies.web;
|
||||||
|
|
||||||
|
import com.s477603.movies.document.User;
|
||||||
|
import com.s477603.movies.dto.WatchlistRecordDTO;
|
||||||
|
import com.s477603.movies.repository.WatchlistRepository;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/watchlist")
|
||||||
|
public class WatchlistController {
|
||||||
|
@Autowired
|
||||||
|
WatchlistRepository watchlistRepository;
|
||||||
|
|
||||||
|
@PostMapping("/add")
|
||||||
|
@PreAuthorize("#watchlistRecordDTO.userId == #user.id")
|
||||||
|
public ResponseEntity add(@AuthenticationPrincipal User user, @RequestBody WatchlistRecordDTO watchlistRecordDTO) {
|
||||||
|
if (!watchlistRepository.exists(watchlistRecordDTO)) {
|
||||||
|
watchlistRepository.save(watchlistRecordDTO);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResponseEntity.ok().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/remove")
|
||||||
|
@PreAuthorize("#watchlistRecordDTO.userId == #user.id")
|
||||||
|
public ResponseEntity remove(@AuthenticationPrincipal User user, @RequestBody WatchlistRecordDTO watchlistRecordDTO) {
|
||||||
|
watchlistRepository.delete(watchlistRecordDTO);
|
||||||
|
|
||||||
|
return ResponseEntity.ok().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/all/{userId}")
|
||||||
|
public ResponseEntity all(@PathVariable String userId) {
|
||||||
|
return ResponseEntity.ok(watchlistRepository.findAllByUserId(userId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/watched")
|
||||||
|
@PreAuthorize("#watchlistRecordDTO.userId == #user.id")
|
||||||
|
public ResponseEntity watched(@AuthenticationPrincipal User user, @RequestBody WatchlistRecordDTO watchlistRecordDTO) {
|
||||||
|
return ResponseEntity.ok(watchlistRepository.toggleWatched(watchlistRecordDTO));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Plan na jutro:
|
||||||
|
// - zmiana DTO na klasy z documents
|
||||||
|
// - controller na Rating
|
||||||
|
// - dodawanie oceny
|
||||||
|
// - zmiana oceny
|
||||||
|
// - lista filmów wg ocen, liczba ocen i śrenia
|
||||||
|
// - detal usera z watchlistą i jego ocenami
|
||||||
|
// -zacząć frontend, zacząć od oauth2, zacząć bez spektakularnego UI
|
||||||
|
}
|
5
src/main/resources/application-dev.yml
Normal file
5
src/main/resources/application-dev.yml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
ACCESS_TOKEN_PRIVATE_KEY_PATH: "access-refresh-token-keys/access-token-private.key"
|
||||||
|
ACCESS_TOKEN_PUBLIC_KEY_PATH: "access-refresh-token-keys/access-token-public.key"
|
||||||
|
REFRESH_TOKEN_PRIVATE_KEY_PATH: "access-refresh-token-keys/refresh-token-private.key"
|
||||||
|
REFRESH_TOKEN_PUBLIC_KEY_PATH: "access-refresh-token-keys/refresh-token-public.key"
|
||||||
|
TMDB_API_KEY: "467188b6746d2763198f8fdc0ae4bc9e"
|
17
src/main/resources/application.yml
Normal file
17
src/main/resources/application.yml
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
spring:
|
||||||
|
datasource:
|
||||||
|
url: jdbc:mysql://localhost:3306/movies?useSSL=false
|
||||||
|
username: root
|
||||||
|
password: marcin
|
||||||
|
profiles:
|
||||||
|
active: dev
|
||||||
|
|
||||||
|
access-token:
|
||||||
|
private: ${ACCESS_TOKEN_PRIVATE_KEY_PATH}
|
||||||
|
public: ${ACCESS_TOKEN_PUBLIC_KEY_PATH}
|
||||||
|
refresh-token:
|
||||||
|
private: ${REFRESH_TOKEN_PRIVATE_KEY_PATH}
|
||||||
|
public: ${REFRESH_TOKEN_PUBLIC_KEY_PATH}
|
||||||
|
|
||||||
|
tmdb:
|
||||||
|
api-key: ${TMDB_API_KEY}
|
13
src/test/java/com/s477603/movies/MoviesApplicationTests.java
Normal file
13
src/test/java/com/s477603/movies/MoviesApplicationTests.java
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
package com.s477603.movies;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
class MoviesApplicationTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void contextLoads() {
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user