Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions api/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,16 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:3.1.1'
runtimeOnly 'com.h2database:h2'
runtimeOnly 'org.postgresql:postgresql'
testImplementation 'org.springframework.boot:spring-boot-starter-actuator-test'
testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test'
testImplementation 'org.springframework.boot:spring-boot-starter-validation-test'
testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'

testImplementation 'org.springframework.boot:spring-boot-starter-security-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

Expand Down
68 changes: 68 additions & 0 deletions api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package edu.csumb.cst438.api;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;

/**
* This class should limit specific API routes to admin only
* Idk if this will later be replaced with OAuth or something else.
* But I wanted to make sure users can't call those specific API routes.
* Also I wanted to test it.
*/
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
/**
* This basically just states what routes can only be called by ADMIN
* @param http http
* @return http.build()
* @throws Exception if there's an exception
*/
@Bean
public SecurityFilterChain securityFilterChain(
HttpSecurity http,
@Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver) throws Exception{
AuthenticationEntryPoint entryPoint = (request, response, ex) -> {
response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer");
resolver.resolveException(request, response, null, ex);
};
AccessDeniedHandler deniedHandler = (request, response, ex) ->
resolver.resolveException(request, response, null, ex);

http
.csrf(csrf -> csrf.disable())
.headers(headers ->
headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
.authorizeHttpRequests(auth -> auth
.requestMatchers(
"/v3/api-docs/**",
"/swagger-ui/**",
"/swagger-ui.html"
).permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/users/me").authenticated()
.requestMatchers(HttpMethod.DELETE, "/api/v1/users/me").authenticated()
.requestMatchers(HttpMethod.GET, "/api/v1/users").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET, "/api/v1/users/{userid}").hasRole("ADMIN")
.requestMatchers(HttpMethod.PATCH, "/api/v1/users/{userid}").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/api/v1/users/{userid}").hasRole("ADMIN")
.anyRequest().authenticated()
)
.exceptionHandling(ex -> ex
.authenticationEntryPoint(entryPoint)
.accessDeniedHandler(deniedHandler));
return http.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package edu.csumb.cst438.api.controller;

import edu.csumb.cst438.api.record.UserResponseDTO;
import edu.csumb.cst438.api.record.UserRoleUpdateRequest;
import edu.csumb.cst438.api.service.UserService;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.data.web.PagedModel;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;

/**
* The home of the API routes and what they do
* Specifically for /api/v1/users and routes beyond that.
*/
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
private final UserService userService;

/**
* The constructor of UserController
* @param userService UserService instance
*/
public UserController(UserService userService){
this.userService = userService;
}

/**
* Call for multiple users on a single page
* @param page What page number the admin goes to (starts at 0)
* @param size What page number the admin goes to (starts at 0)
* @return Ok with users unless the one calling it isn't an Admin
*/
@GetMapping
public ResponseEntity<PagedModel<UserResponseDTO>> getAllUsers(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size){
Page<UserResponseDTO> users = userService.getAllUsers(page, size);
return ResponseEntity.ok(new PagedModel<>(users));
}

/**
* Call for one user via ID
* @param userId the ID that's being called
* @return Ok with user unless the one calling it isn't an Admin
*/
@GetMapping("/{userId}")
public ResponseEntity<UserResponseDTO> getUserById(@PathVariable Long userId){
UserResponseDTO user = userService.getUserById(userId);
return ResponseEntity.ok(user);
}

/**
* Call to delete one user via ID
* @param userId the ID that's being called
* @return noContent unless the one calling it isn't an Admin
*/
@DeleteMapping("/{userId}")
public ResponseEntity<Void> deleteUser(@PathVariable Long userId){
userService.deleteUser(userId);
return ResponseEntity.noContent().build();
}

/**
* Call to patch one user via ID and role
* @param userId the ID of the user being called
* @param request the role that it's being changed to
* @return Ok with user unless the one calling it isn't an Admin
*/
@PatchMapping("/{userId}")
public ResponseEntity<UserResponseDTO> patchUser(@PathVariable Long userId, @Valid @RequestBody UserRoleUpdateRequest request){
UserResponseDTO updatedUser = userService.patchUser(userId, request.role());
return ResponseEntity.ok(updatedUser);
}

/**
* Call to current logged in user
* @param principal the current user
* @return Ok with user unless the one calling it isn't the current user
*/
@GetMapping("/me")
public ResponseEntity<UserResponseDTO> getCurrentUser(Principal principal){
UserResponseDTO user = userService.getUserByEmail(principal.getName());
return ResponseEntity.ok(user);
}

/**
* Call to delete current logged in user
* @param principal the current user
* @return noContent unless the one calling it isn't the current user
*/
@DeleteMapping("/me")
public ResponseEntity<Void> deleteCurrentUser(Principal principal){
UserResponseDTO user = userService.getUserByEmail(principal.getName());
userService.deleteUser(user.id());
return ResponseEntity.noContent().build();
}
}
12 changes: 12 additions & 0 deletions api/src/main/java/edu/csumb/cst438/api/entity/User.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package edu.csumb.cst438.api.entity;

