public static Dictionary <string, object> ToDictonary(this System.DirectoryServices.PropertyCollection Collection, string[] ToAdd = null) { if (Collection == null) { throw new ArgumentNullException("Collection", "DirectoryServices PropertyCollection is null"); } Dictionary <string, object> values = new Dictionary <string, object>(Collection.Count); IEnumerable <string> propertynames; if (ToAdd != null) { propertynames = from name in (new PropertyNameCollectionEnumerable(Collection.PropertyNames)) where ToAdd.Contains(name) select name; } else { propertynames = new PropertyNameCollectionEnumerable(Collection.PropertyNames); } foreach (string name in propertynames) { values.Add(name, Collection[name].Value); } return(values); }
private static bool IsValidUserName(string un) { try { try { //attempt to get information from AD string domain = GetFqd((!string.IsNullOrEmpty(un) && un.Contains("\\") ? un.Split('\\')[0] : string.Empty)); using (System.DirectoryServices.AccountManagement.PrincipalContext ctx = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, domain)) { using (System.DirectoryServices.AccountManagement.UserPrincipal up = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(ctx, un ?? throw new ArgumentNullException(nameof(un)))) { if (up != null) { using (System.DirectoryServices.DirectoryEntry de = (System.DirectoryServices.DirectoryEntry)up.GetUnderlyingObject()) { System.DirectoryServices.PropertyCollection pc = de.Properties; //all properties AD maintains for a user //List<string> availableProperties = new List<string>(); //foreach (string pn in pc.PropertyNames) //{ // availableProperties.Add(String.Format("{0} -> {1}", pn, pc[pn].Value)); //} _UserInfo = new AdUser() { ObjectGuid = BitConverter.ToString((byte[])pc["objectguid"].Value) .Replace("-", string.Empty), UserName = un, EmployeeNumber = (string)pc["employeenumber"].Value, FirstName = up.GivenName, MiddleName = up.MiddleName, LastName = up.Surname, DisplayName = up.DisplayName, EmailAddress = up.EmailAddress, OfficePhoneNumber = up.VoiceTelephoneNumber, MobilePhoneNumber = (string)pc["mobile"].Value, Title = (string)pc["title"].Value }; } } } } } catch { _UserInfo = null; } return(true); //valid/active user } catch (Exception ex) { Log(ex, MethodBase.GetCurrentMethod()); } return(false); }
/// <summary> /// This function will take a DL or Group name and return list of users /// </summary> /// <param name="groupName"></param> /// <returns></returns> public List <ADUserDetail> GetUserFromGroup(String groupName) { List <ADUserDetail> userlist = new List <ADUserDetail>(); try { using (HostingEnvironment.Impersonate()) { _directoryEntry = null; DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot); directorySearch.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))"; SearchResult results = directorySearch.FindOne(); if (results != null) { DirectoryEntry deGroup = new DirectoryEntry(results.Path); //, LDAPUser, LDAPPassword); System.DirectoryServices.PropertyCollection pColl = deGroup.Properties; int count = pColl["member"].Count; for (int i = 0; i < count; i++) { string respath = results.Path; string[] pathnavigate = respath.Split("CN".ToCharArray()); respath = pathnavigate[0]; string objpath = pColl["member"][i].ToString(); string path = respath + objpath; DirectoryEntry user = new DirectoryEntry(path); //, LDAPUser, LDAPPassword); ADUserDetail userobj = ADUserDetail.GetUser(user); userlist.Add(userobj); user.Close(); } } return(userlist); } } catch (Exception ex) { return(userlist); } }
/// <summary> /// 验证域用户 /// </summary> /// <param name="account">域账号</param> /// <param name="password">密码</param> /// <returns></returns> public object queryUser() { try { string accounts = HttpContext.Current.Request["accounts"]; StringBuilder sb = new StringBuilder(); string domainIP = Config.GetValue("DomainName"); //域名 string userAccount = Config.GetValue("Account"); //域账号 string Password = Config.GetValue("Pwd"); //域账号密码 using (System.DirectoryServices.DirectoryEntry deUser = new System.DirectoryServices.DirectoryEntry(@"LDAP://" + domainIP, userAccount, Password)) { System.DirectoryServices.DirectorySearcher src = new System.DirectoryServices.DirectorySearcher(deUser); if (!string.IsNullOrWhiteSpace(accounts)) { StringBuilder sbAcounts = new StringBuilder(); string[] arr = accounts.Split(','); foreach (string str in arr) { sbAcounts.AppendFormat("(sAMAccountName=*{0})", accounts); } src.Filter = string.Format("(&(objectClass=user)(company=*广西华昇新材料有限公司)(|({0})))", sbAcounts.ToString());//筛选条件 } else { src.Filter = "(&(objectClass=user)(company=*广西华昇新材料有限公司))";//筛选条件 } src.SearchRoot = deUser; src.SearchScope = System.DirectoryServices.SearchScope.Subtree; System.DirectoryServices.SearchResultCollection results = src.FindAll(); sb.AppendFormat("总共{0}条记录\n", results.Count); foreach (System.DirectoryServices.SearchResult result in results) { System.DirectoryServices.PropertyCollection rprops = result.GetDirectoryEntry().Properties; string account = ""; //获取账号 if (rprops["sAMAccountName"] != null) { if (rprops["sAMAccountName"].Value != null) { account = rprops["sAMAccountName"].Value.ToString(); } } string realName = ""; //获取姓名 if (rprops["displayName"] != null) { if (rprops["displayName"].Value != null) { realName = rprops["displayName"].Value.ToString(); } } string mobile = ""; //获取手机号 if (rprops["telephoneNumber"] != null) { if (rprops["telephoneNumber"].Value != null) { mobile = rprops["telephoneNumber"].Value.ToString(); } } string department = ""; //获取部门名称 if (rprops["department"] != null) { if (rprops["department"].Value != null) { department = rprops["department"].Value.ToString(); } } sb.AppendFormat("账号:{0},姓名:{1},手机号:{2},部门:{3}\n", account, realName, mobile, department); sb.Append("\n"); } } return(new { code = 0, message = sb.ToString() }); } catch (Exception ex) { System.IO.File.AppendAllText(string.Format(@"D:\logs\{0}.log", DateTime.Now.ToString("yyyyMMdd")), ex.Message); return(new { code = 1, message = ex.Message }); } }
// GET api/<controller>/5 /// <summary> /// 获取域用户信息并更新系统用户(广西华昇) /// </summary> /// <param name="accounts">需要同步的用户账号(多个用逗号分隔)</param> /// <param name="orgId">单位Id</param> /// <returns></returns> public object SyncUser(string orgId = "2b322255-c10b-a8e6-8bd1-d2fcc7e677f8") { try { string accounts = HttpContext.Current.Request["accounts"]; //需要更新的账号,为空则获取更新所有匹配的用户 StringBuilder sb = new StringBuilder(); string domainIP = Config.GetValue("DomainName"); //域名 string userAccount = Config.GetValue("Account"); //域账号 string Password = Config.GetValue("Pwd"); //域账号密码 using (System.DirectoryServices.DirectoryEntry deUser = new System.DirectoryServices.DirectoryEntry(@"LDAP://" + domainIP, userAccount, Password)) { System.DirectoryServices.DirectorySearcher src = new System.DirectoryServices.DirectorySearcher(deUser); if (!string.IsNullOrWhiteSpace(accounts)) { StringBuilder sbAcounts = new StringBuilder(); string[] arr = accounts.Split(','); foreach (string str in arr) { sbAcounts.AppendFormat("(sAMAccountName=*{0})", accounts); } src.Filter = string.Format("(&(objectClass=user)(company=*广西华昇新材料有限公司)(|({0})))", sbAcounts.ToString());//筛选条件 } else { src.Filter = "(&(objectClass=user)(company=*广西华昇新材料有限公司))";//筛选条件 } //src.PropertiesToLoad.Add("cn"); src.SearchRoot = deUser; src.SearchScope = System.DirectoryServices.SearchScope.Subtree; System.DirectoryServices.SearchResultCollection results = src.FindAll(); sb.AppendFormat("总共{0}条记录\n", results.Count); List <object> list = new List <object>(); List <UserEntity> lstUsers = new List <UserEntity>(); DepartmentEntity org = deptBll.GetEntity(orgId); string orgCode = org.EnCode; foreach (System.DirectoryServices.SearchResult result in results) { System.DirectoryServices.PropertyCollection rprops = result.GetDirectoryEntry().Properties; string account = ""; //获取账号 if (rprops["sAMAccountName"] != null) { if (rprops["sAMAccountName"].Value != null) { account = rprops["sAMAccountName"].Value.ToString(); } } string realName = ""; //获取姓名 if (rprops["displayName"] != null) { if (rprops["displayName"].Value != null) { realName = rprops["displayName"].Value.ToString(); } } string mobile = ""; //获取手机号 if (rprops["telephoneNumber"] != null) { if (rprops["telephoneNumber"].Value != null) { mobile = rprops["telephoneNumber"].Value.ToString(); } } string department = ""; string deptId = ""; //部门ID string deptCode = ""; //部门编码 string pxDeptId = ""; //培训平台部门ID string pxDeptCode = ""; //培训平台部门编码 string roleId = ""; //角色ID string roleName = ""; //角色名称 //获取部门名称 if (rprops["department"] != null) { if (rprops["department"].Value != null) { department = rprops["department"].Value.ToString(); System.Data.DataTable dtDept = new System.Data.DataTable(); System.Data.DataTable dtRole = new System.Data.DataTable(); if (department == "公司领导") { deptId = pxDeptId = orgId; deptCode = pxDeptCode = orgCode; dtDept = deptBll.GetDataTable(string.Format("select d.departmentid,d.encode,d.deptkey from base_department d where departmentid='{0}'", orgId)); //如果是公司领导则赋予普通用户和公司级用户角色 dtRole = deptBll.GetDataTable(string.Format("select r.roleid,r.fullname from base_role r where r.category=1 and fullname in('普通用户','公司级用户')")); } else //如果是部门 { dtDept = deptBll.GetDataTable(string.Format("select d.departmentid,d.encode,d.deptkey from base_department d where organizeid='{1}' and d.fullname='{0}'", department, orgId)); //如果是公司领导则赋予普通用户和部门级用户角色 dtRole = deptBll.GetDataTable(string.Format("select r.roleid,r.fullname from base_role r where r.category=1 and fullname in('普通用户','部门级用户')")); } if (dtRole.Rows.Count > 0) { roleId = string.Join(",", dtRole.AsEnumerable().Select(t => t.Field <string>("roleid")).ToArray()); roleName = string.Join(",", dtRole.AsEnumerable().Select(t => t.Field <string>("fullname")).ToArray()); } if (dtDept.Rows.Count > 0) { deptId = pxDeptId = dtDept.Rows[0][0].ToString(); deptCode = pxDeptCode = dtDept.Rows[0][1].ToString(); string deptKey = dtDept.Rows[0][2].ToString(); //转换成培训平台对应的部门ID if (!string.IsNullOrWhiteSpace(deptKey)) { string[] arr = deptKey.Split('|'); pxDeptId = arr[0]; if (arr.Length > 1) { pxDeptCode = arr[1]; } } } else //部门名称不匹配 { sb.AppendFormat("用户(账号:{0},姓名:{1},部门:{2})部门与系统部门名称不匹配,无法同步!\n", account, realName, department); continue; } } } sb.AppendFormat("账号:{0},姓名:{1},手机号:{2},部门:{3}\n", account, realName, mobile, department); sb.Append("\n"); System.Data.DataTable dtUser = deptBll.GetDataTable(string.Format("select userid from base_user where account='{0}'", account)); UserEntity user = new UserEntity(); string action = "add"; string userId = Guid.NewGuid().ToString(); string password = "******"; if (dtUser.Rows.Count > 0) //修改 { action = "edit"; userId = dtUser.Rows[0][0].ToString(); user = userBll.GetEntity(userId); password = null; if (user.RoleName.Contains("部门级")) { user.DepartmentId = deptId; user.DepartmentCode = deptCode; } } else //新增 { user.UserId = userId; user.Account = account; user.Password = password; user.RoleId = roleId; user.RoleName = roleName; user.IsEpiboly = "0"; user.IsPresence = "1"; user.DeleteMark = 0; user.EnabledMark = 1; user.DepartmentId = deptId; user.DepartmentCode = deptCode; user.OrganizeCode = orgCode; user.OrganizeId = orgId; } user.OpenId = 1; //此字段标记数据来源于预控用户 user.RealName = realName; user.Mobile = mobile; userId = userBll.SaveForm(userId, user); if (!string.IsNullOrWhiteSpace(userId)) { object obj = new { action = action, time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), userId = userId, userName = realName, password = password, account = account, deptId = pxDeptId, deptCode = pxDeptCode, sex = user.Gender, idCard = user.IdentifyID, email = user.Email, mobile = user.Mobile, birth = user.Birthday, postId = user.DutyId, postName = user.DutyName, //岗位 age = user.Age.ToIntOrNull(), //年龄 native = user.Native, //籍贯 nation = user.Nation, //民族 encode = user.EnCode, //工号 jobTitle = user.JobTitle, techLevel = user.TechnicalGrade, workType = user.Craft, companyId = org.InnerPhone, trainRoles = user.TrainRoleId, role = 0//角色(0:学员,1:培训管理员) }; list.Add(obj); user.Password = password; lstUsers.Add(user); sb.AppendFormat("已同步用户信息(账号:{0},姓名:{1},部门:{2},手机号:{3})!\n", account, realName, department, mobile); } } //推送用户数据到消息队列 if (list.Count > 0) { if (list.Count > 50) { int page = 0; int total = list.Count; if (total % 50 == 0) { page = total / 50; } else { page = total / 50 + 1; } for (int j = 0; j < page; j++) { Busines.JPush.JPushApi.PushMessage(list.Skip(j * 50).Take(50), 1); } } else { Busines.JPush.JPushApi.PushMessage(list, 1); } System.IO.File.AppendAllText(string.Format(@"D:\logs\{0}.log", DateTime.Now.ToString("yyyyMMdd")), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + list.ToJson() + "\n\n"); } //同步用户信息到班组 if (lstUsers.Count > 0) { ImportUsersToBZ(lstUsers); } } return(new { code = 0, message = sb.ToString() }); } catch (Exception ex) { System.IO.File.AppendAllText(string.Format(@"D:\logs\{0}.log", DateTime.Now.ToString("yyyyMMdd")), ex.Message); return(new { code = 1, message = ex.Message }); } }