Merge pull request 'user-fix' (#32) from user-fix into master

Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/32
This commit is contained in:
Marcin Woźniak 2020-12-18 17:28:02 +01:00
commit 48c23ad4f8
11 changed files with 142 additions and 44 deletions

View File

@ -35,11 +35,11 @@ spring.profiles.active=prod
Jeżeli chcemy zmienić jakieś opcję dla pordukcji to robimy to w tym sammym katalogi w pliku `application-prod.properties` i dla dev analogicznie w `application-dev.properties`.
W paczce dla proda w protpertiesach poufne dane odczytywane są ze zmiennych środowiskowych systemu na którym odpalana jest aplikacja. Ustawić trzeba następujące zmienne:
- PLANNAPLAN_MYSQL_DB_HOST - host bazy danych np `localhost`
- PLANNAPLAN_MYSQL_DB_PORT - port na którym działa baza
- PLANNAPLAN_MYSQL_DB - nazwa bazy dancyh. W profilu **dev** jest to np test
- PLANNAPLAN_MYSQL_DB_USERNAME - nazwa użytkownika bazy
- PLANNAPLAN_MYSQL_DB_PASSWORD - hasło użytkownika bazy
- `PLANNAPLAN_MYSQL_DB_HOST` - host bazy danych np `localhost`
- `PLANNAPLAN_MYSQL_DB_PORT` - port na którym działa baza
- `PLANNAPLAN_MYSQL_DB` - nazwa bazy dancyh. W profilu **dev** jest to np test
- `PLANNAPLAN_MYSQL_DB_USERNAME` - nazwa użytkownika bazy
- `PLANNAPLAN_MYSQL_DB_PASSWORD` - hasło użytkownika bazy
## Packaging

View File

@ -12,27 +12,23 @@ import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
/**
* UserRepository.getByAuthority:
* Return list of:
* SELECT * FROM User WHERE email = i.
* UserRepository.getByAuthority: Return list of: SELECT * FROM User WHERE email
* = i.
*
* Where i, ?1 are equale to variables.
*
* UserRepository.getByToken:
* Return list of:
* SELECT * FROM User WHERE token = i.
* UserRepository.getByToken: Return list of: SELECT * FROM User WHERE token =
* i.
*
* Where i, ?1 are equale to variables.
*
* UserRepository.searchForUsers:
* Return list of:
* SELECT * FROM User WHERE (name LIKE %?1% OR surname LIKE %?1%).
* UserRepository.searchForUsers: Return list of: SELECT * FROM User WHERE (name
* LIKE %?1% OR surname LIKE %?1%).
*
* Where i, ?1 are equale to variables.
*
* UserRepository.searchForUsers with role:
* Return list of:
* SELECT * FROM User WHERE (name LIKE %?1% OR surname LIKE %?1%) AND role=?2").
* UserRepository.searchForUsers with role: Return list of: SELECT * FROM User
* WHERE (name LIKE %?1% OR surname LIKE %?1%) AND role=?2").
*
* Where i, ?1 are equale to variables.
*/
@ -51,6 +47,9 @@ public interface UserRepository extends JpaRepository<User, Long> {
@Query("FROM User WHERE (name LIKE %?1% OR surname LIKE %?1%) AND role=?2")
List<User> searchForUsers(@Param("query") String query, @Param("role") UserRoles role);
@Query("FROM User WHERE role=?1")
List<User> getAllByRole(@Param("role") UserRoles role);
@Query("FROM User WHERE usosId = ?1")
Optional<User> getByUsosId(@Param("usosId") String usosId);
}

View File

@ -77,4 +77,8 @@ public class UserService {
return this.repo.findById(userId);
}
public List<User> getAllStudents() {
return this.repo.getAllByRole(UserRoles.STUDENT);
}
}

View File

@ -120,6 +120,11 @@ public class App {
newuser.setSurname("Sad");
newuser.setRole(UserRoles.STUDENT);
this.userService.save(newuser);
newuser = new User();
newuser.setEmail("iamnull@st.amu.edu.pl");
newuser.setRole(UserRoles.STUDENT);
this.userService.save(newuser);
}
System.out.println(Logo.getStartedInfo(isDev));

View File

@ -24,14 +24,10 @@ public class Swagger2Config extends WebMvcConfigurationSupport {
@Bean
public Docket createRestApi() {
Parameter authHeader = new ParameterBuilder()
.parameterType("header")
.name("Authorization")
.modelRef(new ModelRef("string"))
.build();
Parameter authHeader = new ParameterBuilder().parameterType("header").name("Authorization")
.modelRef(new ModelRef("string")).build();
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.plannaplan")).paths(PathSelectors.any())
.build()
.apis(RequestHandlerSelectors.basePackage("com.plannaplan")).paths(PathSelectors.any()).build()
.globalOperationParameters(Collections.singletonList(authHeader));
}

View File

@ -2,6 +2,7 @@ package com.plannaplan.controllers;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import com.plannaplan.App;
import com.plannaplan.entities.Groups;
@ -13,9 +14,11 @@ import com.plannaplan.services.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@ -57,4 +60,20 @@ public class GroupController {
}
return new ResponseEntity<>(GroupsMappers.mapToGetCourseGroupsDefaultResponse(groups), HttpStatus.OK);
}
@PutMapping("/{id}/capacity")
@PreAuthorize("hasRole('ROLE_DEANERY')")
@ApiOperation(value = "Change capacity of given group. You need to provide DEANERY token to be ale to change capacity")
public ResponseEntity<String> updateCapacity(
@PathVariable(name = "id", required = true) @ApiParam(value = "id of group to change capacity") Long id,
@RequestParam(name = "newcapacity", required = true) Integer newcapacity) {
final Optional<Groups> group = this.groupService.getGroupById(id);
if (group.isEmpty()) {
return new ResponseEntity<>("Given group doens't exist", HttpStatus.NOT_FOUND);
}
final Groups gr = group.get();
gr.setCapacity(newcapacity);
this.groupService.save(gr);
return new ResponseEntity<>("Success", HttpStatus.OK);
}
}

