From 566e775e58b7339150fe27df043038ef7b3ce81b Mon Sep 17 00:00:00 2001 From: Pekka Helenius Date: Sat, 3 Oct 2020 01:25:38 +0300 Subject: [PATCH] Implement UserDetailServiceImpl Signed-off-by: Pekka Helenius --- .../session/UserDetailServiceImpl.java | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 bookstore/src/main/java/com/fjordtek/bookstore/service/session/UserDetailServiceImpl.java diff --git a/bookstore/src/main/java/com/fjordtek/bookstore/service/session/UserDetailServiceImpl.java b/bookstore/src/main/java/com/fjordtek/bookstore/service/session/UserDetailServiceImpl.java new file mode 100644 index 0000000..8513c3b --- /dev/null +++ b/bookstore/src/main/java/com/fjordtek/bookstore/service/session/UserDetailServiceImpl.java @@ -0,0 +1,76 @@ +// Pekka Helenius , Fjordtek 2020 + +package com.fjordtek.bookstore.service.session; + +import java.util.ArrayList; +import java.util.Collection; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import com.fjordtek.bookstore.model.auth.User; +import com.fjordtek.bookstore.model.auth.UserRepository; +import com.fjordtek.bookstore.model.auth.UserRole; +import com.fjordtek.bookstore.model.auth.UserRoleRepository; + +/** +* +* +* @author Pekka Helenius +*/ + +@Service +public class UserDetailServiceImpl implements UserDetailsService { + + private UserRepository userRepository; + private UserRoleRepository userRoleRepository; + + @Autowired + public void instanceAttributeUserDetailsService( + UserRepository userRepository, + UserRoleRepository userRoleRepository + ) { + this.userRepository = userRepository; + this.userRoleRepository = userRoleRepository; + } + + /* + * Retrieve user roles from the USER_ROLE table + */ + private Collection getUserGrantedAuthorities(String userName) { + + User currentUser = userRepository.findByUsername(userName); + + Collection authorities = new ArrayList<>(); + + for (UserRole role : userRoleRepository.findAll()) { + + if (role.getUser().getId() == currentUser.getId()) { + authorities.add( + new SimpleGrantedAuthority(role.getRole().getName()) + ); + } + } + + return authorities; + } + + @Override + public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { + + User currentUser = userRepository.findByUsername(userName); + + UserDetails userDetails = new org.springframework.security.core.userdetails.User( + userName, currentUser.getPassword(), getUserGrantedAuthorities(userName) + ); + + return userDetails; + + } + +} \ No newline at end of file