forked from CodeURJC-DAW-2023-24/webapp07
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UserRestController.java
268 lines (225 loc) · 12.3 KB
/
UserRestController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package com.daw.webapp07.controller.REST;
import com.daw.webapp07.DTO.*;
import com.daw.webapp07.model.*;
import com.daw.webapp07.service.ProjectService;
import com.daw.webapp07.service.RepositoryUserDetailsService;
import com.daw.webapp07.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.net.URI;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import static org.springframework.web.servlet.support.ServletUriComponentsBuilder.fromCurrentRequest;
@RestController
@RequestMapping("/api")
public class UserRestController {
@Autowired
private UserService userService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private RepositoryUserDetailsService repositoryUserDetailsService;
@Autowired
private ProjectService projectService;
@Operation(summary = "Get user", description = "Returns the user logged.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "User returned successfully",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = UserDetailsDTO.class))
),
@ApiResponse(responseCode = "400", description = "Bad request.", content = @Content),
@ApiResponse(responseCode = "403", description = "Forbidden. The request is not authorized.", content = @Content),
@ApiResponse(responseCode = "404", description = "Not found. The specified user could not be found.", content = @Content)
})
@GetMapping("/users")
public ResponseEntity<UserDetailsDTO> getUser(HttpServletRequest request) {
if(request.getUserPrincipal() == null){
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
Optional<UserEntity> checkUser = userService.findUserByName(request.getUserPrincipal().getName());
if(checkUser.isEmpty()){
return ResponseEntity.notFound().build();
}
UserEntity user = checkUser.get();
if(request.getUserPrincipal().getName().equals(user.getName())) {
UserDetailsDTO userDTO = new UserDetailsDTO(user);
return new ResponseEntity<>(userDTO, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
@GetMapping("/usersId")
public String getUserId() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
Optional<UserEntity> user = userService.findByEmailOrName(username);
if (user.isPresent()) {
Long userId = user.get().getId();
return userId.toString();
} else {
return "Error auth user";
}
}
@Operation(summary = "Get user's inversions", description = "Returns a user's inversions by their ID.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Inversions returned successfully",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = InversionDTO.class))
),
@ApiResponse(responseCode = "400", description = "Invalid ID supplied.", content = @Content),
@ApiResponse(responseCode = "404", description = "User not found. The user with the specified ID could not be found.", content = @Content)
})
@GetMapping("/users/{id}/inversions")
public ResponseEntity<Iterable<InversionDTO>> getUserInversions(@PathVariable long id) {
Optional<UserEntity> userdb = userService.findUserById(id);
if (userdb.isPresent()) {
List<Inversion> inversions = userdb.get().getInversions();
Collection<InversionDTO> inversionsDTO = new ArrayList<>();
for (Inversion inversion : inversions) {
inversionsDTO.add(new InversionDTO(inversion));
}
return new ResponseEntity<>(inversionsDTO, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@Operation(summary = "Get user's comments", description = "Returns a user's comments by their ID.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Comments returned successfully",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = CommentDTO.class))
),
@ApiResponse(responseCode = "400", description = "Invalid ID supplied.", content = @Content),
@ApiResponse(responseCode = "404", description = "User not found. The user with the specified ID could not be found.", content = @Content)
})
@GetMapping("/users/{id}/comments")
public ResponseEntity<Iterable<CommentDTO>> getUserComments(@PathVariable long id) {
Optional<UserEntity> userdb = userService.findUserById(id);
if (userdb.isPresent()) {
List<Comment> comments = userdb.get().getComments();
Collection<CommentDTO> commentsDTO = new ArrayList<>();
for (Comment comment : comments) {
commentsDTO.add(new CommentDTO(comment));
}
return new ResponseEntity<>(commentsDTO, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@Operation(summary = "Get user's projects", description = "Returns the user's projects")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Projects returned successfully",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = ProjectPreviewDTO.class))
),
@ApiResponse(responseCode = "400", description = "Invalid", content = @Content),
@ApiResponse(responseCode = "404", description = "User not found", content = @Content)
})
@GetMapping("/users/projects")
public ResponseEntity<Iterable<ProjectPreviewDTO>> getUserProjects(HttpServletRequest request) {
String name = request.getUserPrincipal().getName();
Optional<UserEntity> userdb = userService.findUserByName(name);
if (userdb.isPresent()) {
List<Project> userProjects = projectService.findByOwnerName(name);
Collection<ProjectPreviewDTO> projectsDTO = new ArrayList<>();
for (Project project : userProjects) {
projectsDTO.add(new ProjectPreviewDTO(project));
}
return new ResponseEntity<>(projectsDTO, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@Operation(summary = "Get user's profile photo", description = "Returns user's photo by his id.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Photo returned successfully", content = @Content),
@ApiResponse(responseCode = "400", description = "Invalid id supplied", content = @Content),
@ApiResponse(responseCode = "404", description = "User not found", content = @Content)
})
@GetMapping("/users/{id}/profile")
public ResponseEntity<Object> displayProfilePhoto(@PathVariable Long id) throws SQLException{
UserEntity userEntity = userService.findUserById(id).orElseThrow();
Resource file = new InputStreamResource(userEntity.getProfilePhoto().getImageFile().getBinaryStream());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_TYPE, "image/jpeg")
.contentLength(userEntity.getProfilePhoto().getImageFile().length())
.body(file);
}
@Operation(summary = "Creates a new user", description = "Creates a new user in the system.")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "User created successfully",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = UserDetailsDTO.class))
),
@ApiResponse(responseCode = "400", description = "Bad request.", content = @Content),
@ApiResponse(responseCode = "403", description = "Forbidden. The request is not authorized.", content = @Content),
@ApiResponse(responseCode = "404", description = "Not found. The specified resource could not be found.", content = @Content)
})
@PostMapping("/users")
public ResponseEntity<UserDetailsDTO> createUser(@RequestBody UserEntity user){
user.setEncodedPassword(passwordEncoder.encode(user.getEncodedPassword()));
user.setRoles(List.of("USER"));
if(repositoryUserDetailsService.registerUser(user)){
URI location = fromCurrentRequest().path("/{id}/").buildAndExpand(user.getId()).toUri();
return ResponseEntity.created(location).body(new UserDetailsDTO(user));
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
@Operation(summary = "Edits user's profile", description = "Edits the profile of an existing user in the system.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "User profile updated successfully", content = @Content),
@ApiResponse(responseCode = "400", description = "Bad request.", content = @Content),
@ApiResponse(responseCode = "403", description = "Forbidden. The request is not authorized.", content = @Content),
@ApiResponse(responseCode = "404", description = "Not found. The specified user could not be found.", content = @Content)
})
@PutMapping("/users")
public ResponseEntity<UserEntity> editUser(@RequestBody UserEntity newUser, HttpServletRequest request) {
String name = request.getUserPrincipal().getName();
Optional<UserEntity> user = userService.findUserByName(name);
if (user.isPresent()) {
user.get().setEmail(newUser.getEmail());
userService.saveUser(user.get());
return ResponseEntity.ok().build();
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
@Operation(summary = "Edits user's profile photo", description = "Edits the profile photo of an existing user in the system.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "User profile photo updated successfully", content = @Content),
@ApiResponse(responseCode = "400", description = "Bad request.", content = @Content),
@ApiResponse(responseCode = "403", description = "Forbidden. The request is not authorized.", content = @Content),
@ApiResponse(responseCode = "404", description = "Not found. The specified user could not be found.", content = @Content)
})
@PutMapping("/users/images")
public ResponseEntity<UserEntity> editProfilePicture(@RequestParam MultipartFile file, HttpServletRequest request){
Optional<UserEntity> checkUser = userService.findUserByName(request.getUserPrincipal().getName());
if(checkUser.isEmpty()){
return ResponseEntity.notFound().build();
}
UserEntity user = checkUser.get();
if(request.getUserPrincipal().getName().equals(user.getName())){
Image image = new Image(file);
user.setProfilePhoto(image);
userService.saveUser(user);
return ResponseEntity.ok().build();
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
}