View File

@ -47,7 +47,7 @@ public class UsersController {
@PreAuthorize("hasRole('ROLE_DEANERY')")
@ApiOperation(value = "Gets all students. You need token with DEANERY role to call this")
public ResponseEntity<List<UserResponse>> getAllStudents() {
final List<User> searches = this.userService.searchForStudents("");
final List<User> searches = this.userService.getAllStudents();
final List<UserResponse> response = UserResponseMappers.mapToDefaultResponse(searches);
return new ResponseEntity<>(response, HttpStatus.OK);
}

View File

@ -8,6 +8,7 @@ spring.jpa.hibernate.ddl-auto=create-drop
spring.jackson.serialization.fail-on-empty-beans=false
spring.main.allow-bean-definition-overriding=true
spring.jackson.default-property-inclusion = NON_NULL
logging.level.io.swagger.models.parameters.AbstractSerializableParameter=ERROR
server.port=1285
plannaplan.dev = true
plannaplan.frontendUrl= http://localhost:3000

View File

@ -8,6 +8,7 @@ spring.jpa.hibernate.ddl-auto=update
spring.jackson.serialization.fail-on-empty-beans=false
spring.main.allow-bean-definition-overriding=true
spring.jackson.default-property-inclusion = NON_NULL
logging.level.io.swagger.models.parameters.AbstractSerializableParameter=ERROR
server.port=1285

View File

@ -2,6 +2,7 @@ package com.plannaplan.controllers;
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;
@ -9,7 +10,17 @@ import org.springframework.test.web.servlet.MockMvc;
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.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import com.plannaplan.entities.Groups;
import com.plannaplan.entities.User;
import com.plannaplan.services.GroupService;
import com.plannaplan.services.UserService;
import com.plannaplan.types.UserRoles;
import com.plannaplan.types.WeekDay;
@RunWith(SpringRunner.class)
@SpringBootTest
@ -17,6 +28,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
public class GroupControllerTest extends AbstractControllerTest {
private static final String GROUPS_BY_COURSE_ENDPOINT = "/api/v1/groups/course";
private static final String UPDATE_GROUPS_ENDPOINT = "/api/v1/groups/521/capacity";
@Autowired
private UserService service;
@Autowired
private GroupService groupService;
@Test
public void shouldFailWithNoParaeter() throws Exception {
@ -29,4 +47,59 @@ public class GroupControllerTest extends AbstractControllerTest {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
mockMvc.perform(get(GROUPS_BY_COURSE_ENDPOINT + "/2")).andExpect(status().isOk());
}
@Test
public void shouldFailWithNoToken() throws Exception {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(put(UPDATE_GROUPS_ENDPOINT)).andExpect(status().is4xxClientError());
}
@Test
public void shouldFailWithStudentToken() throws Exception {
final User user = this.service
.save(new User(null, null, "shouldFailWithStudentToken@GroupController.test", UserRoles.STUDENT));
final String token = this.service.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(put(UPDATE_GROUPS_ENDPOINT).header("Authorization", "Bearer " + token))
.andExpect(status().is4xxClientError());
}
@Test
public void shouldFailWithNoParams() throws Exception {
final User user = this.service
.save(new User(null, null, "shouldFailWithNoParams@GroupController.test", UserRoles.DEANERY));
final String token = this.service.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(put(UPDATE_GROUPS_ENDPOINT).header("Authorization", "Bearer " + token))
.andExpect(status().is4xxClientError());
}
@Test
public void shouldFailWithWrongId() throws Exception {
final User user = this.service
.save(new User(null, null, "shouldFailWithWrongId@GroupController.test", UserRoles.DEANERY));
final String token = this.service.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(put("/api/v1/groups/" + user.getId() + "/capacity").param("newcapacity", "23")
.header("Authorization", "Bearer " + token)).andExpect(status().isNotFound());
}
@Test
public void shouldChangeCapacity() throws Exception {
final User user = this.service
.save(new User(null, null, "shouldChangeCapacity@GroupController.test", UserRoles.DEANERY));
final String token = this.service.login(user).getToken();
final Groups newGroup = this.groupService.save(new Groups(43, "A-Nigzdie", null, 436, WeekDay.FRIDAY, null));
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(put("/api/v1/groups/" + newGroup.getId() + "/capacity").param("newcapacity", "23")
.header("Authorization", "Bearer " + token)).andExpect(status().isOk());
assertTrue(this.groupService.getGroupById(newGroup.getId()).get().getCapacity() == 23);
}
}