[b101b69] | 1 | package mk.ukim.finki.busngo.config;
|
---|
| 2 |
|
---|
| 3 | import mk.ukim.finki.busngo.service.KorisnikService;
|
---|
| 4 | import org.springframework.security.authentication.AuthenticationProvider;
|
---|
| 5 | import org.springframework.security.authentication.BadCredentialsException;
|
---|
| 6 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
---|
| 7 | import org.springframework.security.core.Authentication;
|
---|
| 8 | import org.springframework.security.core.AuthenticationException;
|
---|
| 9 | import org.springframework.security.core.userdetails.UserDetails;
|
---|
| 10 | import org.springframework.security.crypto.password.PasswordEncoder;
|
---|
| 11 | import org.springframework.stereotype.Component;
|
---|
| 12 |
|
---|
| 13 | @Component
|
---|
| 14 | public class CustomUsernamePasswordAuthenticationProvider implements AuthenticationProvider {
|
---|
| 15 |
|
---|
| 16 | private final KorisnikService userService;
|
---|
| 17 | private final PasswordEncoder passwordEncoder;
|
---|
| 18 |
|
---|
| 19 | public CustomUsernamePasswordAuthenticationProvider(KorisnikService userService, PasswordEncoder passwordEncoder) {
|
---|
| 20 | this.userService = userService;
|
---|
| 21 | this.passwordEncoder = passwordEncoder;
|
---|
| 22 | }
|
---|
| 23 |
|
---|
| 24 | @Override
|
---|
| 25 | public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
---|
| 26 | String username = authentication.getName();
|
---|
| 27 | String password = authentication.getCredentials().toString();
|
---|
| 28 |
|
---|
| 29 | if (username.isEmpty() || password.isEmpty()) {
|
---|
| 30 | throw new BadCredentialsException("Empty credentials!");
|
---|
| 31 | }
|
---|
| 32 |
|
---|
| 33 | UserDetails userDetails = this.userService.loadUserByEmail(username);
|
---|
| 34 |
|
---|
| 35 | if (!passwordEncoder.matches(password, userDetails.getPassword())) {
|
---|
| 36 | throw new BadCredentialsException("Password is incorrect!");
|
---|
| 37 | }
|
---|
| 38 | return new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
|
---|
| 39 | }
|
---|
| 40 |
|
---|
| 41 | @Override
|
---|
| 42 | public boolean supports(Class<?> aClass) {
|
---|
| 43 | return aClass.equals(UsernamePasswordAuthenticationToken.class);
|
---|
| 44 | }
|
---|
| 45 |
|
---|
| 46 | }
|
---|