|
1 | 1 | package com.bezkoder.springjwt.controllers; |
2 | 2 |
|
3 | | -import java.util.HashSet; |
4 | | -import java.util.List; |
5 | | -import java.util.Set; |
6 | | -import java.util.stream.Collectors; |
7 | | - |
8 | | -import javax.validation.Valid; |
9 | | - |
10 | | -import org.springframework.beans.factory.annotation.Autowired; |
| 3 | +import com.bezkoder.springjwt.models.ERole; |
| 4 | +import com.bezkoder.springjwt.models.Role; |
| 5 | +import com.bezkoder.springjwt.models.User; |
| 6 | +import com.bezkoder.springjwt.payload.request.LoginRequest; |
| 7 | +import com.bezkoder.springjwt.payload.request.SignupRequest; |
| 8 | +import com.bezkoder.springjwt.payload.response.JwtResponse; |
| 9 | +import com.bezkoder.springjwt.payload.response.MessageResponse; |
| 10 | +import com.bezkoder.springjwt.repository.RoleRepository; |
| 11 | +import com.bezkoder.springjwt.repository.UserRepository; |
| 12 | +import com.bezkoder.springjwt.security.jwt.JwtUtils; |
| 13 | +import com.bezkoder.springjwt.security.services.UserDetailsImpl; |
| 14 | +import lombok.RequiredArgsConstructor; |
11 | 15 | import org.springframework.http.ResponseEntity; |
12 | 16 | import org.springframework.security.authentication.AuthenticationManager; |
13 | 17 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
14 | 18 | import org.springframework.security.core.Authentication; |
| 19 | +import org.springframework.security.core.GrantedAuthority; |
15 | 20 | import org.springframework.security.core.context.SecurityContextHolder; |
16 | 21 | import org.springframework.security.crypto.password.PasswordEncoder; |
17 | 22 | import org.springframework.web.bind.annotation.CrossOrigin; |
|
20 | 25 | import org.springframework.web.bind.annotation.RequestMapping; |
21 | 26 | import org.springframework.web.bind.annotation.RestController; |
22 | 27 |
|
23 | | -import com.bezkoder.springjwt.models.ERole; |
24 | | -import com.bezkoder.springjwt.models.Role; |
25 | | -import com.bezkoder.springjwt.models.User; |
26 | | -import com.bezkoder.springjwt.payload.request.LoginRequest; |
27 | | -import com.bezkoder.springjwt.payload.request.SignupRequest; |
28 | | -import com.bezkoder.springjwt.payload.response.JwtResponse; |
29 | | -import com.bezkoder.springjwt.payload.response.MessageResponse; |
30 | | -import com.bezkoder.springjwt.repository.RoleRepository; |
31 | | -import com.bezkoder.springjwt.repository.UserRepository; |
32 | | -import com.bezkoder.springjwt.security.jwt.JwtUtils; |
33 | | -import com.bezkoder.springjwt.security.services.UserDetailsImpl; |
| 28 | +import javax.validation.Valid; |
| 29 | +import java.util.HashSet; |
| 30 | +import java.util.List; |
| 31 | +import java.util.Set; |
| 32 | +import java.util.stream.Collectors; |
34 | 33 |
|
35 | 34 | @CrossOrigin(origins = "*", maxAge = 3600) |
36 | 35 | @RestController |
| 36 | +@RequiredArgsConstructor |
37 | 37 | @RequestMapping("/api/auth") |
38 | 38 | public class AuthController { |
39 | | - @Autowired |
40 | | - AuthenticationManager authenticationManager; |
41 | | - |
42 | | - @Autowired |
43 | | - UserRepository userRepository; |
44 | | - |
45 | | - @Autowired |
46 | | - RoleRepository roleRepository; |
47 | | - |
48 | | - @Autowired |
49 | | - PasswordEncoder encoder; |
50 | | - |
51 | | - @Autowired |
52 | | - JwtUtils jwtUtils; |
53 | | - |
54 | | - @PostMapping("/signin") |
55 | | - public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) { |
56 | | - |
57 | | - Authentication authentication = authenticationManager.authenticate( |
58 | | - new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); |
59 | | - |
60 | | - SecurityContextHolder.getContext().setAuthentication(authentication); |
61 | | - String jwt = jwtUtils.generateJwtToken(authentication); |
62 | | - |
63 | | - UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); |
64 | | - List<String> roles = userDetails.getAuthorities().stream() |
65 | | - .map(item -> item.getAuthority()) |
66 | | - .collect(Collectors.toList()); |
67 | | - |
68 | | - return ResponseEntity.ok(new JwtResponse(jwt, |
69 | | - userDetails.getId(), |
70 | | - userDetails.getUsername(), |
71 | | - userDetails.getEmail(), |
72 | | - roles)); |
73 | | - } |
74 | | - |
75 | | - @PostMapping("/signup") |
76 | | - public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) { |
77 | | - if (userRepository.existsByUsername(signUpRequest.getUsername())) { |
78 | | - return ResponseEntity |
79 | | - .badRequest() |
80 | | - .body(new MessageResponse("Error: Username is already taken!")); |
81 | | - } |
82 | 39 |
|
83 | | - if (userRepository.existsByEmail(signUpRequest.getEmail())) { |
84 | | - return ResponseEntity |
85 | | - .badRequest() |
86 | | - .body(new MessageResponse("Error: Email is already in use!")); |
| 40 | + private final AuthenticationManager authenticationManager; |
| 41 | + |
| 42 | + private final UserRepository userRepository; |
| 43 | + |
| 44 | + private final RoleRepository roleRepository; |
| 45 | + |
| 46 | + private final PasswordEncoder encoder; |
| 47 | + |
| 48 | + private final JwtUtils jwtUtils; |
| 49 | + |
| 50 | + @PostMapping("/signin") |
| 51 | + public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) { |
| 52 | + |
| 53 | + Authentication authentication = authenticationManager.authenticate( |
| 54 | + new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); |
| 55 | + |
| 56 | + SecurityContextHolder.getContext().setAuthentication(authentication); |
| 57 | + String jwt = jwtUtils.generateJwtToken(authentication); |
| 58 | + |
| 59 | + UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); |
| 60 | + List<String> roles = userDetails.getAuthorities().stream() |
| 61 | + .map(GrantedAuthority::getAuthority) |
| 62 | + .collect(Collectors.toList()); |
| 63 | + |
| 64 | + return ResponseEntity.ok(new JwtResponse(jwt, |
| 65 | + userDetails.getId(), |
| 66 | + userDetails.getUsername(), |
| 67 | + userDetails.getEmail(), |
| 68 | + roles)); |
87 | 69 | } |
88 | 70 |
|
89 | | - // Create new user's account |
90 | | - User user = new User(signUpRequest.getUsername(), |
91 | | - signUpRequest.getEmail(), |
92 | | - encoder.encode(signUpRequest.getPassword())); |
93 | | - |
94 | | - Set<String> strRoles = signUpRequest.getRole(); |
95 | | - Set<Role> roles = new HashSet<>(); |
96 | | - |
97 | | - if (strRoles == null) { |
98 | | - Role userRole = roleRepository.findByName(ERole.ROLE_USER) |
99 | | - .orElseThrow(() -> new RuntimeException("Error: Role is not found.")); |
100 | | - roles.add(userRole); |
101 | | - } else { |
102 | | - strRoles.forEach(role -> { |
103 | | - switch (role) { |
104 | | - case "admin": |
105 | | - Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN) |
106 | | - .orElseThrow(() -> new RuntimeException("Error: Role is not found.")); |
107 | | - roles.add(adminRole); |
108 | | - |
109 | | - break; |
110 | | - case "mod": |
111 | | - Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR) |
112 | | - .orElseThrow(() -> new RuntimeException("Error: Role is not found.")); |
113 | | - roles.add(modRole); |
114 | | - |
115 | | - break; |
116 | | - default: |
117 | | - Role userRole = roleRepository.findByName(ERole.ROLE_USER) |
118 | | - .orElseThrow(() -> new RuntimeException("Error: Role is not found.")); |
119 | | - roles.add(userRole); |
| 71 | + @PostMapping("/signup") |
| 72 | + public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) { |
| 73 | + if (userRepository.existsByUsername(signUpRequest.getUsername())) { |
| 74 | + return ResponseEntity |
| 75 | + .badRequest() |
| 76 | + .body(new MessageResponse("Error: Username is already taken!")); |
| 77 | + } |
| 78 | + |
| 79 | + if (userRepository.existsByEmail(signUpRequest.getEmail())) { |
| 80 | + return ResponseEntity |
| 81 | + .badRequest() |
| 82 | + .body(new MessageResponse("Error: Email is already in use!")); |
120 | 83 | } |
121 | | - }); |
122 | | - } |
123 | 84 |
|
124 | | - user.setRoles(roles); |
125 | | - userRepository.save(user); |
| 85 | + // Create new user's account |
| 86 | + User user = new User(signUpRequest.getUsername(), |
| 87 | + signUpRequest.getEmail(), |
| 88 | + encoder.encode(signUpRequest.getPassword())); |
| 89 | + |
| 90 | + Set<String> strRoles = signUpRequest.getRoles(); |
| 91 | + Set<Role> roles = new HashSet<>(); |
| 92 | + |
| 93 | + if (strRoles == null) { |
| 94 | + Role userRole = roleRepository.findByName(ERole.ROLE_USER) |
| 95 | + .orElseThrow(() -> new RuntimeException("Error: Role is not found.")); |
| 96 | + roles.add(userRole); |
| 97 | + } else { |
| 98 | + strRoles.forEach(role -> { |
| 99 | + switch (role) { |
| 100 | + case "admin": |
| 101 | + Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN) |
| 102 | + .orElseThrow(() -> new RuntimeException("Error: Role is not found.")); |
| 103 | + roles.add(adminRole); |
| 104 | + |
| 105 | + break; |
| 106 | + case "mod": |
| 107 | + Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR) |
| 108 | + .orElseThrow(() -> new RuntimeException("Error: Role is not found.")); |
| 109 | + roles.add(modRole); |
| 110 | + |
| 111 | + break; |
| 112 | + default: |
| 113 | + Role userRole = roleRepository.findByName(ERole.ROLE_USER) |
| 114 | + .orElseThrow(() -> new RuntimeException("Error: Role is not found.")); |
| 115 | + roles.add(userRole); |
| 116 | + } |
| 117 | + }); |
| 118 | + } |
126 | 119 |
|
127 | | - return ResponseEntity.ok(new MessageResponse("User registered successfully!")); |
128 | | - } |
| 120 | + user.setRoles(roles); |
| 121 | + userRepository.save(user); |
| 122 | + return ResponseEntity.ok(new MessageResponse("User registered successfully!")); |
| 123 | + } |
129 | 124 | } |
0 commit comments