SysLdapService.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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 = 485)]
  14. public class SysLdapService : IDynamicApiController, ITransient
  15. {
  16. private readonly SqlSugarRepository<SysLdap> _sysLdapRep;
  17. public SysLdapService(SqlSugarRepository<SysLdap> sysLdapRep)
  18. {
  19. _sysLdapRep = sysLdapRep;
  20. }
  21. /// <summary>
  22. /// 获取系统域登录配置分页列表
  23. /// </summary>
  24. /// <param name="input"></param>
  25. /// <returns></returns>
  26. [DisplayName("获取系统域登录配置分页列表")]
  27. public async Task<SqlSugarPagedList<SysLdap>> Page(SysLdapInput input)
  28. {
  29. return await _sysLdapRep.AsQueryable()
  30. .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u => u.Host.Contains(input.SearchKey.Trim()))
  31. .WhereIF(!string.IsNullOrWhiteSpace(input.Host), u => u.Host.Contains(input.Host.Trim()))
  32. .OrderBy(u => u.CreateTime, OrderByType.Desc)
  33. .ToPagedListAsync(input.Page, input.PageSize);
  34. }
  35. /// <summary>
  36. /// 增加系统域登录配置
  37. /// </summary>
  38. /// <param name="input"></param>
  39. /// <returns></returns>
  40. [ApiDescriptionSettings(Name = "Add"), HttpPost]
  41. [DisplayName("增加系统域登录配置")]
  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. [DisplayName("更新系统域登录配置")]
  56. public async Task Update(UpdateSysLdapInput input)
  57. {
  58. var entity = input.Adapt<SysLdap>();
  59. if (!string.IsNullOrEmpty(input.BindPass) && input.BindPass.Length < 32)
  60. {
  61. entity.BindPass = CryptogramUtil.Encrypt(input.BindPass); // 加密
  62. }
  63. await _sysLdapRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
  64. }
  65. /// <summary>
  66. /// 删除系统域登录配置
  67. /// </summary>
  68. /// <param name="input"></param>
  69. /// <returns></returns>
  70. [ApiDescriptionSettings(Name = "Delete"), HttpPost]
  71. [DisplayName("删除系统域登录配置")]
  72. public async Task Delete(DeleteSysLdapInput input)
  73. {
  74. var entity = await _sysLdapRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
  75. await _sysLdapRep.FakeDeleteAsync(entity); // 假删除
  76. //await _rep.DeleteAsync(entity); // 真删除
  77. }
  78. /// <summary>
  79. /// 获取系统域登录配置详情
  80. /// </summary>
  81. /// <param name="input"></param>
  82. /// <returns></returns>
  83. [DisplayName("获取系统域登录配置详情")]
  84. public async Task<SysLdap> GetDetail([FromQuery] DetailSysLdapInput input)
  85. {
  86. return await _sysLdapRep.GetFirstAsync(u => u.Id == input.Id);
  87. }
  88. /// <summary>
  89. /// 获取系统域登录配置列表
  90. /// </summary>
  91. /// <returns></returns>
  92. [DisplayName("获取系统域登录配置列表")]
  93. public async Task<List<SysLdap>> GetList()
  94. {
  95. return await _sysLdapRep.AsQueryable().Select<SysLdap>().ToListAsync();
  96. }
  97. /// <summary>
  98. /// 验证账号
  99. /// </summary>
  100. /// <param name="account">域用户</param>
  101. /// <param name="password">密码</param>
  102. /// <param name="tenantId">租户</param>
  103. /// <returns></returns>
  104. [NonAction]
  105. public async Task<bool> AuthAccount(long tenantId, string account, string password)
  106. {
  107. var ldap = await _sysLdapRep.GetFirstAsync(u => u.TenantId == tenantId) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
  108. var ldapConn = new LdapConnection();
  109. try
  110. {
  111. ldapConn.Connect(ldap.Host, ldap.Port);
  112. ldapConn.Bind(ldap.Version, ldap.BindDn, ldap.BindPass);
  113. var userEntitys = ldapConn.Search(ldap.BaseDn, LdapConnection.ScopeSub, ldap.AuthFilter.Replace("$s", account), null, false);
  114. string dn = string.Empty;
  115. while (userEntitys.HasMore())
  116. {
  117. var entity = userEntitys.Next();
  118. var sAMAccountName = entity.GetAttribute(ldap.AuthFilter)?.StringValue;
  119. if (!string.IsNullOrEmpty(sAMAccountName))
  120. {
  121. dn = entity.Dn;
  122. break;
  123. }
  124. }
  125. if (string.IsNullOrEmpty(dn)) throw Oops.Oh(ErrorCodeEnum.D1002);
  126. var attr = new LdapAttribute("userPassword", password);
  127. ldapConn.Bind(dn, password);
  128. }
  129. catch (LdapException e)
  130. {
  131. return e.ResultCode switch
  132. {
  133. LdapException.NoSuchObject or LdapException.NoSuchAttribute => throw Oops.Oh(ErrorCodeEnum.D0009),
  134. LdapException.InvalidCredentials => false,
  135. _ => throw Oops.Oh(e.Message),
  136. };
  137. }
  138. finally
  139. {
  140. ldapConn.Disconnect();
  141. }
  142. return true;
  143. }
  144. /// <summary>
  145. /// 同步域用户
  146. /// </summary>
  147. /// <param name="input"></param>
  148. /// <returns></returns>
  149. [DisplayName("同步域用户")]
  150. public async Task SyncUser(SyncSysLdapInput input)
  151. {
  152. var ldap = await _sysLdapRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
  153. var ldapConn = new LdapConnection();
  154. try
  155. {
  156. ldapConn.Connect(ldap.Host, ldap.Port);
  157. ldapConn.Bind(ldap.Version, ldap.BindDn, ldap.BindPass);
  158. var userEntitys = ldapConn.Search(ldap.BaseDn, LdapConnection.ScopeOne, "(objectClass=*)", null, false);
  159. var listUserLdap = new List<SysUserLdap>();
  160. while (userEntitys.HasMore())
  161. {
  162. LdapEntry entity;
  163. try
  164. {
  165. entity = userEntitys.Next();
  166. if (entity == null) continue;
  167. }
  168. catch (LdapException)
  169. {
  170. continue;
  171. }
  172. var attrs = entity.GetAttributeSet();
  173. if (attrs.Count == 0 || attrs.ContainsKey("OU"))
  174. SearchDnLdapUser(ldapConn, ldap, listUserLdap, entity.Dn);
  175. else
  176. {
  177. var sysUserLdap = new SysUserLdap
  178. {
  179. Account = !attrs.ContainsKey(ldap.BindAttrAccount) ? null : attrs.GetAttribute(ldap.BindAttrAccount)?.StringValue,
  180. EmployeeId = !attrs.ContainsKey(ldap.BindAttrEmployeeId) ? null : attrs.GetAttribute(ldap.BindAttrEmployeeId)?.StringValue
  181. };
  182. if (string.IsNullOrEmpty(sysUserLdap.EmployeeId)) continue;
  183. listUserLdap.Add(sysUserLdap);
  184. }
  185. }
  186. if (listUserLdap.Count == 0)
  187. return;
  188. await App.GetRequiredService<SysUserLdapService>().InsertUserLdaps(ldap.TenantId.Value, listUserLdap);
  189. }
  190. catch (LdapException e)
  191. {
  192. throw e.ResultCode switch
  193. {
  194. LdapException.NoSuchObject or LdapException.NoSuchAttribute => Oops.Oh(ErrorCodeEnum.D0009),
  195. _ => Oops.Oh(e.Message),
  196. };
  197. }
  198. finally
  199. {
  200. ldapConn.Disconnect();
  201. }
  202. }
  203. /// <summary>
  204. /// 遍历查询域用户
  205. /// </summary>
  206. /// <param name="conn"></param>
  207. /// <param name="ldap"></param>
  208. /// <param name="listUserLdap"></param>
  209. /// <param name="baseDn"></param>
  210. private static void SearchDnLdapUser(LdapConnection conn, SysLdap ldap, List<SysUserLdap> listUserLdap, string baseDn)
  211. {
  212. var userEntitys = conn.Search(baseDn, LdapConnection.ScopeOne, "(objectClass=*)", null, false);
  213. while (userEntitys.HasMore())
  214. {
  215. LdapEntry entity;
  216. try
  217. {
  218. entity = userEntitys.Next();
  219. if (entity == null) continue;
  220. }
  221. catch (LdapException)
  222. {
  223. continue;
  224. }
  225. var attrs = entity.GetAttributeSet();
  226. if (attrs.Count == 0 || attrs.ContainsKey("OU"))
  227. SearchDnLdapUser(conn, ldap, listUserLdap, entity.Dn);
  228. else
  229. {
  230. var sysUserLdap = new SysUserLdap
  231. {
  232. Account = !attrs.ContainsKey(ldap.BindAttrAccount) ? null : attrs.GetAttribute(ldap.BindAttrAccount)?.StringValue,
  233. EmployeeId = !attrs.ContainsKey(ldap.BindAttrEmployeeId) ? null : attrs.GetAttribute(ldap.BindAttrEmployeeId)?.StringValue
  234. };
  235. if (string.IsNullOrEmpty(sysUserLdap.EmployeeId)) continue;
  236. listUserLdap.Add(sysUserLdap);
  237. }
  238. }
  239. }
  240. }