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
66 lines
2.3 KiB
package com.gcc_manpower.config;
|
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.beans.factory.annotation.Qualifier;
|
|
import org.springframework.jdbc.core.JdbcTemplate;
|
|
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.stereotype.Service;
|
|
|
|
import javax.sql.DataSource;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
|
|
@Service
|
|
public class AppUserDetailsService implements UserDetailsService {
|
|
|
|
private JdbcTemplate jdbcTemplate;
|
|
|
|
@Autowired
|
|
public void setDataSource(@Qualifier("mysqlItcellManagementDataSource") DataSource dataSource) {
|
|
this.jdbcTemplate = new JdbcTemplate(dataSource);
|
|
}
|
|
|
|
@Override
|
|
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
|
String sql = "SELECT usr_name, usr_pass, usr_role, is_active FROM app_user WHERE usr_name = ?";
|
|
List<Map<String, Object>> users;
|
|
try {
|
|
users = jdbcTemplate.queryForList(sql, username);
|
|
} catch (Exception e) {
|
|
throw new UsernameNotFoundException("Database error during user retrieval", e);
|
|
}
|
|
|
|
if (users == null || users.isEmpty()) {
|
|
throw new UsernameNotFoundException("Invalid username or password!");
|
|
}
|
|
|
|
Map<String, Object> user = users.get(0);
|
|
|
|
// Check if user is active
|
|
int isActive = 1;
|
|
Object activeObj = user.get("is_active");
|
|
if (activeObj instanceof Number) {
|
|
isActive = ((Number) activeObj).intValue();
|
|
} else if (activeObj instanceof Boolean) {
|
|
isActive = (Boolean) activeObj ? 1 : 0;
|
|
}
|
|
|
|
if (isActive == 0) {
|
|
throw new UsernameNotFoundException("User account is inactive!");
|
|
}
|
|
|
|
String password = (String) user.get("usr_pass");
|
|
String role = (String) user.get("usr_role");
|
|
if (role == null) {
|
|
role = "USER";
|
|
}
|
|
|
|
return User.withUsername(username)
|
|
.password(password != null ? password : "")
|
|
.roles(role.toUpperCase()) // Will be loaded as authority ROLE_ROLE
|
|
.build();
|
|
}
|
|
}
|