Skip to content

Commit 874ed4a

Browse files
authored
Merge pull request #38 from TP-RENTPLACE/feature/(TP-77)-add-auth-module
Feature/(tp 77) add auth module
2 parents 62a17f9 + 5e4ff2b commit 874ed4a

24 files changed

Lines changed: 177 additions & 46 deletions

rentplace/src/main/java/kattsyn/dev/rentplace/auth/JwtAuthentication.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,6 @@ public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentExce
5050

5151
@Override
5252
public String getName() {
53-
return name;
53+
return email;
5454
}
5555
}

rentplace/src/main/java/kattsyn/dev/rentplace/configs/SecurityConfig.java

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,11 +52,8 @@ public void init() {
5252
};
5353

5454
ADMIN_URLS = new String[]{
55-
"/" + apiPath + "/reservations/{id}",
56-
"/" + apiPath + "/properties/{id}",
5755
"/" + apiPath + "/categories/**",
5856
"/" + apiPath + "/facilities/**",
59-
"/" + apiPath + "/users/{id}",
6057
"/" + apiPath + "/images/{id}"
6158
};
6259

rentplace/src/main/java/kattsyn/dev/rentplace/controllers/AuthController.java

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,16 @@
11
package kattsyn.dev.rentplace.controllers;
22

33
import io.swagger.v3.oas.annotations.Operation;
4+
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
45
import io.swagger.v3.oas.annotations.tags.Tag;
56
import jakarta.security.auth.message.AuthException;
6-
import jakarta.servlet.http.HttpServletResponse;
7-
import kattsyn.dev.rentplace.dtos.CodeRequest;
8-
import kattsyn.dev.rentplace.dtos.JwtRequest;
9-
import kattsyn.dev.rentplace.dtos.JwtResponse;
10-
import kattsyn.dev.rentplace.dtos.RefreshJwtRequest;
7+
import kattsyn.dev.rentplace.dtos.*;
118
import kattsyn.dev.rentplace.services.AuthService;
129
import kattsyn.dev.rentplace.services.VerificationCodeService;
1310
import lombok.RequiredArgsConstructor;
14-
import org.springframework.http.HttpHeaders;
15-
import org.springframework.http.ResponseCookie;
1611
import org.springframework.http.ResponseEntity;
1712
import org.springframework.web.bind.annotation.*;
1813

