Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.realdolmen.ticker.services;
- import com.realdolmen.ticker.repositories.UserRepository;
- import java.util.ArrayList;
- import java.util.List;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.security.core.authority.SimpleGrantedAuthority;
- import org.springframework.security.core.userdetails.User;
- import org.springframework.security.core.userdetails.UserDetails;
- import org.springframework.security.core.userdetails.UserDetailsService;
- import org.springframework.security.core.userdetails.UsernameNotFoundException;
- import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
- import org.springframework.security.crypto.password.PasswordEncoder;
- import org.springframework.stereotype.Service;
- @Service("CustomUserDetailService")
- public class CustomUserDetailsService implements UserDetailsService
- {
- @Autowired
- private UserRepository repository;
- static final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
- @Override
- public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException
- {
- com.realdolmen.ticker.models.User user = repository.findByEmail(s);
- //check if this user with this username exist, if not, throw an exception
- // and stop the login process
- if (user == null)
- {
- throw new UsernameNotFoundException("User details not found with this email: " + s);
- }
- String username = user.getEmail();
- String password = user.getPassword();
- String role = user.getRole().getName();
- List<SimpleGrantedAuthority> authList = getAuthorities(role);
- //get the encoded password
- String encodedPassword = passwordEncoder.encode(password);
- User userDetails = new User(username, encodedPassword, authList);
- return userDetails;
- }
- private List<SimpleGrantedAuthority> getAuthorities(String role)
- {
- List<SimpleGrantedAuthority> authList = new ArrayList<>();
- authList.add(new SimpleGrantedAuthority("ROLE_USER"));
- authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
- if (role != null && role.trim().length() > 0)
- {
- if (role.equals("admin"))
- {
- authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
- }
- if (role.equals("user"))
- {
- authList.add(new SimpleGrantedAuthority("ROLE_USER"));
- }
- }
- return authList;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement