All GCC vendors and employee details for IT department management
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.3 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. package com.gcc_manpower.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.beans.factory.annotation.Qualifier;
  4. import org.springframework.jdbc.core.JdbcTemplate;
  5. import org.springframework.security.core.userdetails.User;
  6. import org.springframework.security.core.userdetails.UserDetails;
  7. import org.springframework.security.core.userdetails.UserDetailsService;
  8. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  9. import org.springframework.stereotype.Service;
  10. import javax.sql.DataSource;
  11. import java.util.List;
  12. import java.util.Map;
  13. @Service
  14. public class AppUserDetailsService implements UserDetailsService {
  15. private JdbcTemplate jdbcTemplate;
  16. @Autowired
  17. public void setDataSource(@Qualifier("mysqlItcellManagementDataSource") DataSource dataSource) {
  18. this.jdbcTemplate = new JdbcTemplate(dataSource);
  19. }
  20. @Override
  21. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  22. String sql = "SELECT usr_name, usr_pass, usr_role, is_active FROM app_user WHERE usr_name = ?";
  23. List<Map<String, Object>> users;
  24. try {
  25. users = jdbcTemplate.queryForList(sql, username);
  26. } catch (Exception e) {
  27. throw new UsernameNotFoundException("Database error during user retrieval", e);
  28. }
  29. if (users == null || users.isEmpty()) {
  30. throw new UsernameNotFoundException("Invalid username or password!");
  31. }
  32. Map<String, Object> user = users.get(0);
  33. // Check if user is active
  34. int isActive = 1;
  35. Object activeObj = user.get("is_active");
  36. if (activeObj instanceof Number) {
  37. isActive = ((Number) activeObj).intValue();
  38. } else if (activeObj instanceof Boolean) {
  39. isActive = (Boolean) activeObj ? 1 : 0;
  40. }
  41. if (isActive == 0) {
  42. throw new UsernameNotFoundException("User account is inactive!");
  43. }
  44. String password = (String) user.get("usr_pass");
  45. String role = (String) user.get("usr_role");
  46. if (role == null) {
  47. role = "USER";
  48. }
  49. return User.withUsername(username)
  50. .password(password != null ? password : "")
  51. .roles(role.toUpperCase()) // Will be loaded as authority ROLE_ROLE
  52. .build();
  53. }
  54. }