Skip to content
Snippets Groups Projects
Commit e5d5e34d authored by Dominika Zemanovičová's avatar Dominika Zemanovičová
Browse files

Merge branch 'M3-enrol-expel-rework' into 'main'

LanguageSchool fixes + enrol expel rework

See merge request !46
parents e502766c e4b28547
No related branches found
No related tags found
1 merge request!46LanguageSchool fixes + enrol expel rework
Pipeline #
Showing
with 204 additions and 81 deletions
package org.fuseri.modulelanguageschool.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
......@@ -19,21 +20,38 @@ public class AppSecurityConfig {
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable();
httpSecurity.authorizeHttpRequests(x -> x
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**","/users/register").permitAll()
.requestMatchers(HttpMethod.POST, "/courses/**").hasAuthority("SCOPE_test_1")
// "/users/register" is for automatic registering upon authentication
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/datainitializer").permitAll()
// PUT
.requestMatchers(HttpMethod.PUT, "/courses/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
// POST
.requestMatchers(HttpMethod.POST, "/courses/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
// PATCH
.requestMatchers(HttpMethod.PATCH, "/courses/enrolStudent/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
.requestMatchers(HttpMethod.PATCH, "/courses/expelStudent/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
// DELETE
.requestMatchers(HttpMethod.DELETE, "/courses/**").hasAuthority("SCOPE_test_1")
.requestMatchers(HttpMethod.PUT, "/courses/**").hasAnyAuthority("SCOPE_test_1","SCOPE_test_2")
.requestMatchers(HttpMethod.GET, "/courses/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
// PUT
.requestMatchers(HttpMethod.PUT, "/lectures/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
// POST
.requestMatchers(HttpMethod.POST, "/lectures/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
// PATCH
.requestMatchers(HttpMethod.PATCH, "/lectures/setLecturer/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
.requestMatchers(HttpMethod.PATCH, "/lectures/enrolStudent/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
.requestMatchers(HttpMethod.PATCH, "/lectures/expelStudent/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
// DELETE
.requestMatchers(HttpMethod.DELETE, "/lectures/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
.requestMatchers(HttpMethod.PUT, "/lectures/**").hasAnyAuthority("SCOPE_test_1","SCOPE_test_2")
.requestMatchers(HttpMethod.GET, "/lectures/**").hasAnyAuthority("SCOPE_test_1", "SCOPE_test_2")
.requestMatchers(HttpMethod.POST, "/users/**").hasAuthority("SCOPE_test_1")
// PUT
.requestMatchers(HttpMethod.PUT, "/users/**").hasAuthority("SCOPE_test_1")
// POST
.requestMatchers(HttpMethod.POST, "/users").hasAuthority("SCOPE_test_1")
.requestMatchers(HttpMethod.POST, "/users/").hasAuthority("SCOPE_test_1")
// DELETE
.requestMatchers(HttpMethod.DELETE, "/users/**").hasAuthority("SCOPE_test_1")
.anyRequest().authenticated()
).oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken)
......
package org.fuseri.modulelanguageschool.course;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
......@@ -18,6 +19,8 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal;
import org.springframework.web.bind.annotation.*;
import java.util.List;
......@@ -44,7 +47,7 @@ public class CourseController {
* @param dto the CourseCreateDto containing the course data
* @return the newly created CourseDto
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Create a new course")
@PostMapping
@ApiResponses({
......@@ -68,7 +71,7 @@ public class CourseController {
@ApiResponse(code = 200, message = "Course found"),
@ApiResponse(code = 404, message = "Course not found")
})
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1","test_2"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
public ResponseEntity<CourseDto> find(@PathVariable Long id) {
CourseDto courseDto = courseFacade.findById(id);
return ResponseEntity.ok(courseDto);
......@@ -80,8 +83,7 @@ public class CourseController {
* @param page the page number to retrieve
* @return the Result containing the requested page of CourseDtos
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1","test_2"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Retrieve a paginated list of courses")
@GetMapping("/findAll")
@ApiResponses(value = {
......@@ -99,7 +101,7 @@ public class CourseController {
* @param lang the language to find courses of
* @return the Result containing the requested page of CourseDtos
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1","test_2"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Retrieve a paginated list of courses of a given language")
@GetMapping("/findAllByLang")
@ApiResponses({
......@@ -118,7 +120,7 @@ public class CourseController {
* @param prof the proficiency of the language
* @return the Result containing the requested page of CourseDtos
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1","test_2"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Retrieve a paginated list of courses of a given language and proficiency")
@GetMapping("/findAllByLangProf")
@ApiResponses({
......@@ -138,7 +140,7 @@ public class CourseController {
* @param dto the CourseCreateDto containing the updated course data
* @return the updated CourseDto
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1","test_2"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Update an existing course")
@PutMapping("/update/{id}")
@ApiResponses({
......@@ -162,7 +164,7 @@ public class CourseController {
@ApiResponse(code = 204, message = "Course deleted successfully"),
@ApiResponse(code = 404, message = "Course not found")
})
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
public ResponseEntity<Void> delete(@PathVariable Long id) {
courseFacade.delete(id);
return ResponseEntity.noContent().build();
......@@ -171,13 +173,13 @@ public class CourseController {
/**
* Adds student to the existing course
*
* @param id id of course to update
* @param studentId UserDto for the student
* @param id id of course to update
* @param studentId id of the student
* @return the CourseDto representing the updated course
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1","test_2"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Add student to the existing course")
@PatchMapping("/enrol/{id}")
@PatchMapping("/enrolStudent/{id}")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully enrolled student in course"),
@ApiResponse(code = 404, message = "Course not found")
......@@ -187,24 +189,60 @@ public class CourseController {
return ResponseEntity.ok(updatedCourse);
}
/**
* Adds currently signed-in student to the existing course
*
* @param id id of lecture to update
* @param principal http request received with user email
* @return the CourseDto representing the updated course
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Add me to the existing course")
@PatchMapping("/enrol/{id}")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully enrolled student in course"),
@ApiResponse(code = 404, message = "Course not found")
})
public ResponseEntity<CourseDto> enrol(@PathVariable Long id, @AuthenticationPrincipal OAuth2IntrospectionAuthenticatedPrincipal principal) throws JsonProcessingException {
String email = principal.getSubject();
return ResponseEntity.ok(courseFacade.enrol(id, email));
}
/**
* Removes student from the existing course
*
* @param id id of lecture to update
* @param studentId UserDto for the student
* @param id id of lecture to update
* @param studentId ID of the student
* @return the CourseDto representing the updated course
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1","test_2"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Remove student from the existing course")
@PatchMapping("/expel/{id}")
@PatchMapping("/expelStudent/{id}")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully expelled student from course"),
@ApiResponse(code = 404, message = "Course not found")
})
public ResponseEntity<CourseDto> expel(@PathVariable Long id, @RequestParam Long studentId) {
return ResponseEntity.ok(courseFacade.expel(id, studentId));
}
CourseDto updatedCourse = courseFacade.expel(id, studentId);
return ResponseEntity.ok(updatedCourse);
/**
* Removes currently signed-in student from the existing course
*
* @param id id of lecture to update
* @param principal http request received with user email
* @return the CourseDto representing the updated course
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Remove me from the existing course")
@PatchMapping("/expel/{id}")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully expelled student in course"),
@ApiResponse(code = 404, message = "Course not found")
})
public ResponseEntity<CourseDto> expel(@PathVariable Long id, @AuthenticationPrincipal OAuth2IntrospectionAuthenticatedPrincipal principal) throws JsonProcessingException {
String email = principal.getSubject();
return ResponseEntity.ok(courseFacade.expel(id, email));
}
}
package org.fuseri.modulelanguageschool.course;
import jakarta.persistence.EntityNotFoundException;
import org.fuseri.model.dto.course.CourseCreateDto;
import org.fuseri.model.dto.course.CourseDto;
import org.fuseri.model.dto.course.LanguageTypeDto;
......@@ -70,8 +71,20 @@ public class CourseFacade {
return courseMapper.mapToDto(courseService.enrol(id, student));
}
public CourseDto enrol(Long id, String email) {
var student = userService.findUserByEmail(email)
.orElseThrow(() -> new EntityNotFoundException("User with " + email + " email not found."));
return courseMapper.mapToDto(courseService.enrol(id, student));
}
public CourseDto expel(Long id, Long studentId) {
var student = userService.find(studentId);
return courseMapper.mapToDto(courseService.expel(id, student));
}
public CourseDto expel(Long id, String email) {
var student = userService.findUserByEmail(email)
.orElseThrow(() -> new EntityNotFoundException("User with " + email + " email not found."));
return courseMapper.mapToDto(courseService.expel(id, student));
}
}
package org.fuseri.modulelanguageschool.lecture;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
......@@ -13,6 +14,8 @@ import org.fuseri.modulelanguageschool.ModuleLanguageSchoolApplication;
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.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal;
import org.springframework.web.bind.annotation.*;
import java.util.List;
......@@ -40,6 +43,7 @@ public class LectureController {
* @param lecture the LectureDto representing the lecture to be created
* @return the LectureDto representing the newly created lecture
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Create a new lecture")
@PostMapping
@ApiResponses(value = {
......@@ -58,7 +62,7 @@ public class LectureController {
* @return the LectureDto representing the found lecture
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1","test_2"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Retrieve a lecture by its ID")
@GetMapping("find/{courseId}")
@ApiResponses(value = {
......@@ -76,7 +80,7 @@ public class LectureController {
* @param courseId the course to retrieve lectures from
* @return the list of LectureDtos
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1","test_2"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Retrieve a list of lectures for the corresponding course")
@GetMapping("/findByCourse")
@ApiResponses(value = {
......@@ -93,7 +97,7 @@ public class LectureController {
* @param lecture the CourseCreateDto representing the updated lecture
* @return the LectureDto representing the updated lecture
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1","test_2"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Update an existing lecture")
@PutMapping("/update/{id}")
@ApiResponses(value = {
......@@ -110,7 +114,7 @@ public class LectureController {
*
* @param id the ID of the lecture to delete
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1","test_2"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Delete a lecture by its ID")
@DeleteMapping("/delete/{id}")
@ApiResponses(value = {
......@@ -130,7 +134,7 @@ public class LectureController {
* @param lecturerId UserDto for the course lecturer
* @return the LectureDto representing the updated lecture
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1","test_2"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Add lecturer to the existing lecture")
@PatchMapping("/setLecturer/{id}")
@ApiResponses(value = {
......@@ -149,18 +153,36 @@ public class LectureController {
* @param studentId id for the course student
* @return the LectureDto representing the updated lecture
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1","test_2"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Add student to the existing lecture")
@PatchMapping("/enrol/{id}")
@PatchMapping("/enrolStudent/{id}")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "The lecture has been successfully updated"),
@ApiResponse(code = 400, message = "The request body is invalid"),
@ApiResponse(code = 404, message = "The lecture with the specified ID does not exist")
})
public ResponseEntity<LectureDto> enrol(@PathVariable Long id, @RequestParam Long studentId) {
return ResponseEntity.ok(lectureFacade.enrol(id, studentId));
}
/**
* Adds student to the existing lecture resource
*
* @param id id of lecture to update
* @param principal http request received with user email
* @return the LectureDto representing the updated lecture
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Add me to the existing lecture")
@PatchMapping("/enrol/{id}")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "The lecture has been successfully updated"),
@ApiResponse(code = 404, message = "The lecture with the specified ID does not exist")
})
public ResponseEntity<LectureDto> enrol(@PathVariable Long id, @AuthenticationPrincipal OAuth2IntrospectionAuthenticatedPrincipal principal) throws JsonProcessingException {
String email = principal.getSubject();
return ResponseEntity.ok(lectureFacade.enrol(id, email));
}
/**
* Removes student from the existing lecture resource
*
......@@ -168,15 +190,33 @@ public class LectureController {
* @param studentId id for the course student
* @return the LectureDto representing the updated lecture
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1","test_2"}))
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Remove student from the existing lecture")
@PatchMapping("/expel/{id}")
@PatchMapping("/expelStudent/{id}")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "The lecture has been successfully updated"),
@ApiResponse(code = 400, message = "The request body is invalid"),
@ApiResponse(code = 404, message = "The lecture with the specified ID does not exist")
})
public ResponseEntity<LectureDto> expel(@PathVariable Long id, @RequestParam Long studentId) {
return ResponseEntity.ok(lectureFacade.expel(id, studentId));
}
/**
* Removes student from the existing lecture resource
*
* @param id id of lecture to update
* @param principal http request received with user email
* @return the LectureDto representing the updated lecture
*/
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME))
@ApiOperation(value = "Remove me from the existing lecture")
@PatchMapping("/expel/{id}")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "The lecture has been successfully updated"),
@ApiResponse(code = 404, message = "The lecture with the specified ID does not exist")
})
public ResponseEntity<LectureDto> expel(@PathVariable Long id, @AuthenticationPrincipal OAuth2IntrospectionAuthenticatedPrincipal principal) throws JsonProcessingException {
String email = principal.getSubject();
return ResponseEntity.ok(lectureFacade.expel(id, email));
}
}
\ No newline at end of file
package org.fuseri.modulelanguageschool.lecture;
import jakarta.persistence.EntityNotFoundException;
import org.fuseri.model.dto.course.LanguageTypeDto;
import org.fuseri.model.dto.course.ProficiencyLevelDto;
import org.fuseri.model.dto.lecture.LectureCreateDto;
......@@ -70,16 +71,28 @@ public class LectureFacade {
return lectureMapper.mapToList(lectureService.findAll(Language.valueOf(lang.name()), ProficiencyLevel.valueOf(prof.name())));
}
public LectureDto enrol(Long id, long studentId) {
public LectureDto enrol(Long id, Long studentId) {
var student = userService.find(studentId);
return lectureMapper.mapToDto(lectureService.enrol(id, student));
}
public LectureDto enrol(Long id, String email) {
var student = userService.findUserByEmail(email)
.orElseThrow(() -> new EntityNotFoundException("User with " + email + " email not found."));
return lectureMapper.mapToDto(lectureService.enrol(id, student));
}
public LectureDto expel(Long id, Long studentId) {
var student = userService.find(studentId);
return lectureMapper.mapToDto(lectureService.expel(id, student));
}
public LectureDto expel(Long id, String email) {
var student = userService.findUserByEmail(email)
.orElseThrow(() -> new EntityNotFoundException("User with " + email + " email not found."));
return lectureMapper.mapToDto(lectureService.expel(id, student));
}
public LectureDto setLecturer(Long id, Long lecturerId) {
var lecturer = userService.find(lecturerId);
return lectureMapper.mapToDto(lectureService.setLecturer(id, lecturer));
......
......@@ -19,9 +19,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
......@@ -35,8 +34,8 @@ public class UserController {
this.facade = facade;
}
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {})
,summary = "Get a user by Id", description = "Returns a user with specified Id")
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME)
, summary = "Get a user by Id", description = "Returns a user with specified Id")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "User with the specified Id is retrieved Successfuly",
content = @Content(schema = @Schema(implementation = UserDto.class)
......@@ -44,7 +43,7 @@ public class UserController {
@ApiResponse(responseCode = "404", description = "User with the specified ID was not found.")
})
@GetMapping("/{id}")
public ResponseEntity<UserDto> find(@PathVariable @NotNull Long id,@AuthenticationPrincipal OAuth2IntrospectionAuthenticatedPrincipal principal) {
public ResponseEntity<UserDto> find(@PathVariable @NotNull Long id) {
try {
return ResponseEntity.ok(facade.find(id));
} catch (EntityNotFoundException e) {
......@@ -52,20 +51,20 @@ public class UserController {
}
}
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1"})
,summary = "Create a User", description = "Creates a new User.")
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME)
, summary = "Create a User", description = "Creates a new User.")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "User created successfully."),
@ApiResponse(responseCode = "400", description = "Invalid input.")
})
@PostMapping
public ResponseEntity<UserDto> create(@Valid @RequestBody UserCreateDto dto,@AuthenticationPrincipal OAuth2IntrospectionAuthenticatedPrincipal principal) {
public ResponseEntity<UserDto> create(@Valid @RequestBody UserCreateDto dto) {
UserDto user = facade.create(dto);
return ResponseEntity.status(HttpStatus.CREATED).body(user);
}
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {"test_1"})
,summary = "Delete a User with specified ID", description = "Deletes a User with the specified ID.")
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME)
, summary = "Delete a User with specified ID", description = "Deletes a User with the specified ID.")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "User with the specified ID deleted successfully."),
})
......@@ -75,8 +74,8 @@ public class UserController {
return ResponseEntity.noContent().build();
}
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {})
,summary = "Update a User", description = "Updates a User with the specified ID.")
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME)
, summary = "Update a User", description = "Updates a User with the specified ID.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "User with the specified ID updated successfully."),
@ApiResponse(responseCode = "400", description = "Invalid input."),
......@@ -91,7 +90,7 @@ public class UserController {
}
}
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {}),
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME),
summary = "Get Users in paginated format", description = "Returns Users in paginated format.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully retrieved paginated Users"),
......@@ -112,7 +111,8 @@ public class UserController {
}
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {}),summary = "get finished courses", description = "retrieves finished courses of user with given Id")
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME),
summary = "get finished courses", description = "retrieves finished courses of user with given Id")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully retrieved finished courses"),
@ApiResponse(responseCode = "400", description = "Invalid input")
......@@ -122,8 +122,8 @@ public class UserController {
return ResponseEntity.ok(facade.getFinished(id));
}
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {})
,summary = "get enrolled courses", description = "retrieves currently enrolled courses of user with given Id")
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME),
summary = "get enrolled courses", description = "retrieves currently enrolled courses of user with given Id")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully retrieved enrolled courses"),
@ApiResponse(responseCode = "400", description = "Invalid input")
......@@ -133,7 +133,7 @@ public class UserController {
return ResponseEntity.ok(facade.getEnrolled(id));
}
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME,scopes = {}),
@Operation(security = @SecurityRequirement(name = ModuleLanguageSchoolApplication.SECURITY_SCHEME_NAME),
summary = "adds a language", description = "adds a new language and proficiency to user")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully added a language"),
......
package org.fuseri.modulelanguageschool.user;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.EntityNotFoundException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Getter;
import org.fuseri.modulelanguageschool.common.DomainService;
import org.fuseri.modulelanguageschool.common.UserWithEmailAlreadyExists;
......@@ -10,7 +14,9 @@ import org.fuseri.modulelanguageschool.course.ProficiencyLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.NativeWebRequest;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
......@@ -61,4 +67,5 @@ public class UserService extends DomainService<User> {
throw new EntityNotFoundException("User '" + id + "' not found.");
}
}
}
......@@ -232,7 +232,7 @@ public class CourseControllerTest {
Mockito.when(courseFacade.enrol(ArgumentMatchers.anyLong(),
ArgumentMatchers.anyLong())).thenReturn(courseDtoWithStudent);
mockMvc.perform(patch("/courses/enrol/" + id).param("studentId", String.valueOf(1L))
mockMvc.perform(patch("/courses/enrolStudent/" + id).param("studentId", String.valueOf(1L))
.content(asJsonString(student))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
......@@ -245,7 +245,7 @@ public class CourseControllerTest {
@WithMockUser(authorities = {"SCOPE_test_1"})
@Test
void enrolCourseWithoutUserParameter() throws Exception {
mockMvc.perform(patch("/courses/enrol/" + 0L))
mockMvc.perform(patch("/courses/enrolStudent/" + 0L))
.andExpect(status().is4xxClientError());
}
......@@ -272,7 +272,7 @@ public class CourseControllerTest {
UserDto student = new UserDto("novakovat", "novakova@gamil.com", "Tereza",
"Nováková",new HashMap<>());
mockMvc.perform(patch("/courses/expel/" + id)
mockMvc.perform(patch("/courses/expelStudent/" + id)
.param("studentId","0")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
......@@ -286,7 +286,7 @@ public class CourseControllerTest {
@WithMockUser(authorities = {"SCOPE_test_1"})
@Test
void expelCourseWithoutUserParameter() throws Exception {
mockMvc.perform(patch("/courses/expel/" + 0L))
mockMvc.perform(patch("/courses/expelStudent/" + 0L))
.andExpect(status().is4xxClientError());
}
......
......@@ -216,7 +216,7 @@ public class LectureControllerTest {
.thenReturn(lectureDto);
UserDto student = new UserDto("novakovat", "novakova@gamil.com", "Tereza",
"Nováková",new HashMap<>());
mockMvc.perform(patch("/lectures/enrol/{id}", id)
mockMvc.perform(patch("/lectures/enrolStudent/{id}", id)
.param("studentId","0")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
......@@ -244,7 +244,7 @@ public class LectureControllerTest {
.thenReturn(lectureDto);
UserDto student = new UserDto("novakovat", "novakova@gamil.com", "Tereza",
"Nováková",new HashMap<>());
mockMvc.perform(patch("/lectures/expel/" + id)
mockMvc.perform(patch("/lectures/expelStudent/" + id)
.param("studentId","0")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
......
......@@ -5,11 +5,9 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import org.fuseri.model.dto.course.CourseDto;
import org.fuseri.model.dto.course.LanguageTypeDto;
import org.fuseri.model.dto.course.ProficiencyLevelDto;
import org.fuseri.model.dto.exercise.QuestionCreateDto;
import org.fuseri.model.dto.user.UserAddLanguageDto;
import org.fuseri.model.dto.user.UserCreateDto;
import org.fuseri.model.dto.user.UserDto;
import org.fuseri.model.dto.user.UserLoginDto;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
......@@ -40,21 +38,17 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@AutoConfigureMockMvc
class UserControllerTest {
private final UserCreateDto USER_CREATE_DTO = new UserCreateDto(
"xnovak", "xnovak@emample.com", "Peter", "Novak");
private final UserDto USER_DTO = new UserDto(
"xnovak", "xnovak@emample.com", "Peter", "Novak", new HashMap<>());
@Autowired
private ObjectMapper objectMapper;
@Autowired
private MockMvc mockMvc;
@MockBean
private UserFacade userFacade;
private final UserCreateDto USER_CREATE_DTO = new UserCreateDto(
"xnovak", "xnovak@emample.com", "Peter", "Novak");
private final UserDto USER_DTO = new UserDto(
"xnovak", "xnovak@emample.com", "Peter", "Novak",new HashMap<>());
private static Stream<UserCreateDto> invalidUsers() {
return Stream.of(
new UserCreateDto("", "xnovak@emample.com", "Peter", "Novak"),
......@@ -68,6 +62,10 @@ class UserControllerTest {
);
}
private static String asJsonString(final Object obj) throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(obj);
}
@WithMockUser(authorities = {"SCOPE_test_1"})
@Test
void createUser() throws Exception {
......@@ -120,7 +118,7 @@ class UserControllerTest {
.andExpect(status().isNoContent());
}
@WithMockUser(authorities = {})
@WithMockUser(authorities = {"SCOPE_test_1"})
@Test
void update() throws Exception {
Long id = 1L;
......@@ -138,7 +136,7 @@ class UserControllerTest {
Long id = 1L;
String name = "History Spanish";
List<CourseDto> courses = List.of(
new CourseDto( name, 10, LanguageTypeDto.SPANISH, ProficiencyLevelDto.B2)
new CourseDto(name, 10, LanguageTypeDto.SPANISH, ProficiencyLevelDto.B2)
);
Mockito.when(userFacade.getFinished(id)).thenReturn(courses);
mockMvc.perform(get("/users/{id}/finished-courses", 1L))
......@@ -162,7 +160,7 @@ class UserControllerTest {
.andExpect(jsonPath("$[0].name", equalTo(name)));
}
@WithMockUser(authorities = {})
@WithMockUser(authorities = {"SCOPE_test_1"})
@Test
void addLanguage() throws Exception {
Long id = 1L;
......@@ -172,14 +170,10 @@ class UserControllerTest {
UserDto userWithLanguages = USER_DTO;
userWithLanguages.setLanguageProficiency(Map.of(language, proficiency));
Mockito.when(userFacade.addLanguageProficiency(ArgumentMatchers.isA(Long.class),ArgumentMatchers.isA(UserAddLanguageDto.class))).thenReturn(userWithLanguages);
Mockito.when(userFacade.addLanguageProficiency(ArgumentMatchers.isA(Long.class), ArgumentMatchers.isA(UserAddLanguageDto.class))).thenReturn(userWithLanguages);
mockMvc.perform(put("/users/{id}/languages", id)
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(languageDto)))
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(languageDto)))
.andExpect(status().isOk());
}
private static String asJsonString(final Object obj) throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(obj);
}
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment