diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/.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/build.gradle b/build.gradle new file mode 100644 index 0000000..63527e9 --- /dev/null +++ b/build.gradle @@ -0,0 +1,39 @@ +plugins { + id 'org.springframework.boot' version '2.7.1' + id 'io.spring.dependency-management' version '1.0.11.RELEASE' + id 'java' +} + +group = 'com.aaronr92' +version = '0.5' +sourceCompatibility = '11' + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-actuator' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-web' + + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'mysql:mysql-connector-java:8.0.29' + + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + + implementation 'org.springframework.boot:spring-boot-starter-security' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.security:spring-security-test' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..41d9927 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..00e33ed --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/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 \ + "$@" + +# 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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@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%" == "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%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..c555051 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'account-service' diff --git a/src/main/java/com/aaronr92/accountservice/AccountServiceApplication.java b/src/main/java/com/aaronr92/accountservice/AccountServiceApplication.java new file mode 100644 index 0000000..da48572 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/AccountServiceApplication.java @@ -0,0 +1,12 @@ +package com.aaronr92.accountservice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AccountServiceApplication { + + public static void main(String[] args) { + SpringApplication.run(AccountServiceApplication.class, args); + } +} \ No newline at end of file diff --git a/src/main/java/com/aaronr92/accountservice/config/BeanConfig.java b/src/main/java/com/aaronr92/accountservice/config/BeanConfig.java new file mode 100644 index 0000000..000e8bc --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/config/BeanConfig.java @@ -0,0 +1,70 @@ +package com.aaronr92.accountservice.config; + +import com.aaronr92.accountservice.entities.BreachedPassword; +import com.aaronr92.accountservice.repositories.BreachedPasswordRepository; +import com.aaronr92.accountservice.services.UserService; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpStatus; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.access.AccessDeniedHandler; + +import java.time.Instant; +import java.util.*; + +@Configuration +public class BeanConfig { + + @Autowired + private UserService userService; + + @Bean + public DaoAuthenticationProvider authenticationProvider() { + DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); + provider.setPasswordEncoder(getEncoder()); + provider.setUserDetailsService(userService); + return provider; + } + + @Bean + public PasswordEncoder getEncoder() { + return new BCryptPasswordEncoder(); + } + + /*@Bean + CommandLineRunner commandLineRunner(BreachedPasswordRepository breachedPasswordRepository) { + return args -> { + Set breachedPasswords = new HashSet<>( + Set.of("PasswordForJanuary", "PasswordForFebruary", "PasswordForMarch", "PasswordForApril", + "PasswordForMay", "PasswordForJune", "PasswordForJuly", "PasswordForAugust", + "PasswordForSeptember", "PasswordForOctober", "PasswordForNovember", "PasswordForDecember") + ); + + breachedPasswords.forEach(pass -> breachedPasswordRepository.save( + BreachedPassword.builder() + .password(pass) + .build())); + }; + }*/ + + @Bean + public AccessDeniedHandler getAccessDeniedHandler() { + return (request, response, accessDeniedException) -> { + response.setStatus(HttpStatus.FORBIDDEN.value()); + response.setContentType("application/json"); + Map data = new LinkedHashMap<>(); + data.put("timestamp", Instant.now().toString()); + data.put("status", HttpStatus.FORBIDDEN.value()); + data.put("error", "Forbidden"); + data.put("message", "Access Denied!"); + data.put("path", request.getRequestURI()); + response.getOutputStream() + .println(new ObjectMapper().writeValueAsString(data)); + }; + } +} diff --git a/src/main/java/com/aaronr92/accountservice/controllers/AdminController.java b/src/main/java/com/aaronr92/accountservice/controllers/AdminController.java new file mode 100644 index 0000000..54d020e --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/controllers/AdminController.java @@ -0,0 +1,34 @@ +package com.aaronr92.accountservice.controllers; + +import com.aaronr92.accountservice.entities.User; +import com.aaronr92.accountservice.services.UserService; +import com.aaronr92.accountservice.util.RoleOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/api/admin") +public class AdminController { + + @Autowired + UserService userService; + + @GetMapping("/user") + ResponseEntity> getAllRoles() { + return userService.getAllRoles(); + } + + @DeleteMapping("/user/{email}") + ResponseEntity> deleteUser(@PathVariable String email) { + return userService.deleteUser(email); + } + + @PutMapping("/user/role") + ResponseEntity updateUserRoles(@RequestBody RoleOperation operation) { + return userService.updateRole(operation); + } +} diff --git a/src/main/java/com/aaronr92/accountservice/controllers/AuthController.java b/src/main/java/com/aaronr92/accountservice/controllers/AuthController.java new file mode 100644 index 0000000..68ba510 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/controllers/AuthController.java @@ -0,0 +1,35 @@ +package com.aaronr92.accountservice.controllers; + +import com.aaronr92.accountservice.entities.User; +import com.aaronr92.accountservice.services.UserService; +import com.aaronr92.accountservice.util.NewUserPassword; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +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; + +import javax.validation.Valid; +import java.util.Map; + +@RestController +@RequestMapping("/api/auth") +public class AuthController { + + @Autowired + UserService userService; + + @PostMapping("/signup") + ResponseEntity signUp(@RequestBody User user) { + return new ResponseEntity<>(userService.registerNewUser(user), HttpStatus.OK); + } + + @PostMapping("/changepass") + ResponseEntity> changePassword(@AuthenticationPrincipal User userDetails, + @Valid @RequestBody NewUserPassword newPassword) { + return userService.changePassword(newPassword.getNewPassword(), userDetails); + } +} diff --git a/src/main/java/com/aaronr92/accountservice/controllers/PaymentController.java b/src/main/java/com/aaronr92/accountservice/controllers/PaymentController.java new file mode 100644 index 0000000..2e8b823 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/controllers/PaymentController.java @@ -0,0 +1,36 @@ +package com.aaronr92.accountservice.controllers; + +import com.aaronr92.accountservice.entities.Payment; +import com.aaronr92.accountservice.entities.User; +import com.aaronr92.accountservice.services.PaymentService; +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.*; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/api") +public class PaymentController { + + @Autowired + PaymentService paymentService; + + @GetMapping("/empl/payment") + ResponseEntity getPayment(@AuthenticationPrincipal User user, + @RequestParam(required = false) String period) { + return paymentService.getPaymentForPeriod(period, user); + } + + @PostMapping("/acct/payments") + ResponseEntity> uploadPayrolls(@RequestBody List payments) { + return paymentService.uploadPayrolls(payments); + } + + @PutMapping("/acct/payments") + ResponseEntity> updatePaymentInfo(@RequestBody Payment payment) { + return paymentService.updatePayment(payment); + } +} diff --git a/src/main/java/com/aaronr92/accountservice/entities/BreachedPassword.java b/src/main/java/com/aaronr92/accountservice/entities/BreachedPassword.java new file mode 100644 index 0000000..0b5bf1a --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/entities/BreachedPassword.java @@ -0,0 +1,21 @@ +package com.aaronr92.accountservice.entities; + +import lombok.*; + +import javax.persistence.*; + +@Entity(name = "breached_passwords") +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class BreachedPassword { + + @Id + @GeneratedValue(strategy = GenerationType.TABLE) + private Long id; + + @Column + private String password; +} diff --git a/src/main/java/com/aaronr92/accountservice/entities/Payment.java b/src/main/java/com/aaronr92/accountservice/entities/Payment.java new file mode 100644 index 0000000..2fc3ec5 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/entities/Payment.java @@ -0,0 +1,51 @@ +package com.aaronr92.accountservice.entities; + +import com.aaronr92.accountservice.util.YearMonthDateConverter; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import javax.persistence.*; +import java.time.YearMonth; +import java.util.Objects; + +@Entity(name = "payment") +@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"employee", "period"})}) +@Getter +@Setter +@NoArgsConstructor +public class Payment { + + @Id + @GeneratedValue(strategy = GenerationType.TABLE) + @JsonIgnore + private long id; + + @Column + private String employee; // user's email + + @Column + @Convert(converter = YearMonthDateConverter.class) + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MM-yyyy") + private YearMonth period; // + + @Column + private long salary; + + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Payment payment = (Payment) o; + return Objects.equals(employee, payment.employee) && Objects.equals(period, payment.period); + } + + @Override + public int hashCode() { + return Objects.hash(employee, period); + } +} diff --git a/src/main/java/com/aaronr92/accountservice/entities/Role.java b/src/main/java/com/aaronr92/accountservice/entities/Role.java new file mode 100644 index 0000000..a68032f --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/entities/Role.java @@ -0,0 +1,11 @@ +package com.aaronr92.accountservice.entities; + +import lombok.Getter; + + +@Getter +public enum Role { + ROLE_ADMINISTRATOR, + ROLE_ACCOUNTANT, + ROLE_USER +} diff --git a/src/main/java/com/aaronr92/accountservice/entities/User.java b/src/main/java/com/aaronr92/accountservice/entities/User.java new file mode 100644 index 0000000..16e4eb4 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/entities/User.java @@ -0,0 +1,106 @@ +package com.aaronr92.accountservice.entities; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import org.hibernate.annotations.SortNatural; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import javax.persistence.*; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.util.*; + +@Entity +@ToString +@Getter +@Setter +@NoArgsConstructor +public class User implements UserDetails { + + @Id + @GeneratedValue(strategy = GenerationType.TABLE) + @JsonProperty(access = JsonProperty.Access.READ_ONLY) + @JsonIgnore + private long id; + + @NotBlank + @Column + private String name; + + @NotBlank + @Column + private String lastname; + + @NotBlank + @Pattern(regexp = ".+(@acme.com)$") + @Column + private String email; + + @NotBlank + @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + @Column + private String password; + + @JsonProperty(access = JsonProperty.Access.READ_ONLY) + @Enumerated(EnumType.STRING) + @ElementCollection(fetch = FetchType.EAGER) + @SortNatural + @Column + private Set roles; + + @JsonIgnore + @Override + public Collection getAuthorities() { + List authorities = new ArrayList<>(); + roles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.toString()))); + return authorities; + } + + @JsonIgnore + @Override + public String getUsername() { + return email; + } + + @JsonIgnore + @Override + public boolean isAccountNonExpired() { + return true; + } + + @JsonIgnore + @Override + public boolean isAccountNonLocked() { + return true; + } + + @JsonIgnore + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @JsonIgnore + @Override + public boolean isEnabled() { + return true; + } + + @JsonIgnore + public void grantAuthority(Role authority) { + if (roles == null) + roles = new TreeSet<>(); + roles.add(authority); + } + + @JsonIgnore + public void removeAuthority(Role authority) { + roles.remove(authority); + } +} diff --git a/src/main/java/com/aaronr92/accountservice/exceptions/BreachedPasswordException.java b/src/main/java/com/aaronr92/accountservice/exceptions/BreachedPasswordException.java new file mode 100644 index 0000000..830a171 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/exceptions/BreachedPasswordException.java @@ -0,0 +1,7 @@ +package com.aaronr92.accountservice.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "The password is in the hacker's database!") +public class BreachedPasswordException extends RuntimeException {} diff --git a/src/main/java/com/aaronr92/accountservice/exceptions/DuplicatePaymentException.java b/src/main/java/com/aaronr92/accountservice/exceptions/DuplicatePaymentException.java new file mode 100644 index 0000000..70dd011 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/exceptions/DuplicatePaymentException.java @@ -0,0 +1,8 @@ +package com.aaronr92.accountservice.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Payment already exists!") +public class DuplicatePaymentException extends RuntimeException{ +} diff --git a/src/main/java/com/aaronr92/accountservice/exceptions/EmployeeNotFoundException.java b/src/main/java/com/aaronr92/accountservice/exceptions/EmployeeNotFoundException.java new file mode 100644 index 0000000..73bcad8 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/exceptions/EmployeeNotFoundException.java @@ -0,0 +1,8 @@ +package com.aaronr92.accountservice.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Employee not found!") +public class EmployeeNotFoundException extends RuntimeException { +} diff --git a/src/main/java/com/aaronr92/accountservice/exceptions/Message.java b/src/main/java/com/aaronr92/accountservice/exceptions/Message.java new file mode 100644 index 0000000..ebc23f0 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/exceptions/Message.java @@ -0,0 +1,15 @@ +package com.aaronr92.accountservice.exceptions; + +import lombok.Getter; + +@Getter +public enum Message { + SIGNUP("The password length must be at least 12 chars!"), + CHECK_PASSWORD("Password length must be 12 chars minimum!"); + + private final String message; + + Message(String message) { + this.message = message; + } +} diff --git a/src/main/java/com/aaronr92/accountservice/exceptions/PasswordTooShortException.java b/src/main/java/com/aaronr92/accountservice/exceptions/PasswordTooShortException.java new file mode 100644 index 0000000..2780fe3 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/exceptions/PasswordTooShortException.java @@ -0,0 +1,13 @@ +package com.aaronr92.accountservice.exceptions; + +import lombok.Getter; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@Getter +@ResponseStatus(code = HttpStatus.BAD_REQUEST) +public class PasswordTooShortException extends RuntimeException { + public PasswordTooShortException(Message message) { + super(message.getMessage()); + } +} diff --git a/src/main/java/com/aaronr92/accountservice/exceptions/PaymentNotFoundException.java b/src/main/java/com/aaronr92/accountservice/exceptions/PaymentNotFoundException.java new file mode 100644 index 0000000..1029b8b --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/exceptions/PaymentNotFoundException.java @@ -0,0 +1,8 @@ +package com.aaronr92.accountservice.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Payment by this period was not found!") +public class PaymentNotFoundException extends RuntimeException { +} diff --git a/src/main/java/com/aaronr92/accountservice/exceptions/RepetitivePasswordException.java b/src/main/java/com/aaronr92/accountservice/exceptions/RepetitivePasswordException.java new file mode 100644 index 0000000..c9e5fdb --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/exceptions/RepetitivePasswordException.java @@ -0,0 +1,9 @@ +package com.aaronr92.accountservice.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "The passwords must be different!") +public class RepetitivePasswordException extends RuntimeException { + +} diff --git a/src/main/java/com/aaronr92/accountservice/exceptions/RoleNotFoundException.java b/src/main/java/com/aaronr92/accountservice/exceptions/RoleNotFoundException.java new file mode 100644 index 0000000..01bbdd9 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/exceptions/RoleNotFoundException.java @@ -0,0 +1,8 @@ +package com.aaronr92.accountservice.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Role not found!") +public class RoleNotFoundException extends RuntimeException { +} diff --git a/src/main/java/com/aaronr92/accountservice/exceptions/SalaryException.java b/src/main/java/com/aaronr92/accountservice/exceptions/SalaryException.java new file mode 100644 index 0000000..573c0b7 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/exceptions/SalaryException.java @@ -0,0 +1,8 @@ +package com.aaronr92.accountservice.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Salary must be non negative!") +public class SalaryException extends RuntimeException { +} diff --git a/src/main/java/com/aaronr92/accountservice/exceptions/WrongPeriodException.java b/src/main/java/com/aaronr92/accountservice/exceptions/WrongPeriodException.java new file mode 100644 index 0000000..051c410 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/exceptions/WrongPeriodException.java @@ -0,0 +1,8 @@ +package com.aaronr92.accountservice.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Wrong period!") +public class WrongPeriodException extends RuntimeException { +} diff --git a/src/main/java/com/aaronr92/accountservice/repositories/BreachedPasswordRepository.java b/src/main/java/com/aaronr92/accountservice/repositories/BreachedPasswordRepository.java new file mode 100644 index 0000000..b28325a --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/repositories/BreachedPasswordRepository.java @@ -0,0 +1,13 @@ +package com.aaronr92.accountservice.repositories; + +import com.aaronr92.accountservice.entities.BreachedPassword; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface BreachedPasswordRepository extends CrudRepository { + + @Query + Boolean existsBreachedPasswordsByPassword(String password); +} diff --git a/src/main/java/com/aaronr92/accountservice/repositories/PaymentRepository.java b/src/main/java/com/aaronr92/accountservice/repositories/PaymentRepository.java new file mode 100644 index 0000000..a9d59fc --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/repositories/PaymentRepository.java @@ -0,0 +1,14 @@ +package com.aaronr92.accountservice.repositories; + +import com.aaronr92.accountservice.entities.Payment; +import org.springframework.data.repository.CrudRepository; + +import java.time.YearMonth; +import java.util.List; +import java.util.Optional; + +public interface PaymentRepository extends CrudRepository { + List findPaymentByEmployeeIgnoreCase(String email); + + Optional findPaymentByEmployeeIgnoreCaseAndPeriod(String employee, YearMonth period); +} diff --git a/src/main/java/com/aaronr92/accountservice/repositories/UserRepository.java b/src/main/java/com/aaronr92/accountservice/repositories/UserRepository.java new file mode 100644 index 0000000..d9e10b6 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/repositories/UserRepository.java @@ -0,0 +1,15 @@ +package com.aaronr92.accountservice.repositories; + +import com.aaronr92.accountservice.entities.User; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface UserRepository extends CrudRepository { + + @Query + Optional findUserByEmailIgnoreCase(String email); +} diff --git a/src/main/java/com/aaronr92/accountservice/security/RestAuthenticationEntryPoint.java b/src/main/java/com/aaronr92/accountservice/security/RestAuthenticationEntryPoint.java new file mode 100644 index 0000000..4085911 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/security/RestAuthenticationEntryPoint.java @@ -0,0 +1,20 @@ +package com.aaronr92.accountservice.security; + +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@Component +public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { + @Override + public void commence(HttpServletRequest request, + HttpServletResponse response, + AuthenticationException authException) throws IOException, ServletException { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); + } +} diff --git a/src/main/java/com/aaronr92/accountservice/security/WebSecurityConfig.java b/src/main/java/com/aaronr92/accountservice/security/WebSecurityConfig.java new file mode 100644 index 0000000..57e1b83 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/security/WebSecurityConfig.java @@ -0,0 +1,56 @@ +package com.aaronr92.accountservice.security; + +import com.aaronr92.accountservice.entities.Role; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.access.AccessDeniedHandler; + +@Configuration +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + RestAuthenticationEntryPoint restAuthenticationEntryPoint; + + @Autowired + DaoAuthenticationProvider authenticationProvider; + + @Autowired + AccessDeniedHandler accessDeniedHandler; + + @Override + public void configure(AuthenticationManagerBuilder auth) { + auth.authenticationProvider(authenticationProvider); + } + + @Override + public void configure(HttpSecurity http) throws Exception { + http.httpBasic() + .authenticationEntryPoint(restAuthenticationEntryPoint) // Handle auth error + .and() + .csrf().disable().headers().frameOptions().disable() // for Postman + .and() + .authorizeRequests() + .antMatchers(HttpMethod.POST, "/api/auth/singup").permitAll() + .antMatchers(HttpMethod.POST, "/api/auth/changepass").hasAnyAuthority(Role.ROLE_USER.name(), + Role.ROLE_ACCOUNTANT.name(), + Role.ROLE_ADMINISTRATOR.name()) + .antMatchers(HttpMethod.GET, "/api/empl/payment").hasAnyAuthority(Role.ROLE_USER.name(), + Role.ROLE_ACCOUNTANT.name()) + .antMatchers(HttpMethod.POST, "/api/acct/payments").hasAuthority(Role.ROLE_ACCOUNTANT.name()) + .antMatchers(HttpMethod.PUT, "/api/acct/payments").hasAuthority(Role.ROLE_ACCOUNTANT.name()) + .antMatchers("/api/admin/**").hasAuthority(Role.ROLE_ADMINISTRATOR.name()) + .and() + .exceptionHandling().accessDeniedHandler(accessDeniedHandler) + .and() + .sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // no session + } +} diff --git a/src/main/java/com/aaronr92/accountservice/services/PaymentService.java b/src/main/java/com/aaronr92/accountservice/services/PaymentService.java new file mode 100644 index 0000000..2badc5f --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/services/PaymentService.java @@ -0,0 +1,105 @@ +package com.aaronr92.accountservice.services; + +import com.aaronr92.accountservice.entities.Payment; +import com.aaronr92.accountservice.entities.User; +import com.aaronr92.accountservice.exceptions.*; +import com.aaronr92.accountservice.repositories.PaymentRepository; +import com.aaronr92.accountservice.repositories.UserRepository; +import com.aaronr92.accountservice.util.EmployeePaymentResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +import java.time.DateTimeException; +import java.time.YearMonth; +import java.time.format.DateTimeFormatter; +import java.util.*; + +@Service +public class PaymentService { + + @Autowired + private PaymentRepository paymentRepository; + + @Autowired + private UserRepository userRepository; + + public ResponseEntity> uploadPayrolls(List payments) { + validatePayment(payments); + paymentRepository.saveAll(payments); + return new ResponseEntity<>(Map.of("status", "Added successfully!"), HttpStatus.OK); + } + + public ResponseEntity> updatePayment(Payment payment) { + checkEmployeeExistence(payment.getEmployee()); + validateSalary(payment); + Payment p = paymentRepository + .findPaymentByEmployeeIgnoreCaseAndPeriod(payment.getEmployee(), payment.getPeriod()) + .orElseThrow(EmployeeNotFoundException::new); + p.setSalary(payment.getSalary()); + paymentRepository.save(p); + return new ResponseEntity<>(Map.of("status", "Updated successfully!"), HttpStatus.OK); + } + + public ResponseEntity getPaymentForPeriod(String period, User user) { + if (period == null) { + List payments = paymentRepository.findPaymentByEmployeeIgnoreCase(user.getEmail()); + payments.sort(Comparator.comparing(Payment::getPeriod).reversed()); + List responses = new ArrayList<>(); + for (Payment payment : payments) { + responses.add(createResponse(payment, user)); + } + return new ResponseEntity<>(responses, HttpStatus.OK); + } else { + Payment payment = paymentRepository.findPaymentByEmployeeIgnoreCaseAndPeriod(user.getEmail(), getYearMonthFromString(period)) + .orElseThrow(PaymentNotFoundException::new); + EmployeePaymentResponse response = createResponse(payment, user); + return new ResponseEntity<>(response, HttpStatus.OK); + } + } + + private EmployeePaymentResponse createResponse(Payment payment, User user) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM-yyyy", Locale.ENGLISH); + EmployeePaymentResponse response = new EmployeePaymentResponse(); + response.setName(user.getName()); + response.setLastname(user.getLastname()); + response.setPeriod(payment.getPeriod().format(formatter)); + response.setSalary(String.format("%d dollar(s) %d cent(s)", payment.getSalary() / 100, payment.getSalary() % 100)); + return response; + } + + private void validatePayment(List payments) { + for (Payment payment : payments) { + validateSalary(payment); + checkEmployeeExistence(payment.getEmployee()); + checkDuplicatePayment(payment); + } + } + + private void validateSalary(Payment payment) { + if (payment.getSalary() < 0) + throw new SalaryException(); + } + + private void checkEmployeeExistence(String employee) { + if (userRepository.findUserByEmailIgnoreCase(employee).isEmpty()) + throw new EmployeeNotFoundException(); + } + + private void checkDuplicatePayment(Payment payment) { + List payments = paymentRepository.findPaymentByEmployeeIgnoreCase(payment.getEmployee()); + if (payments.stream().anyMatch(payment::equals)) + throw new DuplicatePaymentException(); + } + + private YearMonth getYearMonthFromString(String period) { + YearMonth yearMonth = null; + try { + yearMonth = YearMonth.parse(period, DateTimeFormatter.ofPattern("MM-yyyy")); + } catch (DateTimeException e) { + throw new WrongPeriodException(); + } + return yearMonth; + } +} diff --git a/src/main/java/com/aaronr92/accountservice/services/UserService.java b/src/main/java/com/aaronr92/accountservice/services/UserService.java new file mode 100644 index 0000000..440b438 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/services/UserService.java @@ -0,0 +1,131 @@ +package com.aaronr92.accountservice.services; + +import com.aaronr92.accountservice.entities.Role; +import com.aaronr92.accountservice.entities.User; +import com.aaronr92.accountservice.exceptions.*; +import com.aaronr92.accountservice.repositories.BreachedPasswordRepository; +import com.aaronr92.accountservice.repositories.UserRepository; +import com.aaronr92.accountservice.util.RoleOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Service +public class UserService implements UserDetailsService { + + @Autowired + private UserRepository userRepository; + @Autowired + private BreachedPasswordRepository breachedPasswordRepository; + @Autowired + private PasswordEncoder passwordEncoder; + + public User findByEmail(String email) { + return userRepository.findUserByEmailIgnoreCase(email.toLowerCase()) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found!")); + } + + public User registerNewUser(User user) { + user.setEmail(user.getEmail().toLowerCase()); + checkValidPassword(user.getPassword()); + if (userRepository.findUserByEmailIgnoreCase(user.getEmail()).isEmpty()) { + if (userRepository.count() == 0) { + user.grantAuthority(Role.ROLE_ADMINISTRATOR); + } else + user.grantAuthority(Role.ROLE_USER); + user.setPassword(passwordEncoder.encode(user.getPassword())); + userRepository.save(user); + } else + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "User exist!"); + return user; + } + + public ResponseEntity> getAllRoles() { + return ResponseEntity.ok((List) userRepository.findAll()); + } + + public ResponseEntity> deleteUser(String email) { + Optional user = userRepository.findUserByEmailIgnoreCase(email); + if (user.isEmpty()) + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found!"); + if (user.get().getRoles().contains(Role.ROLE_ADMINISTRATOR)) + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Can't remove ADMINISTRATOR role!"); + userRepository.delete(user.get()); + return ResponseEntity.ok(Map.of("user", email, "status", "Deleted successfully!")); + } + + public ResponseEntity> changePassword(String newPassword, User authUser) { + checkValidPassword(newPassword); + checkDifferencePasswords(newPassword, authUser.getPassword()); + User tmpUser = userRepository.findUserByEmailIgnoreCase(authUser.getEmail()).get(); + tmpUser.setPassword(passwordEncoder.encode(newPassword)); + userRepository.save(tmpUser); + return new ResponseEntity<>(Map.of("email", authUser.getEmail(),"status","The password has been updated successfully"), HttpStatus.OK); + } + + public ResponseEntity updateRole(RoleOperation operation) { + Optional user = userRepository.findUserByEmailIgnoreCase(operation.getEmail()); + if (user.isEmpty()) + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found!"); + Role role = checkRole(operation.getRole()); + if (operation.getOperation().equals("GRANT")) { + if (user.get().getRoles().contains(Role.ROLE_ADMINISTRATOR) || role == Role.ROLE_ADMINISTRATOR) + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "The user cannot combine administrative and business roles!"); + user.get().grantAuthority(role); + userRepository.save(user.get()); + } else if (operation.getOperation().equals("REMOVE")) { + if (!user.get().getRoles().contains(role)) + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "The user does not have a role!"); + if (role.equals(Role.ROLE_ADMINISTRATOR)) + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Can't remove ADMINISTRATOR role!"); + if (user.get().getRoles().size() == 1) + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "The user must have at least one role!"); + user.get().removeAuthority(role); + userRepository.save(user.get()); + } + return ResponseEntity.ok(user.get()); + } + + @Override + public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { + Optional user = userRepository.findUserByEmailIgnoreCase(email); + if (user.isPresent()) + return user.get(); + else + throw new UsernameNotFoundException(String.format("Username[%s] not found", email)); + } + + private void checkValidPassword(String password) { + if (password == null || password.length() < 12) { + throw new PasswordTooShortException(Message.SIGNUP); + } + if (breachedPasswordRepository.existsBreachedPasswordsByPassword(password)) { + throw new BreachedPasswordException(); + } + } + + private void checkDifferencePasswords(String newPassword, String oldPassword) { + if (passwordEncoder.matches(newPassword, oldPassword)) { + throw new RepetitivePasswordException(); + } + } + + private Role checkRole(String role) { + for (Role r : Role.values()) { + if (r.name().equals(String.format("ROLE_%s", role))) { + return r; + } + } + throw new RoleNotFoundException(); + } +} diff --git a/src/main/java/com/aaronr92/accountservice/util/EmployeePaymentResponse.java b/src/main/java/com/aaronr92/accountservice/util/EmployeePaymentResponse.java new file mode 100644 index 0000000..29c05ba --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/util/EmployeePaymentResponse.java @@ -0,0 +1,19 @@ +package com.aaronr92.accountservice.util; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@NoArgsConstructor +@Getter +@Setter +public class EmployeePaymentResponse { + + private String name; + + private String lastname; + + private String period; + + private String salary; +} diff --git a/src/main/java/com/aaronr92/accountservice/util/NewUserPassword.java b/src/main/java/com/aaronr92/accountservice/util/NewUserPassword.java new file mode 100644 index 0000000..5f06119 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/util/NewUserPassword.java @@ -0,0 +1,22 @@ +package com.aaronr92.accountservice.util; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; + +@NoArgsConstructor +@Getter +@Setter +public class NewUserPassword { + + @Pattern(regexp = ".+(@acme.com)$") + String email; + + @NotBlank + @JsonProperty("new_password") + String newPassword; +} diff --git a/src/main/java/com/aaronr92/accountservice/util/RoleOperation.java b/src/main/java/com/aaronr92/accountservice/util/RoleOperation.java new file mode 100644 index 0000000..883ddec --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/util/RoleOperation.java @@ -0,0 +1,19 @@ +package com.aaronr92.accountservice.util; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@NoArgsConstructor +public class RoleOperation { + + @JsonProperty("user") + private String email; + + private String role; + + private String operation; +} diff --git a/src/main/java/com/aaronr92/accountservice/util/YearMonthDateConverter.java b/src/main/java/com/aaronr92/accountservice/util/YearMonthDateConverter.java new file mode 100644 index 0000000..a89ce15 --- /dev/null +++ b/src/main/java/com/aaronr92/accountservice/util/YearMonthDateConverter.java @@ -0,0 +1,34 @@ +package com.aaronr92.accountservice.util; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; +import java.sql.Date; +import java.time.Instant; +import java.time.YearMonth; +import java.time.ZoneId; + +@Converter +public class YearMonthDateConverter implements AttributeConverter { + + @Override + public Date convertToDatabaseColumn(YearMonth attribute) { + if (attribute != null) + return Date.valueOf( + attribute + .atDay(1) + ); + return null; + } + + @Override + public YearMonth convertToEntityAttribute(Date dbData) { + if (dbData != null) + return YearMonth.from( + Instant + .ofEpochMilli(dbData.getTime()) + .atZone(ZoneId.systemDefault()) + .toLocalDateTime() + ); + return null; + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..c5230f8 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,20 @@ +server.port=8080 +management.endpoints.web.exposure.include=* +management.endpoint.shutdown.enabled=true +spring.jackson.serialization.INDENT_OUTPUT=true +server.error.include-message=always + +#datasource settings +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +spring.datasource.username=springuser +spring.datasource.password=ThePassword +spring.datasource.url=jdbc:mysql://localhost:3306/account_service + +#data settings +spring.jpa.hibernate.ddl-auto=update +spring.main.allow-circular-references=true + +#console settings +spring.jpa.show-sql=false + +debug=false \ No newline at end of file diff --git a/src/test/java/com/aaronr92/accountservice/AccountServiceApplicationTests.java b/src/test/java/com/aaronr92/accountservice/AccountServiceApplicationTests.java new file mode 100644 index 0000000..f4747dc --- /dev/null +++ b/src/test/java/com/aaronr92/accountservice/AccountServiceApplicationTests.java @@ -0,0 +1,13 @@ +package com.aaronr92.accountservice; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class AccountServiceApplicationTests { + + @Test + void contextLoads() { + } + +}