ADSyncService.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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() {
  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. disableUser(employee.getEm_adid(),connection);
  50. //baseDao.updateByCondition("employee","em_adid=null","em_code='"+employee.getEm_code()+"'");
  51. }else {
  52. Optional<HrOrg> orgOptional = orgList.stream().filter(org -> org.getOr_code().equals(employee.getOrcode())).findFirst();
  53. logger.info("同步用户更新:{}",employee.getEm_name());
  54. updateUserDescription(employee.getEm_adid(),employee.getEmjob());
  55. if(orgOptional.isPresent()){
  56. String newOUPath = getOUPath(orgOptional.get().getOr_path());
  57. logger.info("同步用户更新:oldpath{},newpath{}",getUserOUPath(employee.getEm_adid()),newOUPath);
  58. if(!getUserOUPath(employee.getEm_adid()).equals(newOUPath)){
  59. moveUser(employee.getEm_adid(),"CN="+employee.getEm_name()+","+newOUPath,connection);
  60. baseDao.updateByCondition("employee","em_adid='CN="+employee.getEm_name()+","+newOUPath+"'","em_code='"+employee.getEm_code()+"'");
  61. }
  62. }
  63. }
  64. }else if (!"其它人员".equals(employee.getEm_emptype()) && !"离职".equals(employee.getEm_class())) {
  65. Optional<HrOrg> orgOptional = orgList.stream().filter(org -> org.getOr_code().equals(employee.getOrcode())).findFirst();
  66. if(orgOptional.isPresent()){
  67. String ouPath = getOUPath(orgOptional.get().getOr_path());
  68. String adid = addUser(employee.getEm_code(),PinyinUtils.getCustomPinyin(employee.getEm_name()),employee.getEm_name(),ouPath,employee.getEm_password(), employee.getEmjob());
  69. if(adid!=null){
  70. baseDao.updateByCondition("employee","em_adid='"+adid+"'","em_code='"+employee.getEm_code()+"'");
  71. }
  72. }
  73. }
  74. }
  75. }
  76. public String addUser(String userCode,String userName,String displayName, String ouName, String password,String job) {
  77. LdapConnection connection = ldapConnectionManager.getConnection();
  78. Dn dn = null;
  79. logger.info("添加用户:{},displayName:{},ouName:{},password{}",userName,displayName,ouName,password);
  80. try {
  81. dn = new Dn("CN="+displayName+"," + ouName);
  82. Entry entry = new DefaultEntry(
  83. dn,
  84. "objectClass: top",
  85. "objectClass: person",
  86. "objectClass: organizationalPerson",
  87. "objectClass: user",
  88. "sAMAccountName: " + userName,
  89. "userPrincipalName: " + userName + "@" + adConfig.getBaseDn().replace("DC=", "").replace(",", "."),
  90. "userPassword: " + password
  91. );
  92. //处理中文写入异常问题
  93. entry.add("cn",displayName);
  94. entry.add("displayName",displayName);
  95. entry.add("givenName", displayName.substring(0, 1));
  96. entry.add("sn", displayName.substring(1));
  97. entry.add("description", job);
  98. entry.add("userAccountControl", "544");
  99. connection.add(entry);
  100. return "CN="+displayName+"," + ouName;
  101. } catch (Exception e) {
  102. if(e.getMessage().contains("(ENTRY_EXISTS)")){
  103. return "CN="+displayName+"," + ouName;
  104. }else if(e.getMessage().contains("problem 1005 (CONSTRAINT_ATT_TYPE), data 0, Att 90290 (userPrincipalName)")) {
  105. return addUser(userCode,userName+""+userCode,displayName,ouName,password,job);
  106. }
  107. logger.error("添加用户失败:{},错误{}",userName,e.getMessage());
  108. return null;
  109. }
  110. }
  111. //更新用户信息
  112. public void updateUserDescription(String userName, String newDescription) {
  113. LdapConnection connection = null;
  114. try {
  115. connection = ldapConnectionManager.getConnection();
  116. Dn dn = new Dn( userName);
  117. Entry entry = new DefaultEntry(
  118. dn,
  119. "objectClass: top",
  120. "objectClass: organizationalPerson"
  121. );
  122. connection.modify(dn, new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, "description", newDescription));
  123. } catch (Exception e) {
  124. logger.info("updateOrgDescription 更新组织描述失败:{}",e.getMessage());
  125. }finally {
  126. if (connection != null) {
  127. try {
  128. connection.close();
  129. } catch (IOException e) {
  130. throw new RuntimeException(e);
  131. }
  132. }
  133. }
  134. }
  135. public void disableUser(String userDn, LdapConnection connection) {
  136. if(connection==null || !connection.isConnected()){
  137. connection = ldapConnectionManager.getConnection();
  138. }
  139. try {
  140. Dn dn = new Dn( userDn);
  141. Entry entry = new DefaultEntry(
  142. dn,
  143. "objectClass: top",
  144. "objectClass: organizationalPerson"
  145. );
  146. connection.modify(dn, new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, "userAccountControl", "2"));
  147. } catch (Exception e) {
  148. logger.info("disableUser 禁用账号失败:{}",e.getMessage());
  149. }finally {
  150. if (connection != null) {
  151. try {
  152. connection.close();
  153. } catch (IOException e) {
  154. throw new RuntimeException(e);
  155. }
  156. }
  157. }
  158. }
  159. public void deleteUser(String userDn, LdapConnection connection) {
  160. if(connection==null || !connection.isConnected()){
  161. connection = ldapConnectionManager.getConnection();
  162. }
  163. try {
  164. logger.info("删除用户:{}",userDn);
  165. Dn dn = new Dn(userDn);
  166. connection.delete(dn);
  167. logger.info("删除用户成功:{}",userDn);
  168. } catch (LdapException e) {
  169. logger.error("删除用户失败:{}",userDn);
  170. }
  171. }
  172. public void moveUser(String oldUserDnStr, String newRdnStr, LdapConnection connection) {
  173. logger.info("用户 {} 移动组织 {}", oldUserDnStr, newRdnStr);
  174. if (connection == null || !connection.isConnected()) {
  175. connection = ldapConnectionManager.getConnection();
  176. }
  177. try {
  178. connection.moveAndRename(oldUserDnStr, newRdnStr,true);
  179. logger.info("用户 {} 已成功移动到组织 {}", oldUserDnStr, newRdnStr);
  180. } catch (Exception e) {
  181. logger.error("移动用户失败: {}", oldUserDnStr, e);
  182. throw new RuntimeException("移动用户失败: " + e.getMessage());
  183. }
  184. }
  185. //初始化用户
  186. public void initUser() throws IOException {
  187. LdapConnection connection = ldapConnectionManager.getConnection();
  188. List<Employee> employeeList = uasSyncService.getADUserList();
  189. List<ADUser> adUserList = getUsers(connection);
  190. List<HrOrg> orgList = uasSyncService.getADOrgList();
  191. /* for (ADUser adUser : adUserList) {
  192. System.out.println(adUser.getUserCn());
  193. for (Employee employee : employeeList) {
  194. if(employee.getEm_name().equals(adUser.getUserCn()) && !StringUtil.hasText(employee.getEm_adid()) ){
  195. baseDao.updateByCondition("employee","em_adid='"+adUser.getUserDn()+"'", "em_code ='"+employee.getEm_code()+"'");
  196. break;
  197. }
  198. }
  199. }*/
  200. for(Employee employee:employeeList){
  201. if(!StringUtil.hasText(employee.getEm_adid())){
  202. Optional<ADUser> adUserOptional = adUserList.stream().filter(adUser -> adUser.getUserDn().equals(employee.getEm_adid())).findFirst();
  203. if(!adUserOptional.isPresent()){
  204. //System.out.println("用户不存在:"+employee.getEm_adid()+"-"+employee.getEm_name());
  205. //baseDao.updateByCondition("employee","em_adid=null", "em_code ='"+employee.getEm_code()+"'");
  206. if(!"其它人员".equals(employee.getEm_emptype()) && !"离职".equals(employee.getEm_class())) {
  207. Optional<HrOrg> orgOptional = orgList.stream().filter(org -> org.getOr_code().equals(employee.getOrcode())).findFirst();
  208. if(orgOptional.isPresent()){
  209. String ouPath = getOUPath(orgOptional.get().getOr_path());
  210. String adid = addUser(employee.getEm_code(),PinyinUtils.getCustomPinyin(employee.getEm_name()),employee.getEm_name(),ouPath,employee.getEm_password(), employee.getEmjob());
  211. if(adid!=null){
  212. baseDao.updateByCondition("employee","em_adid='"+adid+"'","em_code='"+employee.getEm_code()+"'");
  213. }
  214. }
  215. }
  216. }
  217. }
  218. }
  219. //移动人员组织
  220. }
  221. public List<ADUser> getUsers(LdapConnection connection) throws IOException {
  222. List<ADUser> userList = new ArrayList<>();
  223. if(connection==null || !connection.isConnected()){
  224. connection = ldapConnectionManager.getConnection();
  225. }
  226. try {
  227. // 搜索所有用户
  228. String filter = "(objectClass=organizationalPerson)";
  229. EntryCursor result = connection.search(
  230. "OU=User,"+adConfig.getBaseDn(), // AD基础DN,从配置文件获取
  231. filter,
  232. SearchScope.SUBTREE
  233. );
  234. Entry entry;
  235. while (result.next()) {
  236. try {
  237. entry =result.get();
  238. ADUser adUser = new ADUser();
  239. adUser.setUserDn(entry.getDn().toString());
  240. adUser.setUserCn(entry.get("cn").get().getString());
  241. adUser.setAccountName(entry.get("sAMAccountName").get().getString());
  242. adUser.setUserPrincipalName(entry.get("userPrincipalName").get().getString());
  243. userList.add(adUser);
  244. } catch (CursorException e) {
  245. e.printStackTrace();
  246. }
  247. }
  248. return userList;
  249. } catch (LdapException e) {
  250. e.printStackTrace();
  251. } catch (CursorException e) {
  252. e.printStackTrace();
  253. } finally {
  254. if (connection != null) {
  255. connection.close();
  256. }
  257. }
  258. return null;
  259. }
  260. public void syncOrg() {
  261. LdapConnection connection = ldapConnectionManager.getConnection();
  262. List<HrOrg> orgList = uasSyncService.getADOrgList();
  263. logger.info("同步组织数量:{}",orgList.size());
  264. List<String> orgDns = getOrganizations(connection);
  265. //判断组织是否存在
  266. for (HrOrg org : orgList) {
  267. if("已审核".equals(org.getOr_status())) {
  268. if(!orgDns.isEmpty()){
  269. boolean isExist = false;
  270. for(String orgDn : orgDns){
  271. String orgDescription = orgDn.substring(orgDn.indexOf(";")+1);
  272. String orgPath = orgDn.split(";")[0];
  273. // 组织编号匹配成功
  274. if(StringUtil.hasText(orgDescription) && orgDescription.equals(org.getOr_code())){
  275. //组织编号一致
  276. if(! orgPath.startsWith(getOUPath(org.getOr_path()))){
  277. //组织路径不一致,则更新组织层级信息
  278. logger.info("updateOrg 更新组织信息:old{},new{},orgCode{}",orgPath,getOUPath(org.getOr_path()) , orgDescription);
  279. updateOrg(orgPath, getOUPath(org.getOr_path()), connection);
  280. }
  281. isExist =true;
  282. break;
  283. }
  284. //组织编号匹配不成功,路径匹配相同
  285. if(orgPath.equals(getOUPath(org.getOr_path()))){
  286. if(!StringUtil.hasText(orgDescription)){
  287. //更新AD域组织编号信息
  288. updateOrgDescription(orgDn.split(";")[0], org.getOr_code());
  289. }
  290. isExist =true;
  291. break;
  292. }
  293. }
  294. //不存在的组织
  295. if(!isExist){
  296. //添加组织
  297. addOrg(org, connection);
  298. }
  299. }
  300. }
  301. }
  302. //判断AD域组织存在但没有已审核的组织信息,删除AD域组织
  303. for(String orgDn : orgDns){
  304. String orgDescription = orgDn.substring(orgDn.indexOf(";")+1);
  305. if(StringUtil.hasText(orgDescription)){
  306. //未成功匹配的组织资料
  307. if(!orgList.stream().anyMatch(org -> !"已禁用".equals(org.getOr_status()) && org.getOr_code().equals(orgDescription))){
  308. //删除AD域组织
  309. deleteOrg(orgDn.split(";")[0], connection);
  310. }
  311. }
  312. }
  313. }
  314. public void addOrg(HrOrg org, LdapConnection connection) {
  315. if(connection==null || !connection.isConnected()){
  316. connection=ldapConnectionManager.getConnection();
  317. }
  318. try {
  319. logger.info("添加组织{}",org.getOr_path());
  320. Dn dn = new Dn(getOUPath(org.getOr_path()));
  321. Entry entry = new DefaultEntry(
  322. dn,
  323. "objectClass: top",
  324. "objectClass: organizationalUnit"
  325. );
  326. entry.add("description", org.getOr_code());
  327. connection.add(entry);
  328. logger.info("添加组织{}成功",org.getOr_path());
  329. } catch (Exception e) {
  330. logger.error("添加组织失败",e);
  331. }
  332. }
  333. public void deleteOrg(String ouName, LdapConnection connection) {
  334. if(connection==null || !connection.isConnected()){
  335. connection=ldapConnectionManager.getConnection();
  336. }
  337. Dn dn = null;
  338. logger.info("删除组织{}",ouName);
  339. try {
  340. dn = new Dn( ouName );
  341. String filter = "(objectClass=organizationalUnit)||(objectClass=user)";
  342. EntryCursor result = connection.search(
  343. ouName,
  344. filter,
  345. SearchScope.ONELEVEL, // 搜索所有子节点
  346. "dn"
  347. );
  348. if (result.next()) {
  349. logger.info("组织下存在下级,无法删除{}",ouName);
  350. }else {
  351. connection.delete(dn);
  352. }
  353. } catch (Exception e) {
  354. throw new RuntimeException(e);
  355. }
  356. logger.info("删除组织{}成功",ouName);
  357. }
  358. public void updateOrg(String oldOUName,String newOuName, LdapConnection connection) {
  359. if(connection==null || !connection.isConnected()){
  360. connection=ldapConnectionManager.getConnection();
  361. }
  362. logger.info("更新组织{}为{}",oldOUName,newOuName);
  363. try {
  364. connection.moveAndRename(oldOUName,newOuName,true);
  365. } catch (Exception e) {
  366. logger.error(e.getMessage());
  367. e.printStackTrace();
  368. }
  369. logger.info("更新组织{}为{} 成功",oldOUName,newOuName);
  370. }
  371. /**
  372. * 修改自定义description属性
  373. * */
  374. public void updateOrgDescription(String orgName, String newDescription) {
  375. LdapConnection connection = null;
  376. try {
  377. connection = ldapConnectionManager.getConnection();
  378. Dn dn = new Dn( orgName);
  379. Entry entry = new DefaultEntry(
  380. dn,
  381. "objectClass: top",
  382. "objectClass: organizationalUnit"
  383. );
  384. connection.modify(dn, new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, "description", newDescription));
  385. } catch (Exception e) {
  386. logger.info("updateOrgDescription 更新组织描述失败:{}",e.getMessage());
  387. }finally {
  388. if (connection != null) {
  389. try {
  390. connection.close();
  391. } catch (IOException e) {
  392. throw new RuntimeException(e);
  393. }
  394. }
  395. }
  396. }
  397. /**
  398. * 通过自定义description查看组织信息
  399. * */
  400. public List<String> findOrganizationsByDescription(String description) throws IOException {
  401. LdapConnection connection = null;
  402. try {
  403. connection = ldapConnectionManager.getConnection();
  404. // 设置LDAP搜索过滤器,匹配organizationalUnit且description包含搜索词
  405. String filter = String.format("(&(objectClass=organizationalUnit)(description=*%s*))", description);
  406. EntryCursor result = connection.search(
  407. adConfig.getBaseDn(), // 从配置的基础DN开始搜索
  408. filter,
  409. SearchScope.SUBTREE, // 搜索所有子节点
  410. "dn" // 只返回DN属性
  411. );
  412. List<String> orgDns = new ArrayList<>();
  413. return orgDns;
  414. } catch (Exception e) {
  415. e.printStackTrace();
  416. }
  417. finally {
  418. if (connection != null) {
  419. connection.close();
  420. }
  421. }
  422. return null;
  423. }
  424. private String getOUPath(String orpath){
  425. String[] paths=orpath.split("-");
  426. String ouPath="";
  427. for(int i=paths.length-1;i>=0;i--){
  428. ouPath+="OU="+paths[i]+",";
  429. }
  430. return ouPath.substring(0,ouPath.length()-1)+",OU=User,"+adConfig.getBaseDn();
  431. }
  432. private String getUserOUPath(String userPath){
  433. return userPath.substring(userPath.indexOf(",")+1);
  434. }
  435. public List<String> getOrganizations(LdapConnection connection) {
  436. if(connection==null || !connection.isConnected()){
  437. connection = ldapConnectionManager.getConnection();
  438. }
  439. try {
  440. // 搜索所有组织单元
  441. List<String> orgDns = new ArrayList<>();
  442. String filter = "(objectClass=organizationalUnit)";
  443. EntryCursor result = connection.search(
  444. "OU=User,"+adConfig.getBaseDn(), // AD基础DN,从配置文件获取
  445. filter,
  446. SearchScope.SUBTREE, // 搜索所有子节点
  447. new String[] {"dn", "description"}
  448. );
  449. Entry entry = null;
  450. while (result.next()) {
  451. try {
  452. entry =result.get();
  453. //排除掉根目录
  454. if(!entry.getDn().toString().startsWith("OU=User")){
  455. orgDns.add(String.format("%s;%s", entry.getDn().toString(),
  456. StringUtil.hasText(entry.get("description"))?entry.get("description").get():""));
  457. }
  458. } catch (CursorException e) {
  459. e.printStackTrace();
  460. }
  461. }
  462. return orgDns;
  463. } catch (LdapException e) {
  464. e.printStackTrace();
  465. } catch (CursorException e) {
  466. throw new RuntimeException(e);
  467. } finally {
  468. if (connection != null) {
  469. try {
  470. connection.close();
  471. } catch (IOException e) {
  472. throw new RuntimeException(e);
  473. }
  474. }
  475. }
  476. return null;
  477. }
  478. }