Advertisement
Guest User

Untitled

a guest
Mar 15th, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 KB | None | 0 0
  1. package com.realdolmen.ticker.services;
  2.  
  3. import com.realdolmen.ticker.repositories.UserRepository;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  8. import org.springframework.security.core.userdetails.User;
  9. import org.springframework.security.core.userdetails.UserDetails;
  10. import org.springframework.security.core.userdetails.UserDetailsService;
  11. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  12. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  13. import org.springframework.security.crypto.password.PasswordEncoder;
  14. import org.springframework.stereotype.Service;
  15.  
  16. @Service("CustomUserDetailService")
  17. public class CustomUserDetailsService implements UserDetailsService
  18. {
  19.  
  20. @Autowired
  21. private UserRepository repository;
  22.  
  23. static final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
  24.  
  25. @Override
  26. public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException
  27. {
  28. com.realdolmen.ticker.models.User user = repository.findByEmail(s);
  29.  
  30. //check if this user with this username exist, if not, throw an exception
  31. // and stop the login process
  32. if (user == null)
  33. {
  34. throw new UsernameNotFoundException("User details not found with this email: " + s);
  35. }
  36.  
  37. String username = user.getEmail();
  38. String password = user.getPassword();
  39. String role = user.getRole().getName();
  40.  
  41. List<SimpleGrantedAuthority> authList = getAuthorities(role);
  42.  
  43. //get the encoded password
  44. String encodedPassword = passwordEncoder.encode(password);
  45.  
  46. User userDetails = new User(username, encodedPassword, authList);
  47.  
  48. return userDetails;
  49. }
  50.  
  51. private List<SimpleGrantedAuthority> getAuthorities(String role)
  52. {
  53. List<SimpleGrantedAuthority> authList = new ArrayList<>();
  54. authList.add(new SimpleGrantedAuthority("ROLE_USER"));
  55. authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
  56.  
  57. if (role != null && role.trim().length() > 0)
  58. {
  59. if (role.equals("admin"))
  60. {
  61. authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
  62. }
  63. if (role.equals("user"))
  64. {
  65. authList.add(new SimpleGrantedAuthority("ROLE_USER"));
  66. }
  67. }
  68.  
  69. return authList;
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement