[b8dc761] | 1 | package it.finki.charitable.security;
|
---|
| 2 |
|
---|
| 3 | import it.finki.charitable.entities.AppUser;
|
---|
| 4 | import it.finki.charitable.entities.MainUser;
|
---|
| 5 | import it.finki.charitable.entities.UserRole;
|
---|
| 6 | import it.finki.charitable.services.UserService;
|
---|
| 7 | import org.springframework.security.core.Authentication;
|
---|
| 8 | import org.springframework.security.core.context.SecurityContextHolder;
|
---|
| 9 | import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
|
---|
| 10 | import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
|
---|
| 11 | import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
|
---|
| 12 | import org.springframework.stereotype.Component;
|
---|
| 13 |
|
---|
| 14 | import javax.servlet.ServletException;
|
---|
| 15 | import javax.servlet.http.HttpServletRequest;
|
---|
| 16 | import javax.servlet.http.HttpServletResponse;
|
---|
| 17 | import java.io.IOException;
|
---|
| 18 | import java.util.UUID;
|
---|
| 19 |
|
---|
| 20 | @Component
|
---|
| 21 | public class O2AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
|
---|
| 22 |
|
---|
| 23 | private final UserService userService;
|
---|
| 24 |
|
---|
| 25 | public O2AuthSuccessHandler(UserService userService) {
|
---|
| 26 | this.userService = userService;
|
---|
| 27 | }
|
---|
| 28 |
|
---|
| 29 | @Override
|
---|
| 30 | public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
|
---|
| 31 |
|
---|
| 32 | UserO2Auth userO2Auth = (UserO2Auth) authentication.getPrincipal();
|
---|
| 33 | String email = userO2Auth.getName();
|
---|
| 34 | AppUser user = userService.loadUserByUsername(email);
|
---|
| 35 | if(user == null) {
|
---|
| 36 | AppUser newUser = new MainUser();
|
---|
| 37 | String[] name = userO2Auth.getAttribute("name").toString().split(" ");
|
---|
| 38 | newUser.setFirstName(name[0]);
|
---|
| 39 | newUser.setLastName(name[1]);
|
---|
| 40 | newUser.setEmail(email);
|
---|
| 41 | newUser.setPassword(PasswordEncoder.bCryptPasswordEncoder().encode(UUID.randomUUID().toString()));
|
---|
| 42 | newUser.setUserRole(UserRole.USER);
|
---|
| 43 | newUser.setEnabled(true);
|
---|
| 44 | userService.saveUser(newUser);
|
---|
| 45 | }
|
---|
| 46 |
|
---|
| 47 | super.onAuthenticationSuccess(request, response, authentication);
|
---|
| 48 | }
|
---|
| 49 | }
|
---|