ADSyncService.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. package com.uas.eis.serviceImpl;
  2. import com.uas.eis.core.LdapConnectionManager;
  3. import com.uas.eis.core.config.ADConfig;
  4. import com.uas.eis.dao.BaseDao;
  5. import com.uas.eis.entity.ADUser;
  6. import com.uas.eis.entity.Employee;
  7. import com.uas.eis.entity.HrOrg;
  8. import com.uas.eis.utils.PinyinUtils;
  9. import com.uas.eis.utils.StringUtil;
  10. import org.apache.directory.api.ldap.model.cursor.CursorException;
  11. import org.apache.directory.api.ldap.model.cursor.EntryCursor;
  12. import org.apache.directory.api.ldap.model.entry.*;
  13. import org.apache.directory.api.ldap.model.exception.LdapException;
  14. import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException;
  15. import org.apache.directory.api.ldap.model.message.ModifyDnRequest;
  16. import org.apache.directory.api.ldap.model.message.SearchScope;
  17. import org.apache.directory.api.ldap.model.name.Rdn;
  18. import org.apache.directory.ldap.client.api.LdapConnection;
  19. import org.apache.directory.api.ldap.model.name.Dn;
  20. import org.slf4j.Logger;
  21. import org.slf4j.LoggerFactory;
  22. import org.springframework.beans.factory.annotation.Autowired;
  23. import org.springframework.context.annotation.Lazy;
  24. import org.springframework.stereotype.Service;
  25. import java.io.IOException;
  26. import java.io.UnsupportedEncodingException;
  27. import java.util.*;
  28. @Service
  29. public class ADSyncService {
  30. private final Logger logger = LoggerFactory.getLogger(getClass());
  31. @Autowired
  32. @Lazy
  33. private LdapConnectionManager ldapConnectionManager;
  34. @Autowired
  35. private ADConfig adConfig;
  36. @Autowired
  37. private BaseDao baseDao;
  38. @Autowired
  39. private UasSyncService uasSyncService;
  40. public void syncUser() throws IOException {
  41. LdapConnection connection = ldapConnectionManager.getConnection();
  42. List<Employee> employeeList = uasSyncService.getADUserList();
  43. List<ADUser> adUserList = getUsers(connection);
  44. List<HrOrg> orgList = uasSyncService.getADOrgList();
  45. for (Employee employee : employeeList) {
  46. if(employee.getEm_adid()!=null){
  47. //判断是否需要更新组织
  48. if("离职".equals(employee.getEm_class())){
  49. deleteUser(employee.getEm_adid(),connection);
  50. baseDao.updateByCondition("employee","em_adid=null","em_code='"+employee.getEm_code()+"'");
  51. }
  52. Optional<HrOrg> orgOptional = orgList.stream().filter(org -> org.getOr_code().equals(employee.getOrcode())).findFirst();
  53. logger.info("同步用户更新:{}",employee.getEm_name());
  54. if(orgOptional.isPresent()){
  55. String newOUPath = getOUPath(orgOptional.get().getOr_path());
  56. logger.info("同步用户更新:oldpath{},newpath{}",getUserOUPath(employee.getEm_adid()),newOUPath);
  57. if(employee.getEm_code().equals("ADMIN") && !getUserOUPath(employee.getEm_adid()).equals(newOUPath)){
  58. moveUser(employee.getEm_adid(),"CN="+employee.getEm_name()+","+newOUPath,connection);
  59. baseDao.updateByCondition("employee","em_adid='CN="+employee.getEm_name()+","+newOUPath+"'","em_code='"+employee.getEm_code()+"'");
  60. }
  61. }
  62. }else if (!"生产序列--普工".equals(employee.getEm_emptype()) && !"其它人员".equals(employee.getEm_emptype())) {
  63. Optional<HrOrg> orgOptional = orgList.stream().filter(org -> org.getOr_code().equals(employee.getOrcode())).findFirst();
  64. if(orgOptional.isPresent()){
  65. String ouPath = getOUPath(orgOptional.get().getOr_path());
  66. addUser(PinyinUtils.getCustomPinyin(employee.getEm_name()),employee.getEm_name(),ouPath,employee.getEm_password());
  67. baseDao.updateByCondition("employee","em_adid='CN="+employee.getEm_name()+","+ouPath+"'","em_code='"+employee.getEm_code()+"'");
  68. }
  69. }
  70. }
  71. }
  72. public void addUser(String userName,String displayName, String ouName, String password) {
  73. LdapConnection connection = ldapConnectionManager.getConnection();
  74. Dn dn = null;
  75. logger.info("添加用户:{},displayName:{},ouName:{},password{}",userName,displayName,ouName,password);
  76. try {
  77. dn = new Dn("CN="+displayName+"," + ouName);
  78. Entry entry = new DefaultEntry(
  79. dn,
  80. "objectClass: top",
  81. "objectClass: person",
  82. "objectClass: organizationalPerson",
  83. "objectClass: user",
  84. "sAMAccountName: " + userName,
  85. "userPrincipalName: " + userName + "@" + adConfig.getBaseDn().replace("DC=", "").replace(",", "."),
  86. "userPassword: " + password
  87. );
  88. //处理中文写入异常问题
  89. entry.add("cn",displayName);
  90. entry.add("displayName",displayName);
  91. entry.add("givenName", displayName.substring(0, 1));
  92. entry.add("sn", displayName.substring(1));
  93. connection.add(entry);
  94. } catch (Exception e) {
  95. logger.error("添加用户失败:{},错误{}",userName,e.getMessage());
  96. }
  97. }
  98. public void deleteUser(String userDn, LdapConnection connection) {
  99. if(connection==null || !connection.isConnected()){
  100. connection = ldapConnectionManager.getConnection();
  101. }
  102. try {
  103. logger.info("删除用户:{}",userDn);
  104. Dn dn = new Dn(userDn);
  105. connection.delete(dn);
  106. logger.info("删除用户成功:{}",userDn);
  107. } catch (LdapException e) {
  108. logger.error("删除用户失败:{}",userDn);
  109. }
  110. }
  111. public void moveUser(String oldUserDnStr, String newRdnStr, LdapConnection connection) {
  112. logger.info("用户 {} 移动组织 {}", oldUserDnStr, newRdnStr);
  113. if (connection == null || !connection.isConnected()) {
  114. connection = ldapConnectionManager.getConnection();
  115. }
  116. try {
  117. connection.moveAndRename(oldUserDnStr, newRdnStr,true);
  118. logger.info("用户 {} 已成功移动到组织 {}", oldUserDnStr, newRdnStr);
  119. } catch (Exception e) {
  120. logger.error("移动用户失败: {}", oldUserDnStr, e);
  121. throw new RuntimeException("移动用户失败: " + e.getMessage());
  122. }
  123. }
  124. //初始化用户
  125. public void initUser() throws IOException {
  126. LdapConnection connection = ldapConnectionManager.getConnection();
  127. List<Employee> employeeList = uasSyncService.getADUserList();
  128. List<ADUser> adUserList = getUsers(connection);
  129. for (ADUser adUser : adUserList) {
  130. for (Employee employee : employeeList) {
  131. if(employee.getEm_name().equals(adUser.getUserCn())){
  132. baseDao.updateByCondition("employee","em_adid='"+adUser.getUserDn()+"'", "em_code ='"+employee.getEm_code()+"'");
  133. break;
  134. }
  135. }
  136. }
  137. }
  138. public List<ADUser> getUsers(LdapConnection connection) throws IOException {
  139. List<ADUser> userList = new ArrayList<>();
  140. if(connection==null || !connection.isConnected()){
  141. connection = ldapConnectionManager.getConnection();
  142. }
  143. try {
  144. // 搜索所有用户
  145. String filter = "(objectClass=organizationalPerson)";
  146. EntryCursor result = connection.search(
  147. "OU=User,"+adConfig.getBaseDn(), // AD基础DN,从配置文件获取
  148. filter,
  149. SearchScope.SUBTREE
  150. );
  151. Entry entry;
  152. while (result.next()) {
  153. try {
  154. entry =result.get();
  155. ADUser adUser = new ADUser();
  156. adUser.setUserDn(entry.getDn().toString());
  157. adUser.setUserCn(entry.get("cn").get().getString());
  158. adUser.setAccountName(entry.get("sAMAccountName").get().getString());
  159. adUser.setUserPrincipalName(entry.get("userPrincipalName").get().getString());
  160. userList.add(adUser);
  161. } catch (CursorException e) {
  162. e.printStackTrace();
  163. }
  164. }
  165. return userList;
  166. } catch (LdapException e) {
  167. e.printStackTrace();
  168. } catch (CursorException e) {
  169. e.printStackTrace();
  170. } finally {
  171. if (connection != null) {
  172. connection.close();
  173. }
  174. }
  175. return null;
  176. }
  177. public void syncOrg() throws IOException {
  178. LdapConnection connection = ldapConnectionManager.getConnection();
  179. List<HrOrg> orgList = uasSyncService.getADOrgList();
  180. logger.info("同步组织数量:{}",orgList.size());
  181. List<String> orgDns = getOrganizations(connection);
  182. //判断组织是否存在
  183. for (HrOrg org : orgList) {
  184. if("已审核".equals(org.getOr_status())) {
  185. if(!orgDns.isEmpty()){
  186. boolean isExist = false;
  187. for(String orgDn : orgDns){
  188. String orgDescription = orgDn.substring(orgDn.indexOf(";")+1);
  189. String orgPath = orgDn.split(";")[0];
  190. // 组织编号匹配成功
  191. if(StringUtil.hasText(orgDescription) && orgDescription.equals(org.getOr_code())){
  192. //组织编号一致
  193. if(! orgPath.startsWith(getOUPath(org.getOr_path()))){
  194. //组织路径不一致,则更新组织层级信息
  195. logger.info("updateOrg 更新组织信息:old{},new{},orgCode{}",orgPath,getOUPath(org.getOr_path()) , orgDescription);
  196. updateOrg(orgPath, getOUPath(org.getOr_path()), connection);
  197. }
  198. isExist =true;
  199. break;
  200. }
  201. //组织编号匹配不成功,路径匹配相同
  202. if(orgPath.equals(getOUPath(org.getOr_path()))){
  203. if(!StringUtil.hasText(orgDescription)){
  204. //更新AD域组织编号信息
  205. updateOrgDescription(orgDn.split(";")[0], org.getOr_code());
  206. }
  207. isExist =true;
  208. break;
  209. }
  210. }
  211. //不存在的组织
  212. if(!isExist){
  213. //添加组织
  214. addOrg(org, connection);
  215. }
  216. }
  217. }
  218. }
  219. //判断AD域组织存在但没有已审核的组织信息,删除AD域组织
  220. for(String orgDn : orgDns){
  221. String orgDescription = orgDn.substring(orgDn.indexOf(";")+1);
  222. if(StringUtil.hasText(orgDescription)){
  223. //未成功匹配的组织资料
  224. if(!orgList.stream().anyMatch(org -> !"已禁用".equals(org.getOr_status()) && org.getOr_code().equals(orgDescription))){
  225. //删除AD域组织
  226. deleteOrg(orgDn.split(";")[0], connection);
  227. }
  228. }
  229. }
  230. }
  231. public void addOrg(HrOrg org, LdapConnection connection) {
  232. if(connection==null || !connection.isConnected()){
  233. connection=ldapConnectionManager.getConnection();
  234. }
  235. try {
  236. logger.info("添加组织{}",org.getOr_path());
  237. Dn dn = new Dn(getOUPath(org.getOr_path()));
  238. Entry entry = new DefaultEntry(
  239. dn,
  240. "objectClass: top",
  241. "objectClass: organizationalUnit"
  242. );
  243. entry.add("description", org.getOr_code());
  244. connection.add(entry);
  245. logger.info("添加组织{}成功",org.getOr_path());
  246. } catch (Exception e) {
  247. logger.error("添加组织失败",e);
  248. }
  249. }
  250. public void deleteOrg(String ouName, LdapConnection connection) {
  251. if(connection==null || !connection.isConnected()){
  252. connection=ldapConnectionManager.getConnection();
  253. }
  254. Dn dn = null;
  255. logger.info("删除组织{}",ouName);
  256. try {
  257. dn = new Dn( ouName );
  258. String filter = "(objectClass=organizationalUnit)||(objectClass=user)";
  259. EntryCursor result = connection.search(
  260. ouName,
  261. filter,
  262. SearchScope.ONELEVEL, // 搜索所有子节点
  263. "dn"
  264. );
  265. if (result.next()) {
  266. System.out.println(result.get().toString());
  267. logger.info("组织下存在下级,无法删除{}",ouName);
  268. }else {
  269. connection.delete(dn);
  270. }
  271. } catch (Exception e) {
  272. throw new RuntimeException(e);
  273. }
  274. logger.info("删除组织{}成功",ouName);
  275. }
  276. public void updateOrg(String oldOUName,String newOuName, LdapConnection connection) {
  277. if(connection==null || !connection.isConnected()){
  278. connection=ldapConnectionManager.getConnection();
  279. }
  280. logger.info("更新组织{}为{}",oldOUName,newOuName);
  281. try {
  282. connection.moveAndRename(oldOUName,newOuName,true);
  283. } catch (Exception e) {
  284. logger.error(e.getMessage());
  285. e.printStackTrace();
  286. }
  287. logger.info("更新组织{}为{} 成功",oldOUName,newOuName);
  288. }
  289. /**
  290. * 修改自定义description属性
  291. * */
  292. public void updateOrgDescription(String orgName, String newDescription) throws IOException {
  293. LdapConnection connection = null;
  294. try {
  295. connection = ldapConnectionManager.getConnection();
  296. Dn dn = new Dn( orgName);
  297. Entry entry = new DefaultEntry(
  298. dn,
  299. "objectClass: top",
  300. "objectClass: organizationalUnit"
  301. );
  302. connection.modify(dn, new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, "description", newDescription));
  303. } catch (Exception e) {
  304. logger.info("updateOrgDescription 更新组织描述失败:{}",e.getMessage());
  305. }finally {
  306. if (connection != null) {
  307. connection.close();
  308. }
  309. }
  310. }
  311. /**
  312. * 通过自定义description查看组织信息
  313. * */
  314. public List<String> findOrganizationsByDescription(String description) throws IOException {
  315. LdapConnection connection = null;
  316. try {
  317. connection = ldapConnectionManager.getConnection();
  318. // 设置LDAP搜索过滤器,匹配organizationalUnit且description包含搜索词
  319. String filter = String.format("(&(objectClass=organizationalUnit)(description=*%s*))", description);
  320. EntryCursor result = connection.search(
  321. adConfig.getBaseDn(), // 从配置的基础DN开始搜索
  322. filter,
  323. SearchScope.SUBTREE, // 搜索所有子节点
  324. "dn" // 只返回DN属性
  325. );
  326. List<String> orgDns = new ArrayList<>();
  327. return orgDns;
  328. } catch (Exception e) {
  329. e.printStackTrace();
  330. }
  331. finally {
  332. if (connection != null) {
  333. connection.close();
  334. }
  335. }
  336. return null;
  337. }
  338. private String getOUPath(String orpath){
  339. String[] paths=orpath.split("-");
  340. String ouPath="";
  341. for(int i=paths.length-1;i>=0;i--){
  342. ouPath+="OU="+paths[i]+",";
  343. }
  344. return ouPath.substring(0,ouPath.length()-1)+",OU=User,"+adConfig.getBaseDn();
  345. }
  346. private String getUserOUPath(String userPath){
  347. return userPath.substring(userPath.indexOf(",")+1);
  348. }
  349. public List<String> getOrganizations(LdapConnection connection) throws IOException {
  350. if(connection==null || !connection.isConnected()){
  351. connection = ldapConnectionManager.getConnection();
  352. }
  353. try {
  354. // 搜索所有组织单元
  355. List<String> orgDns = new ArrayList<>();
  356. String filter = "(objectClass=organizationalUnit)";
  357. EntryCursor result = connection.search(
  358. "OU=User,"+adConfig.getBaseDn(), // AD基础DN,从配置文件获取
  359. filter,
  360. SearchScope.SUBTREE, // 搜索所有子节点
  361. new String[] {"dn", "description"}
  362. );
  363. Entry entry = null;
  364. while (result.next()) {
  365. try {
  366. entry =result.get();
  367. //排除掉根目录
  368. if(!entry.getDn().toString().startsWith("OU=User")){
  369. orgDns.add(String.format("%s;%s", entry.getDn().toString(),
  370. StringUtil.hasText(entry.get("description"))?entry.get("description").get():""));
  371. }
  372. } catch (CursorException e) {
  373. e.printStackTrace();
  374. }
  375. }
  376. return orgDns;
  377. } catch (LdapException e) {
  378. e.printStackTrace();
  379. } catch (CursorException e) {
  380. throw new RuntimeException(e);
  381. } finally {
  382. if (connection != null) {
  383. connection.close();
  384. }
  385. }
  386. return null;
  387. }
  388. }