19-
import java.time.Duration;
20-
2114
@RestController
2215
@RequestMapping("${api.path}/auth")
2316
@RequiredArgsConstructor
@@ -118,4 +111,12 @@ public ResponseEntity<JwtResponse> refresh(/*@CookieValue(name = "refreshToken")
118111
.body(jwtResponse);
119112
}
120113

114+
115+
@GetMapping("/info")
116+
@SecurityRequirement(name = "JWT")
117+
@Operation(summary = "Получение информации о пользователе", description = "Возвращает информацию об авторизованном пользователе")
118+
public UserDTO getUserInfo() throws AuthException {
119+
return authService.getUserInfo();
120+
}
121+
121122
}

rentplace/src/main/java/kattsyn/dev/rentplace/controllers/PropertyController.java

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import org.springframework.http.MediaType;
1919
import org.springframework.http.ResponseEntity;
2020
import org.springframework.security.access.prepost.PreAuthorize;
21+
import org.springframework.security.core.Authentication;
2122
import org.springframework.validation.annotation.Validated;
2223
import org.springframework.web.bind.annotation.*;
2324
import org.springframework.web.multipart.MultipartFile;
@@ -43,17 +44,18 @@ public class PropertyController {
4344
@ApiResponse(responseCode = "413", description = "Превышен максимальный размер запроса"),
4445
@ApiResponse(responseCode = "500", description = "Внутренняя ошибка сервера")
4546
})
46-
@PreAuthorize("hasAuthority('ROLE_ADMIN') or hasAuthority('ROLE_USER')" )
47+
@PreAuthorize("hasAuthority('ROLE_ADMIN') or hasAuthority('ROLE_USER')")
4748
@SecurityRequirement(name = "JWT")
4849
public ResponseEntity<List<ImageDTO>> uploadMultipleImages(
4950
@PathVariable @Parameter(description = "id объявления", example = "10") long id,
5051
@Parameter(
5152
description = "Массив файлов фотографий",
5253
required = true,
5354
content = @Content(mediaType = MediaType.MULTIPART_FORM_DATA_VALUE, schema = @Schema(type = "string", format = "binary"))
54-
) @RequestPart("files") MultipartFile[] files) {
55-
55+
) @RequestPart("files") MultipartFile[] files,
56+
Authentication authentication) {
5657

58+
propertyService.ownsPropertyOrAdmin(id, authentication.getName());
5759
List<ImageDTO> savedImages = propertyService.uploadImages(files, id);
5860

5961
return ResponseEntity.ok(savedImages);
@@ -104,10 +106,11 @@ public ResponseEntity<PropertyDTO> findById(@Valid @PathVariable @Parameter(desc
104106
@ApiResponse(responseCode = "422", description = "Ошибка валидации", content = @Content),
105107
@ApiResponse(responseCode = "500", description = "Непредвиденная ошибка со стороны сервера", content = @Content)
106108
})
107-
@PreAuthorize("hasAuthority('ROLE_ADMIN') or hasAuthority('ROLE_USER')" )
109+
@PreAuthorize("hasAuthority('ROLE_ADMIN') or hasAuthority('ROLE_USER')")
108110
@SecurityRequirement(name = "JWT")
109111
@PostMapping(path = "/", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
110-
public ResponseEntity<PropertyDTO> createPropertyWithImage(@Valid @ModelAttribute PropertyCreateEditDTO propertyCreateEditDTO) {
112+
public ResponseEntity<PropertyDTO> createPropertyWithImage(@Valid @ModelAttribute PropertyCreateEditDTO propertyCreateEditDTO, Authentication authentication) {
113+
propertyService.allowedToCreatePropertyOrAdmin(propertyCreateEditDTO, authentication.getName());
111114
return new ResponseEntity<>(propertyService.createWithImages(propertyCreateEditDTO), HttpStatus.CREATED);
112115
}
113116

@@ -122,11 +125,13 @@ public ResponseEntity<PropertyDTO> createPropertyWithImage(@Valid @ModelAttribut
122125
@ApiResponse(responseCode = "422", description = "Ошибка валидации", content = @Content),
123126
@ApiResponse(responseCode = "500", description = "Непредвиденная ошибка со стороны сервера", content = @Content)
124127
})
125-
@PreAuthorize("hasAuthority('ROLE_ADMIN') or hasAuthority('ROLE_USER')" )
128+
@PreAuthorize("hasAuthority('ROLE_ADMIN') or hasAuthority('ROLE_USER')")
126129
@SecurityRequirement(name = "JWT")
127130
@PatchMapping(path = "/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
128131
public ResponseEntity<PropertyDTO> updateProperty(@Valid @PathVariable @Parameter(description = "id объявления", example = "1") long id,
129-
@Valid @ModelAttribute PropertyCreateEditDTO propertyCreateEditDTO) {
132+
@Valid @ModelAttribute PropertyCreateEditDTO propertyCreateEditDTO,
133+
Authentication authentication) {
134+
propertyService.ownsPropertyOrAdmin(id, authentication.getName());
130135
return ResponseEntity.ok(propertyService.update(id, propertyCreateEditDTO));
131136
}
132137

@@ -141,11 +146,13 @@ public ResponseEntity<PropertyDTO> updateProperty(@Valid @PathVariable @Paramete
141146
@ApiResponse(responseCode = "422", description = "Ошибка валидации", content = @Content),
142147
@ApiResponse(responseCode = "500", description = "Непредвиденная ошибка со стороны сервера", content = @Content)
143148
})
144-
@PreAuthorize("hasAuthority('ROLE_ADMIN')" )
149+
@PreAuthorize("hasAuthority('ROLE_ADMIN') or hasAuthority('ROLE_USER')")
145150
@SecurityRequirement(name = "JWT")
146151
@DeleteMapping("/{id}")
147-
public ResponseEntity<Void> deleteProperty(@Valid @PathVariable @Parameter(description = "id объявления", example = "10") long id) {
148-
propertyService.deleteById(id);
152+
public ResponseEntity<Void> deleteProperty(@Valid @PathVariable @Parameter(description = "id объявления", example = "10") long id, Authentication authentication) {
153+
if (propertyService.ownsPropertyOrAdmin(id, authentication.getName())) {
154+
propertyService.deleteById(id);
155+
}
149156
return ResponseEntity.noContent().build();
150157
}
151158
}

rentplace/src/main/java/kattsyn/dev/rentplace/controllers/ReservationController.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import org.springframework.http.MediaType;
1616
import org.springframework.http.ResponseEntity;
1717
import org.springframework.security.access.prepost.PreAuthorize;
18+
import org.springframework.security.core.Authentication;
1819
import org.springframework.validation.annotation.Validated;
1920
import org.springframework.web.bind.annotation.*;
2021

@@ -79,7 +80,9 @@ public ResponseEntity<ReservationDTO> getReservation(@PathVariable
7980
@SecurityRequirement(name = "JWT")
8081
@SecurityRequirement(name = "JWT")
8182
@PostMapping(path = "/", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
82-
public ResponseEntity<ReservationDTO> createReservation(@Valid @ModelAttribute ReservationCreateEditDTO reservationCreateEditDTO) {
83+
public ResponseEntity<ReservationDTO> createReservation(@Valid @ModelAttribute ReservationCreateEditDTO reservationCreateEditDTO,
84+
Authentication authentication) {
85+
reservationService.allowedToCreateReservationOrAdmin(reservationCreateEditDTO, authentication.getName());
8386
return ResponseEntity.ok(reservationService.createReservation(reservationCreateEditDTO));
8487
}
8588

@@ -118,8 +121,10 @@ public ResponseEntity<ReservationDTO> updateReservation(@PathVariable @Parameter
118121
@SecurityRequirement(name = "JWT")
119122
public ResponseEntity<ReservationDTO> deleteReservation(
120123
@PathVariable
121-
@Valid @Parameter(description = "id бронирования", example = "1") long id
124+
@Valid @Parameter(description = "id бронирования", example = "1") long id,
125+
Authentication authentication
122126
) {
127+
reservationService.ownsReservationOrAdmin(id, authentication.getName());
123128
return ResponseEntity.ok(reservationService.deleteById(id));
124129
}
125130

rentplace/src/main/java/kattsyn/dev/rentplace/controllers/UserController.java

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import org.springframework.http.MediaType;
2020
import org.springframework.http.ResponseEntity;
2121
import org.springframework.security.access.prepost.PreAuthorize;
22+
import org.springframework.security.core.Authentication;
2223
import org.springframework.stereotype.Controller;
2324
import org.springframework.web.bind.annotation.*;
2425
import org.springframework.web.multipart.MultipartFile;
@@ -51,8 +52,9 @@ public ResponseEntity<ImageDTO> uploadImage(
5152
content = @Content(mediaType = MediaType.MULTIPART_FORM_DATA_VALUE)
5253
) @RequestParam("file") MultipartFile file,
5354
@PathVariable
54-
@Parameter(description = "id пользователя", example = "10") long id) {
55-
55+
@Parameter(description = "id пользователя", example = "10") long id,
56+
Authentication authentication) {
57+
userService.allowedToEditUser(id, authentication.getName());
5658
return ResponseEntity.ok(userService.uploadImage(file, id));
5759
}
5860

@@ -122,7 +124,9 @@ public ResponseEntity<UserDTO> createUser(@ModelAttribute @Valid UserCreateEditD
122124
public ResponseEntity<UserDTO> updateUser(
123125
@PathVariable
124126
@Parameter(description = "id пользователя", example = "1") long id,
125-
@ModelAttribute @Valid UserCreateEditDTO userCreateEditDTO) {
127+
@ModelAttribute @Valid UserCreateEditDTO userCreateEditDTO,
128+
Authentication authentication) {
129+
userService.allowedToEditUser(id, authentication.getName());
126130
return ResponseEntity.ok(userService.update(id, userCreateEditDTO));
127131
}
128132

rentplace/src/main/java/kattsyn/dev/rentplace/dtos/CodeRequest.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package kattsyn.dev.rentplace.dtos;
22

3+
import io.swagger.v3.oas.annotations.media.Schema;
34
import jakarta.validation.constraints.Email;
45
import lombok.AllArgsConstructor;
56
import lombok.Getter;
@@ -13,6 +14,7 @@
1314
public class CodeRequest {
1415

1516
@Email
17+
@Schema(description = "Почта пользователя", example = "warshard1337@gmail.com")
1618
private String email;
1719

1820
}

rentplace/src/main/java/kattsyn/dev/rentplace/dtos/JwtRequest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ public class JwtRequest {
1414

1515
@Schema(description = "Почта пользователя", example = "warshard1337@gmail.com")
1616
private String email;
17-
@Schema(description = "Код, который пользователь получил на почту", example = "123456")
17+
@Schema(description = "Код, который пользователь получил на почту", example = "12345")
1818
private String code;
1919

2020
}

rentplace/src/main/java/kattsyn/dev/rentplace/dtos/JwtResponse.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package kattsyn.dev.rentplace.dtos;
22

3-
import com.fasterxml.jackson.annotation.JsonIgnore;
3+
import io.swagger.v3.oas.annotations.media.Schema;
44
import lombok.AllArgsConstructor;
55
import lombok.Getter;
66
import lombok.NoArgsConstructor;
@@ -12,10 +12,13 @@
1212
@NoArgsConstructor
1313
public class JwtResponse {
1414

15+
@Schema(example = "Bearer ")
1516
private final String type = "Bearer ";
17+
@Schema(example = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ3YXJzaGFyZDEzMzdAZ21haWwuY29tIiwiZXhwIjoxNzQ2MzA1ODEzLCJyb2xlIjoiUk9MRV9B211JTiIsIm5hbWUiOiJhZG1pbiJ9.4Rg7E39Y4baT9Eld_pkvH0D6S72eepmyd17Ch44K5Fikw32BSbXsnVq4EOnXJgXsQkmkhZrGDHZh-cSGg7pLPg")
1618
private String accessToken;
1719

1820
//@JsonIgnore
21+
@Schema(example = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ3YXJzaGFyZDEzMzdAZ21haWwuY29tIiwiZXhwIjoxNzQ2MzA1ODEzLCJyb2xlIjoiUk9MRV9Bda1JTiIsIm5hbWUiOiJhZG1pbiJ9.4Rg7E39Y4baT9Eld_pkvH0D6S72eepmydCLCh44K5FikwkdBSbXsnVq4EOnXJgXsQkmkhZrGDHZh-cSGg7pLPg")
1922
private String refreshToken;
2023

2124
}

rentplace/src/main/java/kattsyn/dev/rentplace/dtos/UserCreateEditDTO.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import jakarta.validation.constraints.NotBlank;
66
import jakarta.validation.constraints.Size;
77
import kattsyn.dev.rentplace.enums.Gender;
8+
import kattsyn.dev.rentplace.enums.Role;
89
import lombok.AllArgsConstructor;
910
import lombok.Getter;
1011
import lombok.NoArgsConstructor;
@@ -30,6 +31,8 @@ public class UserCreateEditDTO {
3031
private String surname;
3132
@Schema(description = "Пол пользователя. MALE или FEMALE")
3233
private Gender gender;
34+
@Schema(description = "Роль пользователя. ROLE_USER или ROLE_ADMIN")
35+
private Role role;
3336
@Schema(description = "Дата рождения пользователя", example = "2004-02-22")
3437
private LocalDate birthDate;
3538
@Schema(description = "email пользователя", example = "ivanivanov@gmail.com")

0 commit comments

Comments
 (0)