This commit is contained in:
Rinjae
2025-09-05 18:57:45 +09:00
commit aacc1a389e
1229 changed files with 167963 additions and 0 deletions
@@ -0,0 +1,144 @@
package com.eactive.eai.authserver.dao;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.message.mapper.EAIMessageMapper;
import com.eactive.eai.data.entity.onl.message.EAIMessageEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.eactive.eai.authserver.dao.ClientLoader;
import com.eactive.eai.authserver.vo.ClientVO;
import com.eactive.eai.common.dao.BaseDAO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.data.converter.LocalDateTimeFormatters;
import com.eactive.eai.data.entity.onl.authserver.ClientEntity;
@Service
@Transactional
public class ClientDAO extends BaseDAO {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
@Autowired
private ClientLoader clientService;
@Autowired
private EAIMessageMapper eaiMessageMapper;
public Map<String, ClientDetails> loadClientDetails() throws DAOException {
try {
Stream<ClientEntity> clientEntities = clientService.loadAll();
Map<String, ClientDetails> clientDetailsMap = new HashMap<>();
clientEntities.forEach(clientEntity -> {
ClientVO clientVO = createClientVO(clientEntity);
clientDetailsMap.put(clientEntity.getClientid(), clientVO);
});
return clientDetailsMap;
} catch (Exception e) {
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAUC001"));
}
}
public ClientVO getClientById(String clientId) throws DAOException {
try {
Optional<ClientEntity> clientEntityOptional = clientService.findById(clientId);
ClientEntity clientEntity = clientEntityOptional
.orElseThrow(() -> new DAOException("ClientEntity not found for clientId: " + clientId));
return createClientVO(clientEntity);
} catch (Exception e) {
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAUC001"));
}
}
private ClientVO createClientVO(ClientEntity clientEntity) {
ClientVO clientVO = new ClientVO();
clientVO.setClientName(clientEntity.getClientname());
clientVO.setClientId(clientEntity.getClientid());
clientVO.setClientSecret(clientEntity.getClientsecret());
clientVO.setScope(assignSet(clientEntity.getScope(), ","));
clientVO.setAuthorizedGrantTypes(assignSet(clientEntity.getGranttypes(), ","));
clientVO.setRegisteredRedirectUri(assignSet(clientEntity.getRedirecturi(), ","));
clientVO.setAuthorities(assignAuthorities(clientEntity.getAuthorities()));
clientVO.setResourceIds(assignSet(clientEntity.getResourceids(), ","));
if (NumberUtils.isParsable(clientEntity.getAccesstokenvalidityseconds())) {
clientVO.setAccessTokenValiditySeconds(Integer.parseInt(clientEntity.getAccesstokenvalidityseconds()));
}
if (NumberUtils.isParsable(clientEntity.getRefreshtokenvalidityseconds())) {
clientVO.setRefreshTokenValiditySeconds(Integer.parseInt(clientEntity.getRefreshtokenvalidityseconds()));
}
clientVO.setAutoApproveScopes(assignSet(clientEntity.getAutoapprove(), ","));
clientVO.setAllowedIp(clientEntity.getAllowedips());
clientVO.setSecurityKey(clientEntity.getSecuritykey());
clientVO.setModifiedBy(clientEntity.getModifiedby());
clientVO.setOrgId(clientEntity.getModifiedby());
clientVO.setModifiedBy(clientEntity.getModifiedby());
clientVO.setOrgId(clientEntity.getOrgid());
clientVO.setOrgName(clientEntity.getOrgname());
clientVO.setAppStatus(clientEntity.getAppstatus());
clientVO.setDailyTokenLimit(clientEntity.getDailytokenlimit());
if(clientEntity.getModifiedon() != null) {
clientVO.setModifiedOn(clientEntity.getModifiedon().format(LocalDateTimeFormatters.FORMATTER_YYYYMMDDHHMMSS_14));
}
Map<String, EAIMessage> apiMap = new HashMap<>();
for (EAIMessageEntity eaiMessageEntity : clientEntity.getApiList()){
EAIMessage eaiMessage = eaiMessageMapper.toVo(eaiMessageEntity);
apiMap.put(eaiMessage.getEAISvcCd(), eaiMessage);
}
clientVO.setApiMap(apiMap);
return clientVO;
}
private Collection<? extends GrantedAuthority> assignAuthorities(String roleStr) {
List<GrantedAuthority> authorities = new ArrayList<>();
if (StringUtils.isBlank(roleStr)) {
return authorities;
}
for (String role : StringUtils.split(roleStr, ",")) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
private Set<String> assignSet(String str, String delim) {
Set<String> set = new HashSet<>();
if (StringUtils.isBlank(str)) {
return set;
}
String[] arr = StringUtils.split(str, delim);
set.addAll(Arrays.asList(arr));
return set;
}
}
@@ -0,0 +1,81 @@
package com.eactive.eai.authserver.dao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.eactive.eai.common.dao.BaseDAO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.data.entity.onl.authserver.ScopeEntity;
@Service
@Transactional
public class ScopeDAO extends BaseDAO {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
@Autowired
private ScopeLoader scopeLoader;
public Map<String, HashSet<String>> loadApiScopeRelations() throws DAOException {
try {
Stream<ScopeEntity> scopeEntities = scopeLoader.loadAll();
Map<String, HashSet<String>> clientEntitymap = new HashMap<>();
scopeEntities.forEach(scopeEntity -> {
HashSet<String> set = new HashSet<>();
String scopeId = scopeEntity.getId().getBzwksvckeyname() + scopeEntity.getId().getScopeid();
clientEntitymap.put(scopeId, set);
});
return clientEntitymap;
} catch (Exception e) {
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAUC001"));
}
}
public HashSet<String> getApiScopeRelationsByApiId(String apiId) throws DAOException {
try {
HashSet<String> scopeSet = new HashSet<>();
ScopeEntity scopeEntity = scopeLoader.findByIdBzwksvckeyname(apiId);
scopeSet.add(scopeEntity.getId().getBzwksvckeyname());
return scopeSet;
} catch (Exception e) {
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAUC001"));
}
}
public List<String> getApiScopeRelationsByScopeId(String scopeId) throws DAOException {
try {
List<String> apiList = new ArrayList<>();
ScopeEntity scopeEntity = scopeLoader.findByIdScopeid(scopeId);
apiList.add(scopeEntity.getId().getBzwksvckeyname());
return apiList;
} catch (Exception e) {
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAUC001"));
}
}
public boolean hasApiScopeRelation(String apiId, String scopeId) throws DAOException {
try {
ScopeEntity scopeEntity = scopeLoader.findByIdBzwksvckeynameAndIdScopeid(apiId, scopeId);
return scopeEntity != null;
} catch (Exception e) {
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAUC001"));
}
}
}
@@ -0,0 +1,68 @@
package com.eactive.eai.authserver.dao;
import java.util.List;
import java.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.eactive.eai.common.dao.BaseDAO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.data.entity.onl.authserver.TokenIssuanceLog;
@Service
@Transactional
public class TokenIssuanceLogDAO extends BaseDAO {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
@Autowired
private TokenIssuanceLogLoader tokenIssuanceLogLoader;
public TokenIssuanceLog saveTokenIssuanceLog(TokenIssuanceLog log) throws DAOException {
try {
return tokenIssuanceLogLoader.save(log);
} catch (Exception e) {
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAUC002"));
}
}
public List<TokenIssuanceLog> findByClientId(String clientId) throws DAOException {
try {
return tokenIssuanceLogLoader.findByClientId(clientId);
} catch (Exception e) {
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAUC003"));
}
}
public List<TokenIssuanceLog> findByAppName(String appName) throws DAOException {
try {
return tokenIssuanceLogLoader.findByAppName(appName);
} catch (Exception e) {
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAUC004"));
}
}
public List<TokenIssuanceLog> findByIssuanceDateTimeBetween(LocalDateTime start, LocalDateTime end) throws DAOException {
try {
return tokenIssuanceLogLoader.findByIssuanceDateTimeBetween(start, end);
} catch (Exception e) {
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAUC005"));
}
}
public List<TokenIssuanceLog> findBySuccessYn(String successYn) throws DAOException {
try {
return tokenIssuanceLogLoader.findBySuccessYn(successYn);
} catch (Exception e) {
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAUC006"));
}
}
public int findRecentLogsForRestrictionCount(
String clientId, LocalDateTime startDateTime) {
return tokenIssuanceLogLoader.findRecentLogsForRestrictionCount(clientId, startDateTime);
}
}
@@ -0,0 +1,56 @@
package com.eactive.eai.authserver.dao;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
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.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.eactive.eai.authserver.dao.UserLoader;
import com.eactive.eai.common.dao.BaseDAO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.data.entity.onl.authserver.UserEntity;
@Service
@Transactional
public class UserDAO extends BaseDAO {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
@Autowired
private UserLoader userLoader;
public UserDetails getUserByUserId(String userId) throws DAOException {
try {
UserEntity userEntity = userLoader.getById(userId);
if (userEntity != null) {
return new User(userId, userEntity.getPassword(), assignAuthorities(userEntity.getAuthorities()));
}
return null;
} catch (Exception e) {
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAAC009"));
}
}
public List<GrantedAuthority> assignAuthorities(String roleStr) {
List<GrantedAuthority> authorities = new ArrayList<>();
if (StringUtils.isBlank(roleStr)) {
return authorities;
}
for (String role : StringUtils.split(roleStr, ",")) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
}
@@ -0,0 +1,20 @@
package com.eactive.eai.authserver.service;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.stereotype.Service;
@Service("eLinkClientDetailsService")
public class ElinkClientDetailsServiceImpl implements ClientDetailsService {
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
ClientDetails details = OAuth2Manager.getInstance().getClientDeatilsStore().get(clientId);
if (details == null) {
throw new NoSuchClientException("No client with requested id: " + clientId);
}
return details;
}
}
@@ -0,0 +1,221 @@
package com.eactive.eai.authserver.service;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.stereotype.Component;
import com.eactive.eai.agent.authserver.ReloadApiScopeCommand;
import com.eactive.eai.authserver.dao.ClientDAO;
import com.eactive.eai.authserver.dao.ScopeDAO;
import com.eactive.eai.authserver.vo.ClientVO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.lifecycle.Lifecycle;
import com.eactive.eai.common.lifecycle.LifecycleException;
import com.eactive.eai.common.lifecycle.LifecycleListener;
import com.eactive.eai.common.lifecycle.LifecycleSupport;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.transformer.util.MemoryLogger;
@Component
public class OAuth2Manager implements Lifecycle {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
private LifecycleSupport lifecycle = new LifecycleSupport(this);
private Map<String, ClientDetails> clientDetailsStore = new HashMap<>();
private Map<String, HashSet<String>> apiScopeMap = new HashMap<>();
private boolean started;
@Autowired
private ClientDAO clientDAO;
@Autowired
private ScopeDAO scopeDAO;
public static OAuth2Manager getInstance() {
return ApplicationContextProvider.getContext().getBean(OAuth2Manager.class);
}
public ClientVO getClientInfo(String clientId) throws DAOException {
ClientVO vo = clientDAO.getClientById(clientId);
logger.info("OAuth2Manager | getClientVO clientId=" + clientId + " - " + vo);
return vo;
}
public Map<String, ClientDetails> getClientDeatilsStore() {
return clientDetailsStore;
}
public Map<String, HashSet<String>> getApiScopeMap() {
return apiScopeMap;
}
private void initAllClients() throws DAOException {
clientDetailsStore = clientDAO.loadClientDetails();
logger.info("OAuth2Manager | all clients are initialized");
MemoryLogger.txlog("OAuth2Manager | all clients are initialized");
}
private void initAllApiScopeRelations() throws DAOException {
apiScopeMap = scopeDAO.loadApiScopeRelations();
logger.info("OAuth2Manager | all API-Scope Relation are initialized");
MemoryLogger.txlog("OAuth2Manager | all API-Scope Relation are initialized");
}
@Override
public void addLifecycleListener(LifecycleListener listener) {
lifecycle.addLifecycleListener(listener);
}
@Override
public LifecycleListener[] findLifecycleListeners() {
return lifecycle.findLifecycleListeners();
}
@Override
public void removeLifecycleListener(LifecycleListener listener) {
lifecycle.removeLifecycleListener(listener);
}
@Override
public void start() throws LifecycleException {
if (started)
throw new LifecycleException("RECEAIAAC015");
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
try {
// client 초기화
clientDetailsStore.clear();
initAllClients();
// api-scope 초기화
apiScopeMap.clear();
initAllApiScopeRelations();
} catch (Exception e) {
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "RECEAICPM201"));
}
started = true;
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
}
@Override
public void stop() throws LifecycleException {
if (!started)
throw new LifecycleException("RECEAIAAC020");
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
clientDetailsStore = null;
apiScopeMap = null;
started = false;
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STOPPED_EVENT, this);
}
@Override
public boolean isStarted() {
return this.started;
}
public synchronized void reloadClient(String keyName) throws Exception {
// 1. Memory에서 제거
clientDetailsStore.remove(keyName);
// 2. DB에서 select
ClientVO client = clientDAO.getClientById(keyName);
if (client != null) {
// 3. DB에 있으면 Memory에 적재
clientDetailsStore.put(keyName, client);
}
}
public void reloadApiScopeRelation(String[] args) throws Exception {
if (args == null || args.length != 3) {
throw new Exception("Arguments 3 required");
}
String commandType = args[0];
String apiId = args[1];
String scopeId = args[2];
if (StringUtils.equals(commandType, ReloadApiScopeCommand.COMMAND_TYPE_API)) {
reloadApiScopeRelationForApi(apiId);
} else if (StringUtils.equals(commandType, ReloadApiScopeCommand.COMMAND_TYPE_SCOPE)) {
reloadApiScopeRelationForScope(scopeId);
} else if (StringUtils.equals(commandType, ReloadApiScopeCommand.COMMAND_TYPE_API_SCOPE)) {
reloadApiScopeRelationForApiScope(apiId, scopeId);
} else {
throw new IllegalArgumentException("Invalid command type: " + commandType);
}
}
private void reloadApiScopeRelationForApi(String apiId) throws DAOException {
apiScopeMap.remove(apiId);
logger.debug(String.format("Type=%s, ID=%s removed", ReloadApiScopeCommand.COMMAND_TYPE_API, apiId));
HashSet<String> scopeSet = scopeDAO.getApiScopeRelationsByApiId(apiId);
if (scopeSet != null) {
apiScopeMap.put(apiId, scopeSet);
logger.debug(String.format("Type=%s, ID=%s added", ReloadApiScopeCommand.COMMAND_TYPE_API, apiId));
}
}
private void reloadApiScopeRelationForScope(String scopeId) throws DAOException {
for (Set<String> scopeSet : apiScopeMap.values()) {
scopeSet.remove(scopeId);
}
logger.debug(String.format("Type=%s, ID=%s removed", ReloadApiScopeCommand.COMMAND_TYPE_SCOPE, scopeId));
List<String> apiList = scopeDAO.getApiScopeRelationsByScopeId(scopeId);
if (apiList != null) {
for (String apiId : apiList) {
Set<String> scopeSet = apiScopeMap.computeIfAbsent(apiId, k -> new HashSet<>());
scopeSet.add(scopeId);
logger.debug(String.format("Type=%s, ID=%s, %s added", ReloadApiScopeCommand.COMMAND_TYPE_SCOPE, apiId,
scopeId));
}
}
}
private void reloadApiScopeRelationForApiScope(String apiId, String scopeId) throws DAOException {
Set<String> scopeSet = apiScopeMap.computeIfAbsent(apiId, key -> new HashSet<String>());
scopeSet.remove(scopeId);
logger.debug(String.format("Type=%s, ID=%s, %s removed", ReloadApiScopeCommand.COMMAND_TYPE_API_SCOPE, apiId,
scopeId));
if (scopeDAO.hasApiScopeRelation(apiId, scopeId)) {
scopeSet.add(scopeId);
logger.debug(String.format("Type=%s, ID=%s, %s added", ReloadApiScopeCommand.COMMAND_TYPE_API_SCOPE, apiId,
scopeId));
}
}
public ClientVO getClientVO(String clientId){
ClientDetails clientDetails = clientDetailsStore.get(clientId);
if(clientDetails instanceof ClientVO){
return (ClientVO) clientDetails;
}
return null;
}
}
@@ -0,0 +1,37 @@
package com.eactive.eai.authserver.service;
import org.springframework.beans.factory.annotation.Autowired;
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.eactive.eai.authserver.dao.UserDAO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.util.Logger;
@Service("eLinkUserDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
@Autowired
private UserDAO userDAO;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
logger.debug("UserDetailsServiceImpl.loadUserByUsername :::: {}", username);
UserDetails user = null;
try {
user = userDAO.getUserByUserId(username);
} catch (DAOException e) {
logger.error(e.getMessage());
}
if (user == null) {
throw new UsernameNotFoundException(username + " is not found.");
}
return user;
}
}
@@ -0,0 +1,13 @@
package com.eactive.eai.authserver.util;
import com.eactive.eai.common.util.ApplicationContextProvider;
public class BeanUtils {
public static <T> T getBean(String beanId, Class<T> cls) {
return ApplicationContextProvider.getContext().getBean(beanId, cls);
}
public static <T> T getBean(Class<T> cls) {
return ApplicationContextProvider.getContext().getBean(cls);
}
}
@@ -0,0 +1,29 @@
package com.eactive.eai.authserver.vo;
import com.eactive.eai.common.message.EAIMessage;
import lombok.Data;
import org.hibernate.annotations.Comment;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("serial")
@Data
public class ClientVO extends BaseClientDetails {
private String clientName;
private String allowedIp;
private String modifiedOn;
private String modifiedBy;
private String issuer;
private String audience;
private String securityKey;
private String orgId;
private String orgName;
private String appStatus;
private int dailyTokenLimit;
private Map<String, EAIMessage> apiMap = new HashMap<>();
}