-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthController.java
More file actions
139 lines (116 loc) · 4.95 KB
/
AuthController.java
File metadata and controls
139 lines (116 loc) · 4.95 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
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
package in.newdevpoint.bootcamp.controller;
import in.newdevpoint.bootcamp.entity.ERole;
import in.newdevpoint.bootcamp.entity.Role;
import in.newdevpoint.bootcamp.entity.UserEntity;
import in.newdevpoint.bootcamp.payload.request.LoginRequest;
import in.newdevpoint.bootcamp.payload.request.SignupRequest;
import in.newdevpoint.bootcamp.payload.response.JwtResponse;
import in.newdevpoint.bootcamp.payload.response.MessageResponse;
import in.newdevpoint.bootcamp.repository.RoleRepository;
import in.newdevpoint.bootcamp.repository.UserRepository;
import in.newdevpoint.bootcamp.security.jwt.JwtUtils;
import in.newdevpoint.bootcamp.security.services.UserDetailsImpl;
import jakarta.validation.Valid;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
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.*;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired AuthenticationManager authenticationManager;
@Autowired UserRepository userRepository;
@Autowired RoleRepository roleRepository;
@Autowired PasswordEncoder encoder;
@Autowired JwtUtils jwtUtils;
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication =
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles =
userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok(
new JwtResponse(
jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles));
}
@GetMapping("/createRoleList")
public ResponseEntity<?> createRoleList() {
List<Role> roleList = Arrays.stream(ERole.values()).map(Role::new).collect(Collectors.toList());
for (Role role : roleList) {
roleRepository.save(role);
}
return ResponseEntity.ok(new MessageResponse("Done"));
}
@PostMapping("/signup")
public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
if (userRepository.existsByUsername(signUpRequest.getUsername())) {
return ResponseEntity.badRequest()
.body(new MessageResponse("Error: Username is already taken!"));
}
if (userRepository.existsByEmail(signUpRequest.getEmail())) {
return ResponseEntity.badRequest()
.body(new MessageResponse("Error: Email is already in use!"));
}
// Create new user's account
UserEntity user =
new UserEntity(
signUpRequest.getUsername(),
signUpRequest.getEmail(),
encoder.encode(signUpRequest.getPassword()));
Set<String> strRoles = signUpRequest.getRoles();
Set<Role> roles = new HashSet<>();
if (strRoles == null) {
Role userRole =
roleRepository
.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
} else {
strRoles.forEach(
role -> {
switch (role) {
case "admin":
Role adminRole =
roleRepository
.findByName(ERole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(adminRole);
break;
case "mod":
Role modRole =
roleRepository
.findByName(ERole.ROLE_MODERATOR)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(modRole);
break;
default:
Role userRole =
roleRepository
.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
}
}