Skip to content
Snippets Groups Projects
Commit 6c7debff authored by Tini Tran's avatar Tini Tran
Browse files

Added Swagger documentation to the controllers

parent e97584fc
No related branches found
No related tags found
No related merge requests found
package ntnu.idatt2105.group44.trivioServer.controller; package ntnu.idatt2105.group44.trivioServer.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import ntnu.idatt2105.group44.trivioServer.dto.LoginRequest; import ntnu.idatt2105.group44.trivioServer.dto.LoginRequest;
import ntnu.idatt2105.group44.trivioServer.dto.SignUpRequest; import ntnu.idatt2105.group44.trivioServer.dto.SignUpRequest;
import ntnu.idatt2105.group44.trivioServer.model.User; import ntnu.idatt2105.group44.trivioServer.model.User;
...@@ -15,6 +19,8 @@ import org.springframework.web.bind.annotation.RequestBody; ...@@ -15,6 +19,8 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@Tag(name = "Authentication Controller", description = "These endpoints is responsible for "
+ "logging in and signing up")
@RestController @RestController
@RequestMapping @RequestMapping
@CrossOrigin @CrossOrigin
...@@ -31,7 +37,14 @@ public class AuthController { ...@@ -31,7 +37,14 @@ public class AuthController {
this.jwtService = jwtService; this.jwtService = jwtService;
this.userService = userService; this.userService = userService;
} }
@Operation(
summary = "Authenticates the user and generates a token",
description = "The endpoints takes a login request and authenticates the credentials,"
+ "if the credentials are valid, a token is generated")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successful, token is generated and returned")
, @ApiResponse(responseCode = "401", description = "The credentials are invalid")
})
@PostMapping("/login") @PostMapping("/login")
public ResponseEntity<String> login(@RequestBody LoginRequest loginRequest){ public ResponseEntity<String> login(@RequestBody LoginRequest loginRequest){
if(authenticationService.authenticateUser(loginRequest)){ if(authenticationService.authenticateUser(loginRequest)){
...@@ -39,7 +52,13 @@ public class AuthController { ...@@ -39,7 +52,13 @@ public class AuthController {
return new ResponseEntity<>(jwtService.generateToken(Long.toString(user.getId())), HttpStatus.OK); return new ResponseEntity<>(jwtService.generateToken(Long.toString(user.getId())), HttpStatus.OK);
} else return new ResponseEntity<>("Invalid Credentials!", HttpStatus.UNAUTHORIZED); } else return new ResponseEntity<>("Invalid Credentials!", HttpStatus.UNAUTHORIZED);
} }
@Operation(
summary = "Creates an user",
description = "Creates an user and saves it in the database")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "User is created")
, @ApiResponse(responseCode = "400", description = "User credentials already exists in database")
})
@PostMapping("/signup") @PostMapping("/signup")
public ResponseEntity<String> signup(@RequestBody SignUpRequest signUpRequest){ public ResponseEntity<String> signup(@RequestBody SignUpRequest signUpRequest){
if(!authenticationService.credentialsExists(signUpRequest)){ if(!authenticationService.credentialsExists(signUpRequest)){
......
package ntnu.idatt2105.group44.trivioServer.controller; package ntnu.idatt2105.group44.trivioServer.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import ntnu.idatt2105.group44.trivioServer.service.storage.StorageService; import ntnu.idatt2105.group44.trivioServer.service.storage.StorageService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -17,7 +21,8 @@ import org.springframework.web.bind.annotation.RequestHeader; ...@@ -17,7 +21,8 @@ import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
@Tag(name = "FileUpload Controller", description = "These endpoints handle images and stores them"
+ "locally in the resource directory")
@RestController @RestController
@CrossOrigin @CrossOrigin
public class FileUploadController { public class FileUploadController {
...@@ -28,7 +33,19 @@ public class FileUploadController { ...@@ -28,7 +33,19 @@ public class FileUploadController {
public FileUploadController(StorageService storageService) { public FileUploadController(StorageService storageService) {
this.storageService = storageService; this.storageService = storageService;
} }
/**
* POST-method to upload a file.
*
* @param file the file to be uploaded.
* @return a response entity with the file path or bad request status if the file cannot be uploaded.
*/
@Operation(
summary = "Uploads a file",
description = "Takes in a file and copies it into the resource directory")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "File is uploaded into the directory"),
@ApiResponse(responseCode = "400", description = "File is null or unable to be uploaded")
})
@PostMapping("/upload") @PostMapping("/upload")
public ResponseEntity<String> handleFileUpload( public ResponseEntity<String> handleFileUpload(
@RequestBody MultipartFile file) { @RequestBody MultipartFile file) {
...@@ -36,21 +53,9 @@ public class FileUploadController { ...@@ -36,21 +53,9 @@ public class FileUploadController {
String filePath = storageService.saveFile(file); String filePath = storageService.saveFile(file);
return ResponseEntity.ok(filePath); return ResponseEntity.ok(filePath);
} catch (Exception e) { } catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Failed to upload file: " + e.getMessage()); .body("Failed to upload file: " + e.getMessage());
} }
} }
@GetMapping("/media/{imageName}")
public ResponseEntity<Resource> getImage(@PathVariable String imageName)
throws FileNotFoundException {
// Retrieve the image file using the imageName
Resource image = storageService.getFile(imageName);
// Return the image as a response
return ResponseEntity.ok()
.contentType(MediaType.IMAGE_PNG) // Set the appropriate content type
.body(image);
}
} }
package ntnu.idatt2105.group44.trivioServer.controller; package ntnu.idatt2105.group44.trivioServer.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
...@@ -8,7 +12,7 @@ import ntnu.idatt2105.group44.trivioServer.model.Message; ...@@ -8,7 +12,7 @@ import ntnu.idatt2105.group44.trivioServer.model.Message;
import ntnu.idatt2105.group44.trivioServer.dto.UserResponse; import ntnu.idatt2105.group44.trivioServer.dto.UserResponse;
import ntnu.idatt2105.group44.trivioServer.service.MessageService; import ntnu.idatt2105.group44.trivioServer.service.MessageService;
import java.util.List; import java.util.List;
@Tag(name = "Messages", description = "THis API is responsible for messages")
@CrossOrigin @CrossOrigin
@RestController @RestController
@RequestMapping("/messages") @RequestMapping("/messages")
...@@ -20,18 +24,40 @@ public class MessageController { ...@@ -20,18 +24,40 @@ public class MessageController {
public MessageController(MessageService messageService) { public MessageController(MessageService messageService) {
this.messageService = messageService; this.messageService = messageService;
} }
/**
* POST-method to save a message in the database.
*
* @param message the message to be saved.
* @return a response entity with a success message or bad request status.
*/
@Operation(
summary = "Saves message",
description = "Saves message in the database")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Messsage is created")
, @ApiResponse(responseCode = "400", description = "Failed to create message")
})
@PostMapping @PostMapping
public ResponseEntity<UserResponse> createMessage(@RequestBody Message message) { public ResponseEntity<UserResponse> createMessage(@RequestBody Message message) {
try { try {
messageService.createMessage(message); messageService.createMessage(message);
return ResponseEntity.ok(new UserResponse("Message sent. Thanks for feedback!")); return ResponseEntity.ok(new UserResponse("Message sent. Thanks for feedback!"));
} catch (Exception e) { } catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(new UserResponse("Failed to send message. Please try again later.")); .body(new UserResponse("Failed to send message. Please try again later."));
} }
} }
/**
* GET-method to fetch messages from the database.
*
* @return a response entity with a list of messages or bad request status.
*/
@Operation(
summary = "Fetch messages",
description = "Fetches messages from the database")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Messages is retrieved")
})
@GetMapping @GetMapping
public ResponseEntity<List<Message>> getAllMessages() { public ResponseEntity<List<Message>> getAllMessages() {
List<Message> messages = messageService.getAllMessages(); List<Message> messages = messageService.getAllMessages();
......
package ntnu.idatt2105.group44.trivioServer.controller; package ntnu.idatt2105.group44.trivioServer.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List; import java.util.List;
import ntnu.idatt2105.group44.trivioServer.dto.ResultDTO; import ntnu.idatt2105.group44.trivioServer.dto.ResultDTO;
import ntnu.idatt2105.group44.trivioServer.model.Result; import ntnu.idatt2105.group44.trivioServer.model.Result;
...@@ -18,7 +22,8 @@ import org.springframework.web.bind.annotation.RequestHeader; ...@@ -18,7 +22,8 @@ import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@Tag(name = "Messages", description = "Results is the endpoint where the user can retrieve and submit"
+ "their attemps in trivios")
@RestController @RestController
@RequestMapping("results") @RequestMapping("results")
public class ResultController { public class ResultController {
...@@ -29,6 +34,22 @@ public class ResultController { ...@@ -29,6 +34,22 @@ public class ResultController {
this.jwtService = jwtService; this.jwtService = jwtService;
} }
/**
* GET-method to fetch attempts from a chosen user within a chosen trivio.
*
* @param token token to authenticate and identify the user.
* @param title title of the trivio to filter results by.
* @param pageable pageable object for pagination.
* @return a response entity with a page of results or bad request status.
*/
@Operation(
summary = "Fetches attempts from a chosen user within a chosen trivio",
description = "Get results by user ID and optional title."
)
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successful operation"),
@ApiResponse(responseCode = "400", description = "Bad request")
})
@GetMapping() @GetMapping()
public ResponseEntity<Page<Result>> getResultByUserIdAndTitle( public ResponseEntity<Page<Result>> getResultByUserIdAndTitle(
@RequestHeader("Authorization") String token, @RequestHeader("Authorization") String token,
...@@ -48,7 +69,20 @@ public class ResultController { ...@@ -48,7 +69,20 @@ public class ResultController {
return ResponseEntity.badRequest().build(); return ResponseEntity.badRequest().build();
} }
} }
/**
* GET-method to fetch distinct trivio titles associated with the user.
*
* @param token token to authenticate and identify the user.
* @return a response entity with a list of distinct trivio titles or bad request status.
*/
@Operation(
summary = "Get distinct trivio titles",
description = "Fetches distinct trivio titles associated with the user."
)
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Fetches results"),
@ApiResponse(responseCode = "400", description = "Bad request")
})
@GetMapping("/trivioTitles") @GetMapping("/trivioTitles")
public ResponseEntity<List<String>> getDistinctTrivioTitles(@RequestHeader("Authorization") String token) { public ResponseEntity<List<String>> getDistinctTrivioTitles(@RequestHeader("Authorization") String token) {
long userId = Long.parseLong(jwtService.extractSubjectFromHeader(token)); long userId = Long.parseLong(jwtService.extractSubjectFromHeader(token));
...@@ -56,6 +90,20 @@ public class ResultController { ...@@ -56,6 +90,20 @@ public class ResultController {
return ResponseEntity.ok(trivioTitles); return ResponseEntity.ok(trivioTitles);
} }
/**
* POST-method to add a result to the server.
*
* @param resultDTO the result to be added.
* @return a response entity with a success message or bad request status.
*/
@Operation(
summary = "Add a result",
description = "Posts a result to the server."
)
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Result is posted to the database"),
@ApiResponse(responseCode = "400", description = "Bad request")
})
@PostMapping() @PostMapping()
public ResponseEntity<String> postResult(@RequestBody ResultDTO resultDTO) { public ResponseEntity<String> postResult(@RequestBody ResultDTO resultDTO) {
resultService.addResult(resultDTO); resultService.addResult(resultDTO);
......
package ntnu.idatt2105.group44.trivioServer.controller; package ntnu.idatt2105.group44.trivioServer.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.logging.Logger; import java.util.logging.Logger;
...@@ -13,11 +19,13 @@ import org.springframework.data.domain.Page; ...@@ -13,11 +19,13 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@RestController @RestController
@CrossOrigin @CrossOrigin
@RequestMapping("/trivios") @RequestMapping("/trivios")
@Tag(name = "Trivio", description = "Endpoints for managing Trivios")
public class TrivioController { public class TrivioController {
private final TrivioService trivioService; private final TrivioService trivioService;
private final JWTService jwtService; private final JWTService jwtService;
...@@ -28,12 +36,21 @@ public class TrivioController { ...@@ -28,12 +36,21 @@ public class TrivioController {
this.trivioService=trivioService; this.trivioService=trivioService;
this.jwtService=jwtService; this.jwtService=jwtService;
} }
@Operation(summary = "Get all Trivios",
description = "Retrieves all Trivios."
)
@ApiResponses(
@ApiResponse(responseCode = "200", description = "Retrieved all trivios")
)
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping @GetMapping
public List<Trivio> getAllTrivio(){ public List<Trivio> getAllTrivio(){
return trivioService.getAllTrivios(); return trivioService.getAllTrivios();
} }
/** /**
* GET-method to retrieve all trivios by a specific user with filters if necessary. * GET-method to retrieve all trivios by a specific user with filters if necessary.
* @param token token to authenticate and identify the user. * @param token token to authenticate and identify the user.
...@@ -43,8 +60,12 @@ public class TrivioController { ...@@ -43,8 +60,12 @@ public class TrivioController {
* @param pageable page of trivios to retrieve. * @param pageable page of trivios to retrieve.
* @return page with filtered trivios by the specific users. * @return page with filtered trivios by the specific users.
*/ */
@Operation(summary = "Get filtered Trivios by user",
description = "Retrieves filtered Trivios by a specific user.")
@ApiResponse(responseCode = "200", description = "Retrieved filtered trivios")
@GetMapping("/user") @GetMapping("/user")
public ResponseEntity<Page<Trivio>> getFilteredTriviosByUser( public ResponseEntity<Page<Trivio>> getFilteredTriviosByUser(
@Parameter(in = ParameterIn.HEADER, description = "Authorization token", required = true)
@RequestHeader("Authorization") String token, @RequestHeader("Authorization") String token,
@RequestParam(required = false) String category, @RequestParam(required = false) String category,
@RequestParam(required = false) String difficulty, @RequestParam(required = false) String difficulty,
...@@ -75,8 +96,12 @@ public class TrivioController { ...@@ -75,8 +96,12 @@ public class TrivioController {
* @param pageable page of trivios to retrieve. * @param pageable page of trivios to retrieve.
* @return page with filtered public trivios by other users. * @return page with filtered public trivios by other users.
*/ */
@Operation(summary = "Get filtered public Trivios by other users",
description = "Retrieves filtered public Trivios by other users.")
@ApiResponse(responseCode = "200", description = "Retrieved filtered public trivios")
@GetMapping("/discover") @GetMapping("/discover")
public ResponseEntity<Page<Trivio>> getFilteredPublicTriviosByOtherUsers( public ResponseEntity<Page<Trivio>> getFilteredPublicTriviosByOtherUsers(
@Parameter(in = ParameterIn.HEADER, description = "Authorization token", required = true)
@RequestHeader("Authorization") String token, @RequestHeader("Authorization") String token,
@RequestParam(required = false) String category, @RequestParam(required = false) String category,
@RequestParam(required = false) String difficulty, @RequestParam(required = false) String difficulty,
...@@ -99,8 +124,21 @@ public class TrivioController { ...@@ -99,8 +124,21 @@ public class TrivioController {
return new ResponseEntity<>(trivios, HttpStatus.OK); return new ResponseEntity<>(trivios, HttpStatus.OK);
} }
/**
* GET-method to retrieve shared trivios by the user with filters if necessary.
* @param token token to authenticate and identify the user.
* @param category category for filtering the trivios.
* @param difficulty difficulty for filtering the trivios.
* @param tagString tags for filtering the trivios.
* @param pageable page of trivios to retrieve.
* @return page with filtered shared trivios by the user.
*/
@Operation(summary = "Get shared Trivios",
description = "Retrieves shared Trivios by the user.")
@ApiResponse(responseCode = "200", description = "Retrieved shared trivios")
@GetMapping("/shared") @GetMapping("/shared")
public ResponseEntity<Page<Trivio>> getSharedTrivios( public ResponseEntity<Page<Trivio>> getSharedTrivios(
@Parameter(in = ParameterIn.HEADER, description = "Authorization token", required = true)
@RequestHeader("Authorization") String token, @RequestHeader("Authorization") String token,
@RequestParam(required = false) String category, @RequestParam(required = false) String category,
@RequestParam(required = false) String difficulty, @RequestParam(required = false) String difficulty,
...@@ -124,7 +162,6 @@ public class TrivioController { ...@@ -124,7 +162,6 @@ public class TrivioController {
} catch (Exception e) { } catch (Exception e) {
return ResponseEntity.badRequest().build(); return ResponseEntity.badRequest().build();
} }
} }
...@@ -151,9 +188,22 @@ public class TrivioController { ...@@ -151,9 +188,22 @@ public class TrivioController {
// return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); // return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
// } // }
// } // }
/**
@GetMapping(path = "{trivioId}") * GET-method to retrieve a trivio by its ID.
public ResponseEntity<Trivio> getTrivio(@RequestHeader("Authorization") String token, @PathVariable Long trivioId ){ * @param token token to authenticate and identify the user.
* @param trivioId ID of the trivio to retrieve.
* @return the trivio if authorized, otherwise returns unauthorized status.
*/
@Operation(summary = "Get Trivio by ID",
description = "Retrieves a Trivio by its ID.")
@ApiResponse(responseCode = "200", description = "Retrieved trivio")
@ApiResponse(responseCode = "401", description = "Unauthorized")
@GetMapping("/{trivioId}")
public ResponseEntity<Trivio> getTrivio(
@Parameter(in = ParameterIn.HEADER, description = "Authorization token", required = true)
@RequestHeader("Authorization") String token,
@Parameter(description = "Trivio ID", required = true)
@PathVariable Long trivioId) {
try { try {
long userId = Long.parseLong(jwtService.extractSubjectFromHeader(token)); long userId = Long.parseLong(jwtService.extractSubjectFromHeader(token));
Trivio trivio = trivioService.getTrivioById(trivioId); Trivio trivio = trivioService.getTrivioById(trivioId);
...@@ -168,8 +218,22 @@ public class TrivioController { ...@@ -168,8 +218,22 @@ public class TrivioController {
} }
} }
/**
* POST-method to create a new trivio with questions and answers.
* @param token token to authenticate and identify the user.
* @param trivioWithQuestionsAndAnswers TrivioWithQAndA object containing trivio details.
* @return a response entity with a success message or unauthorized status.
*/
@Operation(summary = "Create Trivio with Questions and Answers",
description = "Creates a new Trivio with associated questions and answers.")
@ApiResponse(responseCode = "200", description = "Trivio Created")
@ApiResponse(responseCode = "401", description = "Unauthorized user")
@PostMapping("/create") @PostMapping("/create")
public ResponseEntity<String> addTrivioWithQuestionsAndAnswers(@RequestHeader("Authorization") String token, @RequestBody TrivioWithQAndA trivioWithQuestionsAndAnswers) { public ResponseEntity<String> addTrivioWithQuestionsAndAnswers(
@Parameter(in = ParameterIn.HEADER, description = "Authorization token", required = true)
@RequestHeader("Authorization") String token,
@Parameter(description = "Trivio with Questions and Answers", required = true)
@RequestBody TrivioWithQAndA trivioWithQuestionsAndAnswers) {
try { try {
if (token == null || !token.startsWith("Bearer ")) { if (token == null || !token.startsWith("Bearer ")) {
// Token is missing or invalid format // Token is missing or invalid format
...@@ -186,10 +250,25 @@ public class TrivioController { ...@@ -186,10 +250,25 @@ public class TrivioController {
} }
} }
/**
* PUT-method to edit a trivio with questions and answers.
* @param token token to authenticate and identify the user.
* @param updatedTrivioWithQuestionsAndAnswer Updated TrivioWithQAndA object containing edited trivio details.
* @param trivioId ID of the trivio to be edited.
* @return a response entity with a success message or unauthorized status.
*/
@Operation(summary = "Edit Trivio with Questions and Answers",
description = "Edits an existing Trivio with associated questions and answers.")
@ApiResponse(responseCode = "200", description = "Trivio Updated")
@ApiResponse(responseCode = "400", description = "Bad Request")
@ApiResponse(responseCode = "401", description = "Unauthorized")
@PutMapping("/edit/{trivioId}") @PutMapping("/edit/{trivioId}")
public ResponseEntity<String> editTrivioWithQuestionsAndAnswers( public ResponseEntity<String> editTrivioWithQuestionsAndAnswers(
@Parameter(in = ParameterIn.HEADER, description = "Authorization token", required = true)
@RequestHeader("Authorization") String token, @RequestHeader("Authorization") String token,
@Parameter(description = "Updated Trivio with Questions and Answers", required = true)
@RequestBody TrivioWithQAndA updatedTrivioWithQuestionsAndAnswer, @RequestBody TrivioWithQAndA updatedTrivioWithQuestionsAndAnswer,
@Parameter(description = "ID of the Trivio to be edited", required = true)
@PathVariable long trivioId) { @PathVariable long trivioId) {
try { try {
// Extract user ID from the JWT token // Extract user ID from the JWT token
...@@ -207,7 +286,6 @@ public class TrivioController { ...@@ -207,7 +286,6 @@ public class TrivioController {
logger.severe("Could not update trivio: User is not authorized"); logger.severe("Could not update trivio: User is not authorized");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
} }
} catch (Exception e) { } catch (Exception e) {
// Log the exception // Log the exception
logger.info("An error occurred while updating trivio"); logger.info("An error occurred while updating trivio");
...@@ -216,15 +294,31 @@ public class TrivioController { ...@@ -216,15 +294,31 @@ public class TrivioController {
} }
} }
/**
* PUT-method to add a user to a list that gives them rights to edit a trivio.
* @param token token to authenticate and identify the user.
* @param username username of the user to be added.
* @param trivioId ID of the trivio.
* @return a response entity with a success message or bad request status.
*/
@Operation(summary = "Add User That Can Edit",
description = "Adds a user that can edit a trivio.")
@ApiResponse(responseCode = "200", description = "User added")
@ApiResponse(responseCode = "400", description = "Bad Request")
@PutMapping("/add-user") @PutMapping("/add-user")
public ResponseEntity<String> addUserThatCanEdit(@RequestHeader("Authorization") String token, @RequestParam String username, @RequestParam long trivioId){ public ResponseEntity<String> addUserThatCanEdit(
@Parameter(in = ParameterIn.HEADER, description = "Authorization token", required = true)
@RequestHeader("Authorization") String token,
@Parameter(description = "Username of the user to be added", required = true)
@RequestParam String username,
@Parameter(description = "ID of the trivio", required = true)
@RequestParam long trivioId) {
try { try {
long userId = Long.parseLong(jwtService.extractSubjectFromHeader(token)); long userId = Long.parseLong(jwtService.extractSubjectFromHeader(token));
Trivio trivio = trivioService.getTrivioById(trivioId); Trivio trivio = trivioService.getTrivioById(trivioId);
logger.info(Long.toString(trivio.getUser().getId())); logger.info(Long.toString(trivio.getUser().getId()));
logger.info(Long.toString(userId)); logger.info(Long.toString(userId));
if (userId == trivio.user.getId()) { if (userId == trivio.user.getId()) {
logger.info("i reached here");
trivioService.addUserToTrivio(trivioId, username); trivioService.addUserToTrivio(trivioId, username);
return ResponseEntity.ok("User added!"); return ResponseEntity.ok("User added!");
} }
...@@ -235,8 +329,26 @@ public class TrivioController { ...@@ -235,8 +329,26 @@ public class TrivioController {
} }
} }
/**
* PUT-method to remove a user that can edit a trivio.
* @param token token to authenticate and identify the user.
* @param username username of the user to be removed.
* @param trivioId ID of the trivio.
* @return a response entity with a success message or unauthorized status.
*/
@Operation(summary = "Remove User That Can Edit",
description = "Removes a user that can edit a trivio.")
@ApiResponse(responseCode = "200", description = "User removed")
@ApiResponse(responseCode = "401", description = "Unauthorized")
@ApiResponse(responseCode = "400", description = "Bad Request")
@PutMapping("/remove-user") @PutMapping("/remove-user")
public ResponseEntity<String> removeUserThatCanEdit(@RequestHeader("Authorization") String token, @RequestParam String username, @RequestParam long trivioId){ public ResponseEntity<String> removeUserThatCanEdit(
@Parameter(in = ParameterIn.HEADER, description = "Authorization token", required = true)
@RequestHeader("Authorization") String token,
@Parameter(description = "Username of the user to be removed", required = true)
@RequestParam String username,
@Parameter(description = "ID of the trivio", required = true)
@RequestParam long trivioId) {
try { try {
long userId = Long.parseLong(jwtService.extractSubjectFromHeader(token)); long userId = Long.parseLong(jwtService.extractSubjectFromHeader(token));
Trivio trivio = trivioService.getTrivioById(trivioId); Trivio trivio = trivioService.getTrivioById(trivioId);
...@@ -249,9 +361,22 @@ public class TrivioController { ...@@ -249,9 +361,22 @@ public class TrivioController {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("An error occurred while removing the user: " + e.getMessage()); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("An error occurred while removing the user: " + e.getMessage());
} }
} }
/**
* DELETE-method to delete a trivio.
* @param token token to authenticate and identify the user.
* @param trivioId ID of the trivio to be deleted.
* @return a response entity with a success message or unauthorized status.
*/
@Operation(summary = "Delete Trivio",
description = "Deletes a trivio by its ID.")
@ApiResponse(responseCode = "200", description = "Trivio successfully removed")
@ApiResponse(responseCode = "401", description = "Unauthorized")
@ApiResponse(responseCode = "400", description = "Bad Request")
@DeleteMapping("/delete/{trivioId}") @DeleteMapping("/delete/{trivioId}")
public ResponseEntity<String> deleteTrivio(@RequestHeader("Authorization") String token, public ResponseEntity<String> deleteTrivio(
@Parameter(in = ParameterIn.HEADER, description = "Authorization token", required = true)
@RequestHeader("Authorization") String token,
@Parameter(description = "ID of the trivio to be deleted", required = true)
@PathVariable Long trivioId) { @PathVariable Long trivioId) {
try { try {
if (trivioService.checkIfUserIsOwner(token, trivioId)) { if (trivioService.checkIfUserIsOwner(token, trivioId)) {
...@@ -260,8 +385,7 @@ public class TrivioController { ...@@ -260,8 +385,7 @@ public class TrivioController {
} }
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("User is not authorized!"); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("User is not authorized!");
} catch (Exception e) { } catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("An error occured while deleting trivio" return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("An error occurred while deleting trivio: " + e.getMessage());
+ " "+e.getMessage());
} }
} }
} }
package ntnu.idatt2105.group44.trivioServer.controller; package ntnu.idatt2105.group44.trivioServer.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List; import java.util.List;
import ntnu.idatt2105.group44.trivioServer.model.Question; import ntnu.idatt2105.group44.trivioServer.model.Question;
import ntnu.idatt2105.group44.trivioServer.model.Trivio; import ntnu.idatt2105.group44.trivioServer.model.Trivio;
...@@ -14,7 +18,8 @@ import org.springframework.web.bind.annotation.PostMapping; ...@@ -14,7 +18,8 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@Tag(name = "Trivio Question Controller", description = "Endpoints to retrieve questions for trivios."
+ "This end point is for testing")
@RestController @RestController
@RequestMapping("/trivios") @RequestMapping("/trivios")
public class TrivioQuestionController { public class TrivioQuestionController {
...@@ -27,6 +32,18 @@ public class TrivioQuestionController { ...@@ -27,6 +32,18 @@ public class TrivioQuestionController {
this.questionService = questionService; this.questionService = questionService;
} }
/**
* GET-method to retrieve questions for a trivio.
*
* @param trivioId the ID of the trivio to retrieve questions for.
* @return a response entity with the list of questions for the trivio.
*/
@Operation(
summary = "Get questions for a trivio",
description = "Retrieve questions for a trivio by providing its ID.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Questions retrieved successfully")
})
@GetMapping("{trivioId}/questions") @GetMapping("{trivioId}/questions")
public ResponseEntity<List<Question>> getQuestionForTrivia(@PathVariable Long trivioId){ public ResponseEntity<List<Question>> getQuestionForTrivia(@PathVariable Long trivioId){
Trivio trivio = trivioService.getTrivioById(trivioId); Trivio trivio = trivioService.getTrivioById(trivioId);
......
package ntnu.idatt2105.group44.trivioServer.controller; package ntnu.idatt2105.group44.trivioServer.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List; import java.util.List;
import java.util.logging.Logger; import java.util.logging.Logger;
import ntnu.idatt2105.group44.trivioServer.model.User; import ntnu.idatt2105.group44.trivioServer.model.User;
...@@ -21,6 +26,7 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -21,6 +26,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@Tag(name = "User Controller", description = "Endpoints to manage users")
@CrossOrigin @CrossOrigin
@RestController @RestController
@RequestMapping("/users") @RequestMapping("/users")
...@@ -35,18 +41,53 @@ public class UserController { ...@@ -35,18 +41,53 @@ public class UserController {
this.userService = userService; this.userService = userService;
this.jwtService = jwtService; this.jwtService = jwtService;
} }
/**
* GET-method to retrieve all users.
*
* @return a list of all users.
*/
@Operation(
summary = "Get all users",
description = "Retrieve all users registered in the system. Only administrators can access this endpoint.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Users retrieved successfully")
})
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/all") @GetMapping("/all")
public List<User> getUsers() { public List<User> getUsers() {
return userService.getAllUsers(); return userService.getAllUsers();
} }
/**
* GET-method to retrieve a user by ID.
*
* @param userId ID of the user to retrieve.
* @return the user with the specified ID.
*/
@Operation(
summary = "Get user by ID",
description = "Retrieve a user by their ID. Only administrators can access this endpoint.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "User retrieved successfully")
})
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping(path = "{userId}") @GetMapping(path = "{userId}")
public User getUser(@PathVariable Long userId) { public User getUserById(@Parameter(description = "ID of the user to retrieve", required = true) @PathVariable Long userId) {
return userService.getUserById(userId); return userService.getUserById(userId);
} }
/**
* GET-method to retrieve information of the authenticated user.
*
* @param header Authorization header containing the JWT token.
* @return the authenticated user's information.
*/
@Operation(
summary = "Get user information",
description = "Retrieve information of the authenticated user.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "User information retrieved successfully")
})
@GetMapping() @GetMapping()
public User getUserInfo(@RequestHeader("Authorization") String header) { public User getUserInfo(@RequestHeader("Authorization") String header) {
return userService.getUserById(Long.valueOf(jwtService.extractSubjectFromHeader(header))); return userService.getUserById(Long.valueOf(jwtService.extractSubjectFromHeader(header)));
...@@ -75,10 +116,26 @@ public class UserController { ...@@ -75,10 +116,26 @@ public class UserController {
// } // }
/**
* PUT-method to update user information (username and email).
*
* @param header Authorization header containing the JWT token.
* @param username New username (optional).
* @param email New email (optional).
* @return a response indicating the success or failure of the operation.
*/
@Operation(
summary = "Update user information",
description = "Update user information (username and email).")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Username or email successfully changed"),
@ApiResponse(responseCode = "400", description = "Failed to update user information")
})
@PutMapping("/edit") @PutMapping("/edit")
public ResponseEntity<String> updateUserInfo(@RequestHeader("Authorization") String header, public ResponseEntity<String> updateUserInfo(
@RequestParam(required = false) String username, @RequestHeader("Authorization") String header,
@RequestParam(required = false) String email){ @Parameter(description = "New username (optional)") @RequestParam(required = false) String username,
@Parameter(description = "New email (optional)") @RequestParam(required = false) String email) {
try { try {
String userId = jwtService.extractSubjectFromHeader(header); String userId = jwtService.extractSubjectFromHeader(header);
userService.updateUser(username, email, Long.valueOf(userId)); userService.updateUser(username, email, Long.valueOf(userId));
...@@ -86,9 +143,22 @@ public class UserController { ...@@ -86,9 +143,22 @@ public class UserController {
} catch (RuntimeException err) { } catch (RuntimeException err) {
return ResponseEntity.badRequest().body(err.getMessage()); return ResponseEntity.badRequest().body(err.getMessage());
} }
} }
/**
* PUT-method to update user password.
*
* @param header Authorization header containing the JWT token.
* @param password New password.
* @return a response indicating the success or failure of the operation.
*/
@Operation(
summary = "Update user password",
description = "Update user password.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Password has successfully been changed"),
@ApiResponse(responseCode = "400", description = "Bad request")
})
@PutMapping("/editPassword") @PutMapping("/editPassword")
public ResponseEntity<String> updatePassword(@RequestHeader("Authorization") String header, public ResponseEntity<String> updatePassword(@RequestHeader("Authorization") String header,
@RequestParam(required = false) String password){ @RequestParam(required = false) String password){
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment