-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathAuthController.java
More file actions
55 lines (46 loc) · 2.03 KB
/
Copy pathAuthController.java
File metadata and controls
55 lines (46 loc) · 2.03 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
package com.security.demo.controllers;
import com.security.demo.dto.AuthResponseDto;
import com.security.demo.models.User;
import com.security.demo.services.JwtService;
import com.security.demo.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private UserService userService;
@Autowired
private JwtService jwtService;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody User user) {
Optional<User> optionalUser = userService.findByUsername(user.getUsername());
if (optionalUser.isPresent()) {
User foundUser = optionalUser.get();
if (userService.checkPassword(foundUser, user.getPassword())) {
// Extract role names
List<String> roleNames = foundUser.getRoles().stream()
.map(role -> role.getName().name())
.collect(Collectors.toList());
String token = jwtService.generateToken(foundUser.getUsername(), roleNames.toString());
AuthResponseDto response = new AuthResponseDto();
response.setToken(token);
response.setUsername(foundUser.getUsername());
response.setRoles(roleNames);
return ResponseEntity.ok(response);
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Incorrect password");
}
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found");
}
}
}