public void testCompleteInitLibrary() { LdapUser adminUser = new LdapUser(ConfigurationManager.AppSettings["LDAPAdminUserDN"], ConfigurationManager.AppSettings["LDAPAdminUserCN"], ConfigurationManager.AppSettings["LDAPAdminUserSN"], null); adminUser.CreateUserAttribute("userPassword", ConfigurationManager.AppSettings["LDAPAdminUserPassword"]); AuthType authType = (AuthType)Enum.Parse(typeof(AuthType), ConfigurationManager.AppSettings["LDAPAuthType"]); LdapManagerObj = new LdapManager(adminUser, ConfigurationManager.AppSettings["LDAPServer"], ConfigurationManager.AppSettings["LDAPSearchBaseDN"], authType, Convert.ToBoolean(ConfigurationManager.AppSettings["secureSocketLayerFlag"]), Convert.ToBoolean(ConfigurationManager.AppSettings["transportSocketLayerFlag"]), Convert.ToBoolean(ConfigurationManager.AppSettings["ClientCertificationFlag"]), ConfigurationManager.AppSettings["clientCertificatePath"], Convert.ToBoolean(ConfigurationManager.AppSettings["enableLDAPLibraryLog"]), ConfigurationManager.AppSettings["LDAPLibraryLogPath"], ConfigurationManager.AppSettings["LdapUserObjectClass"], ConfigurationManager.AppSettings["LDAPMatchFieldUsername"] ); Assert.IsFalse(LdapManagerObj.Equals(null)); }
private List <LdapUser> GetUsers() { List <LdapUser> users = new List <LdapUser>(); //Abrimos Socket contra el server LdapConnection ldapConn = new LdapConnection(); ldapConn.Connect("192.168.123.159", 389); //Definimos un filtro Ldap utilizado mas tarde, en este caso solo queremos los objetos tipo usuario string filter = "(ObjectClass=inetOrgPerson)"; //Hacemos la busqueda LdapSearchResults query = ldapConn.Search("dc=examen,dc=ies", LdapConnection.SCOPE_SUB, filter, null, false); foreach (var element in query) { LdapUser user = new LdapUser(); user.DN = element.DN; user.Name = element.getAttribute("givenName").ToString(); user.Surname = element.getAttribute("sn").ToString(); users.Add(user); } return(users); }
public void testModifyUserAttribute() { bool result; testAdminConnect(); LdapUser testLdapUser = setupTestUser(); result = LdapManagerObj.CreateUser(testLdapUser); Assert.IsTrue(result); List <LdapUser> returnUsers = new List <LdapUser>(); const string userAttributeValue = "description Modified"; result = LdapManagerObj.ModifyUserAttribute(DirectoryAttributeOperation.Replace, testLdapUser, "description", userAttributeValue); Assert.IsTrue(result); result = LdapManagerObj.SearchUsers( new List <string> { "description" }, LDAPMatchSearchField, out returnUsers); Assert.IsTrue(result); Assert.AreEqual(returnUsers[0].GetUserCn(), testLdapUser.GetUserCn()); Assert.AreEqual(returnUsers[0].GetUserAttribute("description")[0], userAttributeValue); result = LdapManagerObj.DeleteUser(testLdapUser); Assert.IsTrue(result); }
public async Task <IActionResult> Login([FromBody] LoginArgs args) { if (!ModelState.IsValid) { return(new BadRequestObjectResult(new ErrorsResponse(ModelState))); } LdapUser user = new LdapUser(); try { user = await Task.Run(() => _ldap.GetUser(args.Username, args.Password)); } catch (LdapConnectionException e) { _logger.LogError($"exception: {e}"); return(StatusCode(500, new ErrorResponse("could not connect to LDAP server"))); } catch (LdapUnauthorizedException e) { _logger.LogWarning($"exception: {e}"); return(Unauthorized()); } return(Ok(new TokenResponse(new JwtSecurityTokenHandler().WriteToken(_jwt.BuildToken(new[] { new Claim(JwtRegisteredClaimNames.Sub, user.Username), new Claim("name", user.DisplayName), new Claim("role", user.Role) }))))); }
public LdapUser GetUserByUserName(string userName) { LdapUser user = null; var filter = $"(&(objectClass=user)(name={userName}))"; using (var ldapConnection = this.GetConnection()) { var search = ldapConnection.Search( this._ldapSettings.SearchBase, LdapConnection.ScopeSub, filter, this._attributes, false, null); LdapMessage message; if (search.HasMore()) { foreach (var entry in search) { user = this.CreateUserFromAttributes(this._ldapSettings.SearchBase, entry.GetAttributeSet()); } } } return(user); }
/// <summary> /// /// </summary> /// <param name="user"></param> /// <param name="validationMessage"></param> private static bool ValidateLdapUser(LdapUser user, out string validationMessage) { validationMessage = string.Empty; if (string.IsNullOrEmpty(user.ErrorMessage)) { return(true); } else { validationMessage = user.ErrorMessage; return(false); } //// Validazione campi obbligatori //if (!ValidateRequiredProperty(user.UserID, "UserID", out validationMessage)) // return false; //if (!ValidateRequiredProperty(user.Matricola, "Matricola", out validationMessage)) // return false; //if (!ValidateRequiredProperty(user.Email, "Email", out validationMessage)) // return false; //if (!ValidateRequiredProperty(user.Nome, "Nome", out validationMessage)) // return false; //if (!ValidateRequiredProperty(user.Nome, "Cognome", out validationMessage)) // return false; //return true; }
public void testUserConnectWithoutWritePermissions() { if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["LDAPAdminUserDN"])) { testAdminConnect(); } else { //Init the DLL testStandardInitLibrary(); } LdapUser testUser = setupReadOnlyTestUser(); NetworkCredential testUserCredential = new NetworkCredential( testUser.GetUserDn(), testUser.GetUserAttribute("userPassword")[0], ""); bool result = LdapManagerObj.Connect(testUserCredential, Convert.ToBoolean(ConfigurationManager.AppSettings["secureSocketLayerFlag"]), Convert.ToBoolean(ConfigurationManager.AppSettings["transportSocketLayerFlag"]), Convert.ToBoolean(ConfigurationManager.AppSettings["ClientCertificationFlag"])); Assert.IsTrue(result); }
public static ILdapManager SetupLdapLibrary() { var authType = (AuthType)Enum.Parse(typeof(AuthType), Config.LdapLibrary["LDAPAuthType"]); if (string.IsNullOrEmpty(Config.LdapLibrary["LDAPAdminUserDN"])) { return(new LdapManager(null, (LDAPAdminMode)Enum.Parse(typeof(LDAPAdminMode), Config.LdapLibrary["LDAPAdminMode"]), Config.LdapLibrary["LDAPServer"], Config.LdapLibrary["LDAPSearchBaseDN"], authType, (LoggerType)Enum.Parse(typeof(LoggerType), Config.LdapLibrary["enableLDAPLibraryLog"]), Config.LdapLibrary["LDAPLibraryLogPath"] )); } var adminUser = new LdapUser(Config.LdapLibrary["LDAPAdminUserDN"], Config.LdapLibrary["LDAPAdminUserCN"], Config.LdapLibrary["LDAPAdminUserSN"], null); adminUser.CreateUserAttribute("userPassword", Config.LdapLibrary["LDAPAdminUserPassword"]); return(new LdapManager(adminUser, (LDAPAdminMode)Enum.Parse(typeof(LDAPAdminMode), Config.LdapLibrary["LDAPAdminMode"]), Config.LdapLibrary["LDAPServer"], Config.LdapLibrary["LDAPSearchBaseDN"], authType, (LoggerType)Enum.Parse(typeof(LoggerType), Config.LdapLibrary["enableLDAPLibraryLog"]), Config.LdapLibrary["LDAPLibraryLogPath"] )); }
async Task AddAccount() { newUserDialogIsOpen = false; var newUser = ldapUsers.FirstOrDefault(u => u.UserName == LdapUser.UserName); // Remove from dropdown list of LdapUsers collection ldapUsers.Remove(newUser); var jsonContent = JsonConvert.SerializeObject(newUser); var buffer = System.Text.Encoding.UTF8.GetBytes(jsonContent); var byteContent = new ByteArrayContent(buffer); byteContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var response = await HttpClient.PostAsync("api/account/identity/add", byteContent); var content = await response.Content.ReadAsStringAsync(); //Add to UsersIdentity collection var appUserIdentity = JsonConvert.DeserializeObject <AppUserIdentity>(content); appUsersList.Add(appUserIdentity.AssosiatedUser); appUsersList = appUsersList.OrderBy(d => d.DisplayName).ToList(); Toaster.Add($"Пользователь успешно добавлен в систему", MatToastType.Success, "Успех!"); LdapUser = new LdapUser(); }
public LdapUser GetUserByUserName(string userName) { LdapUser user = null; var filter = $"(&(objectClass=user)(name={userName}))"; using (var ldapConnection = this.GetConnection()) { var search = ldapConnection.Search( this._searchBase, LdapConnection.SCOPE_SUB, filter, this._attributes, false, null, null); LdapMessage message; while ((message = search.getResponse()) != null) { if (!(message is LdapSearchResult searchResultMessage)) { continue; } user = this.CreateUserFromAttributes(this._searchBase, searchResultMessage.Entry.getAttributeSet()); } } return(user); }
/// <summary> /// Reperimento degli utenti in LDAP appartenenti al gruppo configurato in amministrazione /// </summary> /// <param name="ldapInfo"></param> /// <returns></returns> private static Dictionary <string, LdapUser> GetLdapUsers(LdapConfig ldapInfo) { Dictionary <string, LdapUser> result = new Dictionary <string, LdapUser>(); LdapUser userError = null; try { // Creazione dei servizi per la gestione LDAP BaseLdapUserServices ldapUserServices = LdapUserServicesFactory.CreateInstance(ldapInfo); // Reperimento da LDAP di tutti gli utenti appartenti al gruppo configurato foreach (LdapUser user in ldapUserServices.GetUsers()) { userError = user; logger.Debug("GET UTENTE LDAP utente userid " + user.UserID + " matricola " + user.Matricola + " DN " + user.DN + " email " + user.Email); try { result.Add(user.Key.ToUpper(), user); } catch (Exception ex) { } } } catch (Exception ex) { logger.Debug("errore per utente userid " + userError.UserID + " matricola " + userError.Matricola + " " + ex.StackTrace + " " + ex.Message); } return(result); }
public async Task <IActionResult> SignIn([FromBody] LdapUser model) { // validate username/password against Ldap var user = this.userStore.ValidateCredentials(model.Username, model.Password); if (user != default(IAppUser)) { // Response with authentication cookie await this.HttpContext.SignInAsync(user.SubjectId, user.Username); // Get the Access token var accessToken = await this.tools.IssueJwtAsync(lifetime : 3600, claims : new Claim[] { new Claim(JwtClaimTypes.Audience, model.ApiResource) }); // Save Access token to current session this.HttpContext.Session.SetString("AccessToken", accessToken); // Write the Access token to response await this.HttpContext.Response.WriteAsync(accessToken); // Raise UserLoginSuccessEvent await this.events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username)); return(this.Ok()); } else { return(this.Unauthorized()); } }
private void ResetTestUser() { _testUser = new LdapUser(LdapUserDn, LdapUserCn, LdapUserSn, LdapUserAttributes); }
public LdapUser GetUserByUserName(string userName) { LdapUser user = null; var filter = $"(&(objectClass=user)(objectClass=person)(sAMAccountName={userName}))"; using (var ldapConnection = GetConnection()) { var search = ldapConnection.Search( _ldapSettings.SearchBase, LdapConnection.ScopeSub, filter, _attributes, false, new LdapSearchConstraints { ReferralFollowing = false }); if (search.HasMore()) { foreach (var entry in search) { user = CreateUserFromAttributes(_ldapSettings.SearchBase, entry.GetAttributeSet()); } } } return(user); }
public async Task <IActionResult> CreateUser([FromForm] LdapUser newUser) { if (this.ModelState.IsValid) { try { var result = await this._userManager.CreateAsync(newUser, newUser.Password); if (!result.Succeeded) { this.TempData["CreateErrorMessage"] = result.Errors.Any() ? result.Errors.First().Description : "There was a problem creating the user."; } else { this.TempData["CreateSucceededMessage"] = "The user was sucessfully created."; } } catch (Exception e) { Console.WriteLine(e); throw; } } var vm = new ManageViewModel { Users = this._userManager.Users.ToCollection(), NewUser = newUser }; return(this.View("Index", vm));; }
public void TestDeleteUser() { //Set the test user var testLdapUser = new LdapUser(WriteUserDn, WriteUserCn, "test", null); //Init the DLL and connect the admin TestAdminConnect(); //Create LDAPUser to delete. var result = _ldapManagerObj.CreateUser(testLdapUser); Assert.IsTrue(result); //Delete user result = _ldapManagerObj.DeleteUser(testLdapUser); //Assert the correct operations Assert.IsTrue(result); Assert.AreEqual(_ldapManagerObj.GetLdapMessage().Split('-')[1].Substring(1), "LDAP USER MANIPULATION SUCCESS: "); //Delete user again with error result = _ldapManagerObj.DeleteUser(testLdapUser); //Assert the correct operations Assert.IsFalse(result); Assert.AreEqual(_ldapManagerObj.GetLdapMessage().Split('-')[1].Substring(1), "LDAP DELETE USER ERROR: "); }
/// <summary> /// Creazione nuovo oggetto utente in amministrazione /// </summary> /// <param name="ldapUser"></param> /// <param name="idAmministrazione"></param> /// <param name="dominio"></param> /// <returns></returns> private static OrgUtente CreateUser(LdapUser ldapUser, string idAmministrazione, string dominio) { OrgUtente user = new OrgUtente(); user.UserId = ldapUser.UserID; user.IDAmministrazione = idAmministrazione; user.Dominio = dominio; if (string.IsNullOrEmpty(user.Dominio)) { user.Password = "******"; } user.Email = ldapUser.Email; user.Codice = user.UserId; user.CodiceRubrica = user.Codice; user.Nome = ldapUser.Nome; user.Cognome = ldapUser.Cognome; user.Sede = ldapUser.Sede; user.Abilitato = "1"; user.Amministratore = "0"; // Impostazione dell'id sincronizzazione in ldap user.IdSincronizzazioneLdap = ldapUser.Matricola; // Per default, tutti i nuovi utenti importati da un archivio LDAP // potranno utilizzare le credenziali di dominio per connettersi al sitema user.AutenticatoInLdap = true; return(user); }
public LdapUser GetUser(string userName) { var result = new LdapUser(); var domain = "WEBMEDIA"; var entry = new DirectoryEntry("LDAP://" + domain); var adSearcher = new DirectorySearcher(entry) { SearchScope = SearchScope.Subtree, Filter = "(&(objectClass=user)(samaccountname=" + userName + "))" }; var userObject = adSearcher.FindOne(); if (userObject == null) { return(result); } result.Name = userObject.GetString("displayname"); result.ShortName = userObject.GetString("givenname"); result.Thumbnail = userObject.GetByteArray("thumbnailphoto"); result.BirthDay = userObject.GetDateTime("extensionattribute1"); result.Email = userObject.GetString("mail"); result.DomainName = userObject.GetString("samaccountname"); return(result); }
public async Task Login() { var ldapuser = new LdapUser() { EmailAddress = "*****@*****.**", Name = "*****@*****.**" }; ldapuser.EmailAddress = "*****@*****.**"; this._mockUserManager.Setup(x => x.FindByEmailAddress("*****@*****.**")).ReturnsAsync(() => { return(ldapuser); }); this._mockUserManager.Setup(x => x.CheckPasswordAsync(ldapuser, "*****")).Returns(true); var controller = new AccountController(this._mockUserManager.Object, this._mockLogger.Object, this._mockTokenSettings.Object); var model = new LoginModel(); model.UserName = "******"; model.UserPassword = "******"; var result = await controller.Login(model); Assert.NotNull(result); Assert.NotNull(result.UserAccessToken); }
/// <summary> /// Gets LDAP user data. /// </summary> /// <param name="username">LDAP username without domain prefix.</param> /// <param name="password">The password corresponding to the LDAP username.</param> /// <param name="ldapConnection">The active LDAP connection used for checking credential validity.</param> /// <returns>An object containing LDAP user's data including its username, display name and a boolean indicating membership to a specified group. </returns> private LdapUser GetUserData(string username, string password, LdapConnection ldapConnection) { var searchFilter = string.Format(ldapSettings.Value.SearchFilter, username); var result = ldapConnection.Search( ldapSettings.Value.SearchBase, LdapConnection.SCOPE_SUB, searchFilter, new[] { MemberOfAttribute, DisplayNameAttribute, SAMAccountNameAttribute }, false ); // Needed because of LDAP library imperfections (result.count sometimes won't register properly) var hasMore = result.hasMore(); var count = result.Count; if (count != 1) { logger.LogWarning($"Unexpected response from LDAP server, found {count} users."); throw new ApplicationException($"Unexpected response from LDAP server, found {count} users."); } var entry = result.next(); var user = new LdapUser { DisplayName = entry.getAttribute(DisplayNameAttribute).StringValue, Username = entry.getAttribute(SAMAccountNameAttribute).StringValue, IsAdmin = entry.getAttribute(MemberOfAttribute).StringValueArray.Contains(ldapSettings.Value.AdminCn) }; return(user); }
public void TestCreateUser() { var tempUser = new LdapUser(WriteUserDn, WriteUserCn, "test", null); var existingUser = new LdapUser(ReadOnlyUserDn, ReadOnlyUserCn, "test", new Dictionary <string, List <string> > { { "userPassword", new List <string> { ReadOnlyUserPwd } } }); //Init the DLL and connect the admin TestAdminConnect(); //Create existing user var result = _ldapManagerObj.CreateUser(existingUser); //Assert the correct operations Assert.IsFalse(result); Assert.AreEqual(_ldapManagerObj.GetLdapMessage().Split('-')[1].Substring(1), "LDAP CREATE USER ERROR: "); //Create user result = _ldapManagerObj.CreateUser(tempUser); //Assert the correct operations Assert.IsTrue(result); Assert.AreEqual(_ldapManagerObj.GetLdapMessage().Split('-')[1].Substring(1), "LDAP USER MANIPULATION SUCCESS: "); result = _ldapManagerObj.DeleteUser(tempUser); Assert.IsTrue(result); }
public async Task <JObject> SignIn(LdapUser user) { var tokenResponse = await this.idsrvClient.SignInAsync(user.Username, user.Password); this.HttpContext.Response.StatusCode = tokenResponse.IsError? (int)HttpStatusCode.BadRequest : (int)HttpStatusCode.OK; return(tokenResponse.Json); }
public void testSearchUserAndConnectWithoutWritePermissions() { testAdminConnect(); LdapUser testLdapUser = setupReadOnlyTestUser(); bool result = LdapManagerObj.SearchUserAndConnect(LDAPMatchSearchField[0], testLdapUser.GetUserAttribute("userPassword")[0]); Assert.IsTrue(result); }
public void LdapUserInstance() { var user = new LdapUser(LdapUserDn, LdapUserCn, LdapUserSn, LdapUserAttributes); Assert.IsNotNull(user); }
//private bool useRootDn = false; public Task <LdapUser> TryLdapLogin(ILdapSettings ldapSettings, string userName, string password) { bool success = false; LdapUser user = null; DirectoryEntry directoryEntry = null; try { //if (useRootDn) //{ // directoryEntry = new DirectoryEntry("LDAP://" + ldapSettings.LdapServer + "/" + ldapSettings.LdapRootDN, ldapSettings.LdapDomain + "\\" + userName, password); //} //else //{ //directoryEntry = new DirectoryEntry("LDAP://" + ldapSettings.LdapServer, ldapSettings.LdapDomain + "\\" + userName, password); //} if (ldapSettings.LdapUseSsl) { directoryEntry = new DirectoryEntry("LDAP://" + ldapSettings.LdapServer, ldapSettings.LdapDomain + "\\" + userName, password, AuthenticationTypes.SecureSocketsLayer); } else { directoryEntry = new DirectoryEntry("LDAP://" + ldapSettings.LdapServer, ldapSettings.LdapDomain + "\\" + userName, password); } } catch (Exception ex) { string msg = $"Login failure for user: {userName} Exception: {ex.Message}:{ex.StackTrace}"; _log.LogError(msg); } if (directoryEntry != null) { //Bind to the native AdsObject to force authentication. try { object testobj = directoryEntry.NativeObject; success = true; } catch (Exception ex) { string msg = $"Login failure for user: {userName} Exception: {ex.Message}:{ex.StackTrace}"; _log.LogError(msg); success = false; } if (success && directoryEntry != null) { user = GetLdapUser(directoryEntry, ldapSettings, userName); } } return(Task.FromResult(user)); }
private void FillLdapUserPropertiesFromSearchResult(LdapUser ldapUser, SearchResult result, List <string> requiredProperties, bool isDepartmentNumberRequired) { if (ldapUser != null && result != null && requiredProperties.Count > 0) { ldapUser.FullName = result.Properties[requiredProperties[0]][0].ToString(); ldapUser.DepartmentName = result.Properties[requiredProperties[1]][0].ToString(); if (isDepartmentNumberRequired) { ldapUser.DepartmentNumber = result.Properties[requiredProperties[2]][0].ToString(); } } }
public async Task <IActionResult> Validate([FromBody] LdapUser user) { var isAuthorized = await this.ExecLdapAuthAsync(user.Username, user.Password); if (isAuthorized) { return(this.Ok()); } else { return(this.Unauthorized()); } }
public void TestChangeUserPassword() { TestAdminConnect(); const string newPassword = "******"; var testUser = new LdapUser(WriteUserDn, WriteUserCn, "test", new Dictionary <string, List <string> > { { "userPassword", new List <string> { WriteUserPwd } } }); //Create the user var result = _ldapManagerObj.CreateUser(testUser); Assert.IsTrue(result); //Perform change of password result = _ldapManagerObj.ChangeUserPassword(testUser, newPassword); Assert.IsTrue(result); Assert.AreEqual(_ldapManagerObj.GetLdapMessage().Split('-')[1].Substring(1), "LDAP USER MANIPULATION SUCCESS: "); //Try to connect with the old password var testUserCredential = new NetworkCredential( testUser.GetUserDn(), WriteUserPwd, ""); result = _ldapManagerObj.Connect(testUserCredential); Assert.IsFalse(result); Assert.AreEqual(_ldapManagerObj.GetLdapMessage().Split('-')[1].Substring(1), "LDAP CONNECTION ERROR: "); //Try to connect with the new password testUserCredential = new NetworkCredential( testUser.GetUserDn(), newPassword, ""); result = _ldapManagerObj.Connect(testUserCredential); Assert.IsTrue(result); Assert.AreEqual(_ldapManagerObj.GetLdapMessage().Split('-')[1].Substring(1), "LDAP CONNECTION SUCCESS"); TestAdminConnect(); result = _ldapManagerObj.DeleteUser(testUser); Assert.IsTrue(result); Assert.AreEqual(_ldapManagerObj.GetLdapMessage().Split('-')[1].Substring(1), "LDAP USER MANIPULATION SUCCESS: "); }
public async Task <HttpResponseMessage> CreateUser([FromBody] LdapUser ldapUser) { try { //ユーザーを追加 await new LdapUserStore().CreateAsync(ldapUser); //登録した結果を返す return(Request.CreateResponse(HttpStatusCode.OK)); } catch (Exception e) { return(Request.CreateResponse(HttpStatusCode.InternalServerError, e)); } }
public async Task <JObject> GetToken(LdapUser user) { var response = await this.idsrvClient.GetTokenByFormDataAsync(user.Username, user.Password); if (response.IsSuccessStatusCode == true) { var strResult = await response.Content.ReadAsStringAsync(); return(JObject.Parse(strResult)); } this.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return(null); }
public static LdapUser GetLdapUser(string windowUserLogin) { LdapUser user = null; DirectoryEntry entry = new DirectoryEntry(LdapPath); DirectorySearcher searcher = new DirectorySearcher(entry); //searcher.PropertiesToLoad.Add("givenName"); //searcher.PropertiesToLoad.Add("sn"); searcher.Filter = "(&(objectCategory=person)(samAccountName=" + windowUserLogin + "))"; SearchResult result = searcher.FindOne(); if (result != null) { user = new LdapUser(); user.FirstName = result.Properties["givenName"][0].ToString(); user.LastName = result.Properties["sn"][0].ToString(); user.WindowsLogin = windowUserLogin; } return user; }
// GET: LDAP/Sync public ActionResult Index(int? page, long? filter) { List<DirectoryMemberInfo> mm = null; page = (page == null) ? 1 : page; if (filter == null) mm = AllMembers; else mm = AllMembers.Where(x => MembershipScopeRepository.HasFlag(x.MembershipScope, filter.Value, MembershipScopeEnum)).ToList(); DirectoryEntry domain = new DirectoryEntry("LDAP://lcps.local", "earlyms", "Lcp$-pw1"); DirectoryEntry parentou = null; string adminUserName = "******"; string adminPw = "Lcp$-pw1"; string principalDomain = "lcps.local"; string studentOu = "LDAP://OU=LCPS-Students,OU=LCPS-Accounts,DC=lcps,DC=local"; string staffOu = "OU=LCPS-Staff,OU=LCPS-Accounts,DC=lcps,DC=local"; List<string> groups = new List<string>(); List<LdapUser> ll = new List<LdapUser>(); foreach (DirectoryMemberInfo m in mm) { List<MembershipScope> scopes = MembershipScopeRepository.GetApplicableScopes(m.MembershipScope); bool IsStudent = (scopes.Where(x => x.ScopeQualifier == MembershipScopeQualifier.Grade).Count() > 0); bool IsStaff = (scopes.Where(x => x.ScopeQualifier == MembershipScopeQualifier.Position).Count() > 0); if (IsStudent) { parentou = new DirectoryEntry(studentOu, adminUserName, adminPw); groups.Add("LDAP://CN=Palo Alto Secondary Student Group,OU=LCPS-PaloAlto,DC=lcps,DC=local"); if (MembershipScopeRepository.HasFlag(m.MembershipScope, "Lunenburg Middle", MembershipScopeEnum)) groups.Add("CN=LCPS-LMS-Student Group,OU=LCPS-Students,OU=LCPS-Accounts,DC=lcps,DC=local"); if (MembershipScopeRepository.HasFlag(m.MembershipScope, "Central High", MembershipScopeEnum)) groups.Add("CN=CHS-Students,OU=LCPS-Students,OU=LCPS-Accounts,DC=lcps,DC=local"); } if(IsStudent) parentou = new DirectoryEntry(staffOu, adminUserName, adminPw); LdapUser u = new LdapUser(parentou, domain, m) { AllowPasswordChange = false, PrincipalDomain = principalDomain, AdminPassword = adminPw, AdminUserName = adminUserName, IntendedGroups = groups.ToArray() }; u.GetSyncStatus(); ll.Add(u); } ViewBag.Total = ll.Count(); ViewBag.Page = page.Value; ViewBag.Insert = ll.Where(x => x.SyncStatus == ImportSyncStatus.Insert).Count(); ViewBag.Current = ll.Where(x => x.SyncStatus == ImportSyncStatus.Current).Count(); ViewBag.Update = ll.Where(x => x.SyncStatus == ImportSyncStatus.Update).Count(); ViewBag.Error = ll.Where(x => x.SyncStatus == ImportSyncStatus.Error).Count(); PagedList<LdapUser> pg = new PagedList<LdapUser>(ll, page.Value, 12); return View(pg); }