|
|
@@ -0,0 +1,69 @@
|
|
|
+package fr.jaquin.bdlg.planner.controller;
|
|
|
+
|
|
|
+import java.security.Principal;
|
|
|
+import java.util.List;
|
|
|
+import org.springframework.http.HttpStatus;
|
|
|
+import org.springframework.web.bind.annotation.DeleteMapping;
|
|
|
+import org.springframework.web.bind.annotation.GetMapping;
|
|
|
+import org.springframework.web.bind.annotation.PathVariable;
|
|
|
+import org.springframework.web.bind.annotation.PostMapping;
|
|
|
+import org.springframework.web.bind.annotation.PutMapping;
|
|
|
+import org.springframework.web.bind.annotation.RequestBody;
|
|
|
+import org.springframework.web.bind.annotation.RestController;
|
|
|
+import org.springframework.web.server.ResponseStatusException;
|
|
|
+import fr.jaquin.bdlg.planner.persistence.CustomUser;
|
|
|
+import fr.jaquin.bdlg.planner.persistence.CustomUserRepository;
|
|
|
+
|
|
|
+@RestController
|
|
|
+public class UserController {
|
|
|
+
|
|
|
+
|
|
|
+ private final CustomUserRepository repositoryUser;
|
|
|
+
|
|
|
+ public UserController(CustomUserRepository repositoryUser) {
|
|
|
+ this.repositoryUser = repositoryUser;
|
|
|
+ }
|
|
|
+
|
|
|
+ @GetMapping("/users")
|
|
|
+ List<CustomUser> getUsers() {
|
|
|
+ return (List<CustomUser>) repositoryUser.findAll();
|
|
|
+ }
|
|
|
+
|
|
|
+ @PostMapping("/users")
|
|
|
+ CustomUser getUsers(@RequestBody CustomUser user) {
|
|
|
+ if (repositoryUser.findByUsername(user.getUsername()) == null) {
|
|
|
+ return repositoryUser.save(user);
|
|
|
+ } else {
|
|
|
+ throw new ResponseStatusException(HttpStatus.CONFLICT, "");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ @PutMapping("/users/{username}")
|
|
|
+ void updateUsers(Principal principal, @RequestBody CustomUser user,
|
|
|
+ @PathVariable String username) {
|
|
|
+ if ((principal.getName() == username)) {
|
|
|
+ CustomUser u = repositoryUser.findByUsername(username);
|
|
|
+ if (u == null) {
|
|
|
+ throw new ResponseStatusException(HttpStatus.NOT_FOUND, "");
|
|
|
+ } else {
|
|
|
+ u.setEmail(user.getEmail());
|
|
|
+ System.out.println("Update pwd: " + user.getPassword());
|
|
|
+ u.setPassword(user.getPassword());
|
|
|
+ repositoryUser.save(u);
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ throw new ResponseStatusException(HttpStatus.FORBIDDEN,
|
|
|
+ "You are not authorised to modify this user");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ @DeleteMapping("/users/{username}")
|
|
|
+ void deleteUsers(@PathVariable String username) {
|
|
|
+ CustomUser u = repositoryUser.findByUsername(username);
|
|
|
+ if (u == null) {
|
|
|
+ throw new ResponseStatusException(HttpStatus.NO_CONTENT, "The user doesn't exist.");
|
|
|
+ } else {
|
|
|
+ repositoryUser.delete(u);
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|