-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusercontroller.java
More file actions
61 lines (45 loc) · 1.84 KB
/
Copy pathusercontroller.java
File metadata and controls
61 lines (45 loc) · 1.84 KB
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
#This is the code for the user controller.
package openin.assignment.controller;
import com.example.taskmanager.model.User;
import com.example.taskmanager.service.UserService;
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.*;
@RestController
@RequestMapping("/api/users")
public class usercontroller {
@Autowired
private UserService userService;
@GetMapping("/{userId}")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> getUser(@PathVariable Long userId) {
try {
User user = userService.getUserById(userId);
return new ResponseEntity<>(user, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
}
}
@PutMapping("/{userId}")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> updateUser(@PathVariable Long userId, @RequestBody User updatedUser) {
try {
User user = userService.updateUser(userId, updatedUser);
return new ResponseEntity<>(user, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
@DeleteMapping("/{userId}")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> deleteUser(@PathVariable Long userId) {
try {
userService.deleteUser(userId);
return new ResponseEntity<>("User deleted successfully", HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
}