import jakarta.persistence.*;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;

import java.util.*;
Expand Down Expand Up @@ -56,6 +59,15 @@ public User(String email, String displayName, String role) {
this.role = role;
}

/**
* Updates role
* Not 110% sure if there's a better way to do this...
* @param role USER / ADMIN
*/
public void changeRole(String role){
this.role = role;
}

/**
* Adds a recipe to the collection and synchronizes the user's recipe collection
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package edu.csumb.cst438.api.errorHandling;

import jakarta.persistence.EntityNotFoundException;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.net.URI;
import java.util.stream.Collectors;

/**
* Exception handler class
*/
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* Handles authentication exception
* @param ex exception
* @param request request
* @return problem
*/
@ExceptionHandler(AuthenticationException.class)
public ProblemDetail handleAuthentication(AuthenticationException ex, HttpServletRequest request) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.UNAUTHORIZED, "Authentication is required to access this resource");
problem.setTitle("Unauthorized");
problem.setInstance(URI.create(request.getRequestURI()));
return problem;
}

/**
* Handles access denied exception
* @param ex exception
* @param request request
* @return problem
*/
@ExceptionHandler(AccessDeniedException.class)
public ProblemDetail handleAccessDenied(AccessDeniedException ex, HttpServletRequest request) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.FORBIDDEN, "You do not have permission to access this resource");
problem.setTitle("Forbidden");
problem.setInstance(URI.create(request.getRequestURI()));
return problem;
}

/**
* Handles entity not found exception
* @param ex exception
* @param request request
* @return problem
*/
@ExceptionHandler(EntityNotFoundException.class)
public ProblemDetail handleEntityNotFound(EntityNotFoundException ex, HttpServletRequest request) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Not Found");
problem.setInstance(URI.create(request.getRequestURI()));
return problem;
}

/**
* Handles illegal argument exception
* @param ex exception
* @param request request
* @return problem
*/
@ExceptionHandler(IllegalArgumentException.class)
public ProblemDetail handleBadRequest(IllegalArgumentException ex, HttpServletRequest request) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, ex.getMessage());
problem.setTitle("Bad Request");
problem.setInstance(URI.create(request.getRequestURI()));
return problem;
}

/**
* Handles method argument not valid exception
* @param ex exception
* @param request request
* @return problem
*/
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
String detail = ex.getBindingResult().getFieldErrors().stream()
.map(e -> e.getField() + ": " + e.getDefaultMessage())
.collect(Collectors.joining("; "));
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, detail);
problem.setTitle("Bad Request");
return handleExceptionInternal(ex, problem, headers, HttpStatus.BAD_REQUEST, request);
}

/**
* Handles http message not readable exception
* @param ex exception
* @param request request
* @return problem
*/
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(
HttpMessageNotReadableException ex, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Request body is missing or malformed");
problem.setTitle("Bad Request");
return handleExceptionInternal(ex, problem, headers, HttpStatus.BAD_REQUEST, request);
}

/**
* Handles unexpected stuff
* @param ex exception
* @param request request
* @return problem
*/
@ExceptionHandler(Exception.class)
public ProblemDetail handleUnexpected(Exception ex, HttpServletRequest request) {
log.error("Unhandled exception on {}", request.getRequestURI(), ex);
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
problem.setTitle("Internal Server Error");
problem.setInstance(URI.create(request.getRequestURI()));
return problem;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package edu.csumb.cst438.api.record;

public record UserResponseDTO(
Long id,
String email,
String displayName,
String role
) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package edu.csumb.cst438.api.record;

import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;

/**
* For updating the user role in PATCH
* @param role user role
*/
public record UserRoleUpdateRequest(
@NotNull(message = "role is required")
@Pattern(regexp = "USER|ADMIN", message = "role must be USER or ADMIN")
String role) {
}
Loading
Loading