Added UserRepositoryTest and users/admin users/deanery

Signed-off-by: Marcin Woźniak <y0rune@aol.com>
This commit is contained in:
Marcin Woźniak 2020-12-27 13:54:33 +01:00
parent da4e683248
commit 817350e85e
Signed by: y0rune
GPG Key ID: F204C385F57EB348
6 changed files with 211 additions and 5 deletions

5
.gitignore vendored
View File

@ -33,4 +33,7 @@ build/
### Python ### ### Python ###
__pycache__ __pycache__
.pytest_cache .pytest_cache
### Parser ###
parser/

View File

@ -35,9 +35,12 @@ import org.springframework.stereotype.Repository;
@Repository @Repository
public interface UserRepository extends JpaRepository<User, Long> { public interface UserRepository extends JpaRepository<User, Long> {
@Query("FROM User WHERE email = ?1") @Query("FROM User WHERE email = ?1 OR usosId = ?1")
Optional<User> getByAuthority(@Param("authority") String authority); Optional<User> getByAuthority(@Param("authority") String authority);
@Query("FROM User WHERE email = ?1")
Optional<User> getByEmail(@Param("authority") String authority);
@Query("FROM User WHERE refreshToken = ?1") @Query("FROM User WHERE refreshToken = ?1")
Optional<User> getByRefreshToken(@Param("refreshToken") String refreshToken); Optional<User> getByRefreshToken(@Param("refreshToken") String refreshToken);

View File

@ -30,7 +30,7 @@ public class UserService {
public User checkForUser(String email, String usosId, UserRoles roleIfNotExist) { public User checkForUser(String email, String usosId, UserRoles roleIfNotExist) {
if (usosId == null) { if (usosId == null) {
Optional<User> user = this.repo.getByAuthority(email.replace("\n", "").trim()); Optional<User> user = this.repo.getByEmail(email.replace("\n", "").trim());
if (user.isPresent()) { if (user.isPresent()) {
return user.get(); return user.get();
} else { } else {
@ -64,11 +64,15 @@ public class UserService {
} }
public User getUserByEmail(String email) throws UserNotFoundException { public User getUserByEmail(String email) throws UserNotFoundException {
return this.repo.getByAuthority(email.replace("\n", "").trim()) return this.repo.getByEmail(email.replace("\n", "").trim())
.orElseThrow(() -> new UserNotFoundException("Cannot find user with given authority")); .orElseThrow(() -> new UserNotFoundException("Cannot find user with given authority"));
} }
public Optional<User> getByAuthority(String authority) {
return this.repo.getByAuthority(authority);
}
public Optional<User> getByToken(String token) { public Optional<User> getByToken(String token) {
return this.repo.getByToken(token); return this.repo.getByToken(token);
} }

View File

@ -0,0 +1,52 @@
package com.plannaplan.repositories;
import static org.junit.Assert.assertTrue;
import java.util.Optional;
import com.plannaplan.entities.User;
import com.plannaplan.services.UserService;
import com.plannaplan.types.UserRoles;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
public class UserRepositoryTest {
@Autowired
private UserService userService;
@Autowired
private UserRepository userRepository;
@Test
public void shouldReturnByAuthorityWithGivenEmail(){
final String email = "shouldReturnByAuthorityWithGivenEmail@UserRepository.Test";
final String usosId = "45678";
final User user = this.userService.save(new User("shouldReturnByAuthority", "WithGivenEmail", email, usosId, UserRoles.TEST_USER));
final Optional<User> response = this.userRepository.getByAuthority(email);
assertTrue(response.get().getEmail().equals(email));
assertTrue(response.get().getUsosId().equals(usosId));
assertTrue(response.get().getId().equals(user.getId()));
}
@Test
public void shouldReturnByAuthorityWithUsosId(){
final String email = "shouldReturnByAuthorityWithUsosId@UserRepository.Test";
final String usosId = "45678";
final User user = this.userService.save(new User("shouldReturnByAuthority", "WithGivenEmail", email, usosId, UserRoles.TEST_USER));
final Optional<User> response = this.userRepository.getByAuthority(usosId);
assertTrue(response.get().getEmail().equals(email));
assertTrue(response.get().getUsosId().equals(usosId));
assertTrue(response.get().getId().equals(user.getId()));
}
}

View File

@ -1,12 +1,14 @@
package com.plannaplan.controllers; package com.plannaplan.controllers;
import java.util.List; import java.util.List;
import java.util.Optional;
import com.plannaplan.App; import com.plannaplan.App;
import com.plannaplan.entities.User; import com.plannaplan.entities.User;
import com.plannaplan.responses.mappers.UserResponseMappers; import com.plannaplan.responses.mappers.UserResponseMappers;
import com.plannaplan.responses.models.UserResponse; import com.plannaplan.responses.models.UserResponse;
import com.plannaplan.services.UserService; import com.plannaplan.services.UserService;
import com.plannaplan.types.UserRoles;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
@ -21,6 +23,7 @@ import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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;
@ -51,4 +54,26 @@ public class UsersController {
final List<UserResponse> response = UserResponseMappers.mapToDefaultResponse(searches); final List<UserResponse> response = UserResponseMappers.mapToDefaultResponse(searches);
return new ResponseEntity<>(response, HttpStatus.OK); return new ResponseEntity<>(response, HttpStatus.OK);
} }
}
@PostMapping(path = "/admin")
@PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation(value = "Adds new admin user.")
public ResponseEntity<String> addAdmin(@RequestParam("authority") @ApiParam(value = "USOS ID or E-mail. If user does not exist it should be USOS ID") String authority) {
final Optional<User> userResponse = this.userService.getByAuthority(authority);
final User user = userResponse.orElseGet(() -> new User(null, null, null, authority, UserRoles.ADMIN));
user.setRole(UserRoles.ADMIN);
this.userService.save(user);
return new ResponseEntity<>("Success", HttpStatus.OK);
}
@PostMapping(path = "/deanery")
@PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation(value = "Adds new deanery user.")
public ResponseEntity<String> addDeanery(@RequestParam("authority") @ApiParam(value = "USOS ID or E-mail. If user does not exist it should be USOS ID") String authority) {
final Optional<User> userResponse = this.userService.getByAuthority(authority);
final User user = userResponse.orElseGet(() -> new User(null, null, null, authority, UserRoles.DEANERY));
user.setRole(UserRoles.DEANERY);
this.userService.save(user);
return new ResponseEntity<>("Success", HttpStatus.OK);
}
}

View File

@ -14,9 +14,13 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.junit.Assert.assertTrue;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Optional;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest @SpringBootTest
@ContextConfiguration @ContextConfiguration
@ -24,6 +28,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
public class UsersControllerTest extends AbstractControllerTest { public class UsersControllerTest extends AbstractControllerTest {
private static final String SEARCH_ENDPOINT = "/api/v1/users/student/search"; private static final String SEARCH_ENDPOINT = "/api/v1/users/student/search";
private static final String ALL_USERS_ENDPOINT = "/api/v1/users/students"; private static final String ALL_USERS_ENDPOINT = "/api/v1/users/students";
private static final String ADD_ADMIN_ENDPOINT = "/api/v1/users/admin";
private static final String ADD_DEANERY_ENDPOINT = "/api/v1/users/deanery";
@Autowired @Autowired
private UserService service; private UserService service;
@ -87,4 +93,117 @@ public class UsersControllerTest extends AbstractControllerTest {
.andExpect(status().is4xxClientError()); .andExpect(status().is4xxClientError());
} }
@Test
public void shouldDenyNewAdminWithWrongRole() throws Exception {
final String email = "shouldDenyNewAdminWithWrongRole@shouldDenyAllStudentsTryByStudent.test";
final User user = this.service.save(new User(null, null, email, UserRoles.TEST_USER));
final String token = this.service.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(ADD_ADMIN_ENDPOINT).param("authority","45611").header("Authorization", "Bearer " + token))
.andExpect(status().is4xxClientError());
}
@Test
public void shouldDenyNewAdminWithNoParams() throws Exception {
final String email = "shouldDenyNewAdminWithNoParams@shouldDenyAllStudentsTryByStudent.test";
final User user = this.service.save(new User(null, null, email, UserRoles.ADMIN));
final String token = this.service.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(ADD_ADMIN_ENDPOINT).header("Authorization", "Bearer " + token))
.andExpect(status().is4xxClientError());
}
@Test
public void shouldCreateNewAdmin() throws Exception {
final String email = "shouldCreateNewAdmin@shouldDenyAllStudentsTryByStudent.test";
final String usosId = "121321";
final User user = this.service.save(new User(null, null, email, UserRoles.ADMIN));
final String token = this.service.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(ADD_ADMIN_ENDPOINT).param("authority",usosId).header("Authorization", "Bearer " + token))
.andExpect(status().isOk());
final Optional<User> reponse = this.service.getByAuthority(usosId);
assertTrue(reponse.get().getUsosId().equals(usosId));
}
@Test
public void shouldChangeExistingUserIntoAdmin() throws Exception {
final String email = "shouldChangeExistingUserIntoAdmin@shouldDenyAllStudentsTryByStudent.test";
final String email2 = "shouldChangeExistingUserIntoAdmin2@shouldDenyAllStudentsTryByStudent.test";
final String usosId = "121327";
final User user = this.service.save(new User(null, null, email, UserRoles.ADMIN));
this.service.save(new User(null, null, email2, usosId, UserRoles.TEST_USER));
final String token = this.service.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(ADD_ADMIN_ENDPOINT).param("authority",usosId).header("Authorization", "Bearer " + token))
.andExpect(status().isOk());
final Optional<User> reponse = this.service.getByAuthority(usosId);
assertTrue(reponse.get().getUsosId().equals(usosId));
assertTrue(reponse.get().getRole().equals(UserRoles.ADMIN));
}
@Test
public void shouldDenyNewDeaneryWithWrongRole() throws Exception {
final String email = "shouldDenyNewDeaneryWithWrongRole@shouldDenyAllStudentsTryByStudent.test";
final User user = this.service.save(new User(null, null, email, UserRoles.TEST_USER));
final String token = this.service.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(ADD_DEANERY_ENDPOINT).param("authority","45611").header("Authorization", "Bearer " + token))
.andExpect(status().is4xxClientError());
}
@Test
public void shouldDenyNewDeaneryWithNoParams() throws Exception {
final String email = "shouldDenyNewDeaneryWithNoParams@shouldDenyAllStudentsTryByStudent.test";
final User user = this.service.save(new User(null, null, email, UserRoles.ADMIN));
final String token = this.service.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(ADD_DEANERY_ENDPOINT).header("Authorization", "Bearer " + token))
.andExpect(status().is4xxClientError());
}
@Test
public void shouldCreateNewDeanery() throws Exception {
final String email = "shouldCreateNewDeanery@shouldDenyAllStudentsTryByStudent.test";
final String usosId = "121322";
final User user = this.service.save(new User(null, null, email, UserRoles.ADMIN));
final String token = this.service.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(ADD_DEANERY_ENDPOINT).param("authority",usosId).header("Authorization", "Bearer " + token))
.andExpect(status().isOk());
final Optional<User> reponse = this.service.getByAuthority(usosId);
assertTrue(reponse.get().getUsosId().equals(usosId));
}
@Test
public void shouldChangeExistingUserIntoDeanery() throws Exception {
final String email = "shouldChangeExistingUserIntoDeanery@shouldDenyAllStudentsTryByStudent.test";
final String email2 = "shouldChangeExistingUserIntoDeanery2@shouldDenyAllStudentsTryByStudent.test";
final String usosId = "121328";
final User user = this.service.save(new User(null, null, email, UserRoles.ADMIN));
this.service.save(new User(null, null, email2, usosId, UserRoles.TEST_USER));
final String token = this.service.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(ADD_DEANERY_ENDPOINT).param("authority",usosId).header("Authorization", "Bearer " + token))
.andExpect(status().isOk());
final Optional<User> reponse = this.service.getByAuthority(usosId);
assertTrue(reponse.get().getUsosId().equals(usosId));
assertTrue(reponse.get().getRole().equals(UserRoles.DEANERY));
}
} }