source: src/main/java/it/finki/charitable/security/O2AuthSuccessHandler.java@ 6fa3d09

Last change on this file since 6fa3d09 was b8dc761, checked in by NikolaCenevski <cenevskinikola@…>, 3 years ago

part 2

  • Property mode set to 100644
File size: 2.0 KB
Line 
1package it.finki.charitable.security;
2
3import it.finki.charitable.entities.AppUser;
4import it.finki.charitable.entities.MainUser;
5import it.finki.charitable.entities.UserRole;
6import it.finki.charitable.services.UserService;
7import org.springframework.security.core.Authentication;
8import org.springframework.security.core.context.SecurityContextHolder;
9import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
10import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
11import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
12import org.springframework.stereotype.Component;
13
14import javax.servlet.ServletException;
15import javax.servlet.http.HttpServletRequest;
16import javax.servlet.http.HttpServletResponse;
17import java.io.IOException;
18import java.util.UUID;
19
20@Component
21public 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}
Note: See TracBrowser for help on using the repository browser.