SysLdapService.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. // 大名科技(天津)有限公司 版权所有
  2. //
  3. // 此源代码遵循位于源代码树根目录中的 LICENSE 文件的许可证
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动
  6. //
  7. // 任何基于本项目二次开发而产生的一切法律纠纷和责任,均与作者无关
  8. using Novell.Directory.Ldap;
  9. namespace Admin.NET.Core;
  10. /// <summary>
  11. /// 系统域登录信息配置表服务
  12. /// </summary>
  13. [ApiDescriptionSettings(Order = 100)]
  14. public class SysLdapService : IDynamicApiController, ITransient
  15. {
  16. private readonly SqlSugarRepository<SysLdap> _sysLdapRep;
  17. private readonly SysUserLdapService _sysUserLdapService;
  18. public SysLdapService(SqlSugarRepository<SysLdap> rep, SysUserLdapService sysUserLdapService)
  19. {
  20. _sysLdapRep = rep;
  21. _sysUserLdapService = sysUserLdapService;
  22. }
  23. /// <summary>
  24. /// 获取系统域登录信息配置分页列表
  25. /// </summary>
  26. /// <param name="input"></param>
  27. /// <returns></returns>
  28. public async Task<SqlSugarPagedList<SysLdap>> Page(SysLdapInput input)
  29. {
  30. return await _sysLdapRep.AsQueryable()
  31. .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u => u.Host.Contains(input.SearchKey.Trim()))
  32. .WhereIF(!string.IsNullOrWhiteSpace(input.Host), u => u.Host.Contains(input.Host.Trim()))
  33. .OrderBy(u => u.CreateTime, OrderByType.Desc)
  34. .ToPagedListAsync(input.Page, input.PageSize);
  35. }
  36. /// <summary>
  37. /// 增加系统域登录信息配置
  38. /// </summary>
  39. /// <param name="input"></param>
  40. /// <returns></returns>
  41. [ApiDescriptionSettings(Name = "Add"), HttpPost]
  42. public async Task<long> Add(AddSysLdapInput input)
  43. {
  44. var entity = input.Adapt<SysLdap>();
  45. entity.BindPass = CryptogramUtil.Encrypt(input.BindPass);
  46. await _sysLdapRep.InsertAsync(entity);
  47. return entity.Id;
  48. }
  49. /// <summary>
  50. /// 更新系统域登录信息配置
  51. /// </summary>
  52. /// <param name="input"></param>
  53. /// <returns></returns>
  54. [ApiDescriptionSettings(Name = "Update"), HttpPost]
  55. public async Task Update(UpdateSysLdapInput input)
  56. {
  57. var entity = input.Adapt<SysLdap>();
  58. if (!string.IsNullOrEmpty(input.BindPass) && input.BindPass.Length < 32)
  59. {
  60. entity.BindPass = CryptogramUtil.Encrypt(input.BindPass); // 加密
  61. }
  62. await _sysLdapRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
  63. }
  64. /// <summary>
  65. /// 删除系统域登录信息配置
  66. /// </summary>
  67. /// <param name="input"></param>
  68. /// <returns></returns>
  69. [ApiDescriptionSettings(Name = "Delete"), HttpPost]
  70. public async Task Delete(DeleteSysLdapInput input)
  71. {
  72. var entity = await _sysLdapRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
  73. await _sysLdapRep.FakeDeleteAsync(entity); // 假删除
  74. //await _rep.DeleteAsync(entity); // 真删除
  75. }
  76. /// <summary>
  77. /// 获取系统域登录信息配置详情
  78. /// </summary>
  79. /// <param name="input"></param>
  80. /// <returns></returns>
  81. [ApiDescriptionSettings(Name = "Detail")]
  82. public async Task<SysLdap> GetDetail([FromQuery] DetailSysLdapInput input)
  83. {
  84. return await _sysLdapRep.GetFirstAsync(u => u.Id == input.Id);
  85. }
  86. /// <summary>
  87. /// 获取系统域登录信息配置列表
  88. /// </summary>
  89. /// <param name="input"></param>
  90. /// <returns></returns>
  91. [ApiDescriptionSettings(Name = "List")]
  92. public async Task<List<SysLdap>> GetList([FromQuery] SysLdapInput input)
  93. {
  94. return await _sysLdapRep.AsQueryable().Select<SysLdap>().ToListAsync();
  95. }
  96. /// <summary>
  97. /// 账号验证
  98. /// </summary>
  99. /// <param name="account">域用户</param>
  100. /// <param name="password">密码</param>
  101. /// <param name="tenantId">租户</param>
  102. /// <returns></returns>
  103. [NonAction]
  104. public async Task<bool> Auth(long tenantId, string account, string password)
  105. {
  106. var ldap = await _sysLdapRep.GetFirstAsync(u => u.TenantId == tenantId) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
  107. var ldapConn = new LdapConnection();
  108. try
  109. {
  110. ldapConn.Connect(ldap.Host, ldap.Port);
  111. ldapConn.Bind(ldap.Version, ldap.BindDn, ldap.BindPass);
  112. var userEntitys = ldapConn.Search(ldap.BaseDn, LdapConnection.ScopeSub, ldap.AuthFilter.Replace("$s", account), null, false);
  113. string dn = string.Empty;
  114. while (userEntitys.HasMore())
  115. {
  116. var entity = userEntitys.Next();
  117. var sAMAccountName = entity.GetAttribute(ldap.AuthFilter)?.StringValue;
  118. if (!string.IsNullOrEmpty(sAMAccountName))
  119. {
  120. dn = entity.Dn;
  121. break;
  122. }
  123. }
  124. if (string.IsNullOrEmpty(dn)) throw Oops.Oh(ErrorCodeEnum.D1002);
  125. var attr = new LdapAttribute("userPassword", password);
  126. ldapConn.Bind(dn, password);
  127. }
  128. catch (LdapException e)
  129. {
  130. switch (e.ResultCode)
  131. {
  132. case LdapException.NoSuchObject:
  133. case LdapException.NoSuchAttribute:
  134. throw Oops.Oh(ErrorCodeEnum.D0009);
  135. case LdapException.InvalidCredentials:
  136. return false;
  137. default:
  138. throw Oops.Oh(e.Message);
  139. }
  140. }
  141. finally
  142. {
  143. ldapConn.Disconnect();
  144. }
  145. return true;
  146. }
  147. /// <summary>
  148. /// 同步域用户
  149. /// </summary>
  150. /// <param name="input"></param>
  151. /// <returns></returns>
  152. [HttpPost]
  153. [ApiDescriptionSettings(Name = "UserSync")]
  154. public async Task UserSync(UserSyncIdSysLdapInput input)
  155. {
  156. var ldap = await _sysLdapRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
  157. LdapConnection ldapConn = new LdapConnection();
  158. try
  159. {
  160. ldapConn.Connect(ldap.Host, ldap.Port);
  161. ldapConn.Bind(ldap.Version, ldap.BindDn, ldap.BindPass);
  162. var userEntitys = ldapConn.Search(ldap.BaseDn, LdapConnection.ScopeOne, "(objectClass=*)", null, false);
  163. string dn = string.Empty;
  164. var listUserLdap = new List<SysUserLdap>();
  165. while (userEntitys.HasMore())
  166. {
  167. LdapEntry entity;
  168. try
  169. {
  170. entity = userEntitys.Next();
  171. if (entity == null) continue;
  172. }
  173. catch (LdapException)
  174. {
  175. continue;
  176. }
  177. var attrs = entity.GetAttributeSet();
  178. if (attrs.Count == 0 || attrs.ContainsKey("OU"))
  179. LdapUserSearchDn(ldapConn, ldap, listUserLdap, entity.Dn);
  180. else
  181. {
  182. var sysUserLdap = new SysUserLdap
  183. {
  184. Account = !attrs.ContainsKey(ldap.BindAttrAccount) ? null : attrs.GetAttribute(ldap.BindAttrAccount)?.StringValue,
  185. EmployeeId = !attrs.ContainsKey(ldap.BindAttrEmployeeId) ? null : attrs.GetAttribute(ldap.BindAttrEmployeeId)?.StringValue
  186. };
  187. if (string.IsNullOrEmpty(sysUserLdap.EmployeeId)) continue;
  188. listUserLdap.Add(sysUserLdap);
  189. }
  190. }
  191. if (listUserLdap.Count == 0)
  192. return;
  193. await _sysUserLdapService.InsertUserLdapsAsync(ldap.TenantId.Value, listUserLdap);
  194. }
  195. catch (LdapException e)
  196. {
  197. switch (e.ResultCode)
  198. {
  199. case LdapException.NoSuchObject:
  200. case LdapException.NoSuchAttribute:
  201. throw Oops.Oh(ErrorCodeEnum.D0009);
  202. case LdapException.InvalidCredentials:
  203. default:
  204. throw Oops.Oh(e.Message);
  205. }
  206. }
  207. finally
  208. {
  209. ldapConn.Disconnect();
  210. }
  211. }
  212. /// <summary>
  213. /// 域用户遍历查询
  214. /// </summary>
  215. /// <param name="conn"></param>
  216. /// <param name="ldap"></param>
  217. /// <param name="listUserLdap"></param>
  218. /// <param name="baseDn"></param>
  219. private void LdapUserSearchDn(LdapConnection conn, SysLdap ldap, List<SysUserLdap> listUserLdap, string baseDn)
  220. {
  221. var userEntitys = conn.Search(baseDn, LdapConnection.ScopeOne, "(objectClass=*)", null, false);
  222. string dn = string.Empty;
  223. while (userEntitys.HasMore())
  224. {
  225. LdapEntry entity;
  226. try
  227. {
  228. entity = userEntitys.Next();
  229. if (entity == null) continue;
  230. }
  231. catch (LdapException)
  232. {
  233. continue;
  234. }
  235. var attrs = entity.GetAttributeSet();
  236. if (attrs.Count == 0 || attrs.ContainsKey("OU"))
  237. LdapUserSearchDn(conn, ldap, listUserLdap, entity.Dn);
  238. else
  239. {
  240. var sysUserLdap = new SysUserLdap
  241. {
  242. Account = !attrs.ContainsKey(ldap.BindAttrAccount) ? null : attrs.GetAttribute(ldap.BindAttrAccount)?.StringValue,
  243. EmployeeId = !attrs.ContainsKey(ldap.BindAttrEmployeeId) ? null : attrs.GetAttribute(ldap.BindAttrEmployeeId)?.StringValue
  244. };
  245. if (string.IsNullOrEmpty(sysUserLdap.EmployeeId)) continue;
  246. listUserLdap.Add(sysUserLdap);
  247. }
  248. }
  249. }
  250. }