Ignore:
Timestamp:
08/17/22 16:21:10 (2 years ago)
Author:
unknown <mlviktor23@…>
Branches:
main
Children:
702ca77
Parents:
800779d
Message:

implemented authentication in react

Location:
springapp/src/main/java/mk/profesori/springapp
Files:
1 added
5 edited

Legend:

Unmodified
Added
Removed
  • springapp/src/main/java/mk/profesori/springapp/Controller/PublicController.java

    r800779d r6eba109  
    11package mk.profesori.springapp.Controller;
    22
     3import java.util.Collections;
    34import java.util.List;
     5import java.util.Map;
    46import java.util.Optional;
    57
     
    2123@RestController
    2224@RequestMapping("/public")
    23 @CrossOrigin(origins = { "http://192.168.0.17:3000", "http://192.168.0.24:3000" })
     25@CrossOrigin(origins = { "http://192.168.0.18:3000", "http://192.168.0.24:3000" })
    2426public class PublicController {
    2527
     
    9597        return mainService.getCityById(cityId); // vrakja grad spored id
    9698    }
     99
     100    @RequestMapping(value = "/loginSuccessRegular", method = RequestMethod.GET)
     101    public Map<String, String> loginSuccessRegular(@RequestParam String sessionId) {
     102        return Collections.singletonMap("sessionId", sessionId);
     103    }
     104
     105    @RequestMapping(value = "/loginSuccessModerator", method = RequestMethod.GET)
     106    public Map<String, String> loginSuccessModerator(@RequestParam String sessionId) {
     107        return Collections.singletonMap("sessionId", sessionId);
     108    }
    97109}
  • springapp/src/main/java/mk/profesori/springapp/Controller/SecureController.java

    r800779d r6eba109  
    11package mk.profesori.springapp.Controller;
     2
     3import java.util.Collections;
     4import java.util.Map;
    25
    36import org.springframework.beans.factory.annotation.Autowired;
     
    58import org.springframework.security.core.annotation.CurrentSecurityContext;
    69import org.springframework.security.core.context.SecurityContext;
     10import org.springframework.security.core.userdetails.UserDetails;
    711import org.springframework.web.bind.annotation.CrossOrigin;
    812import org.springframework.web.bind.annotation.PathVariable;
     
    1014import org.springframework.web.bind.annotation.RequestMapping;
    1115import org.springframework.web.bind.annotation.RequestMethod;
     16import org.springframework.web.bind.annotation.RequestParam;
    1217import org.springframework.web.bind.annotation.RestController;
    1318
     
    1520
    1621import mk.profesori.springapp.Model.CustomUserDetails;
     22import mk.profesori.springapp.Service.CustomUserDetailsService;
    1723import mk.profesori.springapp.Service.MainService;
    1824
    1925@RestController
    2026@RequestMapping("/secure")
    21 @CrossOrigin(origins = { "http://192.168.0.17:3000", "http://192.168.0.24:3000" })
     27@CrossOrigin(origins = { "http://192.168.0.18:3000", "http://192.168.0.24:3000" })
    2228public class SecureController {
    2329
    2430    @Autowired
    2531    private MainService mainService;
     32    @Autowired
     33    CustomUserDetailsService customUserDetailsService;
    2634
    2735    @RequestMapping(value = "/professor/{professorId}/addOpinion", method = RequestMethod.POST)
     
    5260    }
    5361
     62    @RequestMapping(value = "/user", method = RequestMethod.GET)
     63    public UserDetails getUserDetails(@CurrentSecurityContext SecurityContext context) {
     64
     65        Authentication authentication = context.getAuthentication();
     66        if (authentication != null && authentication.getPrincipal() instanceof CustomUserDetails) {
     67            CustomUserDetails currentUser = (CustomUserDetails) authentication.getPrincipal();
     68            return customUserDetailsService.loadUserByUsername(currentUser.getEmail());
     69        }
     70
     71        return null;
     72    }
     73
    5474}
  • springapp/src/main/java/mk/profesori/springapp/Model/CustomUserDetails.java

    r800779d r6eba109  
    5353    private Set<ConfirmationToken> confirmationTokens = new HashSet<>();
    5454    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
    55     private List<Post> authoredPosts = new ArrayList<>();
     55    private Set<Post> authoredPosts = new HashSet<>();
    5656
    5757    public CustomUserDetails(String fullName, String username, String email, String password, UserRole userRole) {
     
    9999    }
    100100
    101     List<Post> getAuthoredPosts() {
     101    public Set<Post> getAuthoredPosts() {
    102102        return this.authoredPosts;
    103103    }
  • springapp/src/main/java/mk/profesori/springapp/Security/SecurityConfiguration.java

    r800779d r6eba109  
    1010import org.springframework.security.crypto.password.PasswordEncoder;
    1111import org.springframework.security.web.SecurityFilterChain;
     12import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
    1213import org.springframework.web.servlet.config.annotation.CorsRegistry;
    1314import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
     
    3637            @Override
    3738            public void addCorsMappings(CorsRegistry registry) {
    38                 registry.addMapping("/**").allowedOrigins("http://192.168.0.17:3000", "http://192.168.0.24:3000");
     39                registry.addMapping("/**").allowedOrigins("http://192.168.0.18:3000", "http://192.168.0.24:3000")
     40                        .allowCredentials(true);
    3941            }
    4042        };
     43    }
     44
     45    @Bean
     46    public AuthenticationSuccessHandler customAuthenticationSuccessHandler() {
     47        return new CustomAuthenticationSuccessHandler();
    4148    }
    4249
     
    5461                .antMatchers("/registration/**").permitAll()
    5562                .and()
    56                 .formLogin();
     63                .formLogin().successHandler(customAuthenticationSuccessHandler());
    5764
    5865        return http.build();
  • springapp/src/main/java/mk/profesori/springapp/Service/RegistrationService.java

    r800779d r6eba109  
    2525    private final EmailSender emailSender;
    2626    private final UserRepository userRepository;
    27    
     27
    2828    public String register(RegistrationRequest request) {
    2929
    3030        boolean isValidEmail = emailValidator.test(request.getEmail());
    31         if(!isValidEmail) throw new IllegalStateException("Invalid email");
     31        if (!isValidEmail)
     32            throw new IllegalStateException("Invalid email");
    3233
    3334        boolean isValidPassword = passwordValidator.test(request.getPassword());
    34         if(!isValidPassword) throw new IllegalStateException("Invalid password");
     35        if (!isValidPassword)
     36            throw new IllegalStateException("Invalid password");
    3537
    3638        boolean isValidUsername = usernameValidator.test(request.getUsername());
    37         if(!isValidUsername) throw new IllegalStateException("Invalid username");
     39        if (!isValidUsername)
     40            throw new IllegalStateException("Invalid username");
    3841
    3942        boolean emailExists = userRepository.findByEmail(request.getEmail()).isPresent();
    40         if(emailExists) {
    41             if(!userRepository.findByEmail(request.getEmail()).get().isEnabled()) {
    42                 String tokenToResend = customUserDetailsService.createToken(userRepository.findByEmail(request.getEmail()).get());
    43                 String link = "http://192.168.0.17:8080/registration/confirm?token=" + tokenToResend;
     43        if (emailExists) {
     44            if (!userRepository.findByEmail(request.getEmail()).get().isEnabled()) {
     45                String tokenToResend = customUserDetailsService
     46                        .createToken(userRepository.findByEmail(request.getEmail()).get());
     47                String link = "http://192.168.0.18:8080/registration/confirm?token=" + tokenToResend;
    4448                emailSender.send(request.getEmail(), emailSender.buildEmail(request.getUsername(), link));
    45                 return tokenToResend; 
     49                return tokenToResend;
    4650            } else {
    47             throw new IllegalStateException("Email is taken");
     51                throw new IllegalStateException("Email is taken");
    4852            }
    4953        }
    5054
    5155        boolean usernameExists = userRepository.findByUsername(request.getUsername()).isPresent();
    52         if(usernameExists) {
     56        if (usernameExists) {
    5357            throw new IllegalStateException("Username is taken");
    5458        }
    5559
    5660        String token = customUserDetailsService.signUp(
    57             new CustomUserDetails(
    58                 request.getFullName(),
    59                 request.getUsername(),
    60                 request.getEmail(),
    61                 request.getPassword(),
    62                 UserRole.REGULAR
    63             )
    64             );
    65        
    66         String link = "http://192.168.0.17:8080/registration/confirm?token=" + token;
    67        
     61                new CustomUserDetails(
     62                        request.getFullName(),
     63                        request.getUsername(),
     64                        request.getEmail(),
     65                        request.getPassword(),
     66                        UserRole.REGULAR));
     67
     68        String link = "http://192.168.0.18:8080/registration/confirm?token=" + token;
     69
    6870        emailSender.send(request.getEmail(), emailSender.buildEmail(request.getUsername(), link));
    69        
     71
    7072        return token;
    7173    }
     
    7577        ConfirmationToken confirmationToken = confirmationTokenService
    7678                .getToken(token)
    77                 .orElseThrow(() ->
    78                         new IllegalStateException("Token not found"));
     79                .orElseThrow(() -> new IllegalStateException("Token not found"));
    7980
    8081        if (confirmationToken.getConfirmedAt() != null) {
Note: See TracChangeset for help on using the changeset viewer.