async public Task <IEnumerable <ActiveDirectoryUser> > ActiveDirectoryUsersAsync()
        {
            List <ActiveDirectoryUser> activeDirectoryUsers = new List <ActiveDirectoryUser>();
            ActiveDirectoryClient      client          = Helpers.AuthenticationHelper.GetActiveDirectoryClient();
            IPagedCollection <IUser>   pagedCollection = await client.Users.ExecuteAsync();

            if (pagedCollection != null)
            {
                do
                {
                    List <IUser> usersList = pagedCollection.CurrentPage.ToList();
                    foreach (var user in usersList)
                    {
                        ActiveDirectoryUser adUser = new ActiveDirectoryUser();
                        adUser.ActiveDirectoryId = user.ObjectId;
                        adUser.FullName          = user.DisplayName;
                        adUser.Position          = user.JobTitle;
                        adUser.Location          = user.City + ", " + user.State;
                        adUser.ImageUrl          = "/Users/ShowThumbnail/" + user.ObjectId;
                        adUser.ObjectId          = user.ObjectId;

                        activeDirectoryUsers.Add(adUser);
                    }

                    pagedCollection = await pagedCollection.GetNextPageAsync();
                }while (pagedCollection != null);
            }

            return(activeDirectoryUsers);
        }
Example #2
0
    //Database Functions
    //Write an ActiveDirectoryUser to MongoDB
    public static void UpdateDatabaseUser(ActiveDirectoryUser User)
    {
        //Collection hook
        var collection = new MongoClient(config.MongoDbConnectionString)
                         .GetDatabase(config.MongoDbDatabase)
                         .GetCollection <ActiveDirectoryUser>(config.MongoDbCollection);

        //Try to find an existing user to replace/update
        var existingUser = collection.AsQueryable()
                           .FirstOrDefault(u => u.username == User.username);

        if (existingUser == null)
        {
            //Create a fresh user object
            collection.InsertOne(User);
        }
        else
        {
            //Replace an existing user object
            var filter = Builders <ActiveDirectoryUser> .Filter.Eq(s => s.Id, existingUser.Id);

            User.Id = existingUser.Id;

            collection.ReplaceOne(filter, User);
        }
    }
Example #3
0
        public ActiveDirectoryUser GetByLogonUser(string logonUser)
        {
            string domain   = logonUser.Split('\\')[0];
            string username = logonUser.Split('\\')[1];

            ActiveDirectoryUser activeDirectoryUser = new ActiveDirectoryUser
            {
                DomainName = domain,
            };

            // Enter AD settings, search in the domain the user is logged in from. Domain does not always equal the LDAP name so these are mapped in web.config
            PrincipalContext AD = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings[domain].Split(',')[0]);

            // Create search user and add criteria
            UserPrincipal u = new UserPrincipal(AD)
            {
                SamAccountName = username
            };

            // Search for user
            using (PrincipalSearcher search = new PrincipalSearcher(u))
            {
                using (DirectorySearcher Searcher = search.GetUnderlyingSearcher() as DirectorySearcher)
                {
                    Searcher.PageSize = 1;
                    Searcher.PropertiesToLoad.Clear();
                    Searcher.PropertiesToLoad.Add("samaccountname");
                    Searcher.PropertiesToLoad.Add("displayname");
                    activeDirectoryUser.UserPrincipal = (UserPrincipal)search.FindOne();
                    return(activeDirectoryUser);
                }
            }
        }
Example #4
0
        /// <summary>
        ///     Checks to see if the user is in the cache. If so then
        ///     validates the date. User will be filtered out if the changed
        ///     by
        /// </summary>
        /// <param name="userToFilter">Reference to the user to check.</param>
        /// <param name="jobConfig">The current job configuration.</param>
        /// <returns></returns>
        public ActiveDirectoryUser Execute(ActiveDirectoryUser userToFilter, JobElement jobConfig)
        {
            if (_cacheService == null)
            {
                _cacheService = CacheServiceFactory.CreateCacheService(Logger, jobConfig.Name);
            }

            var cacheKey = userToFilter.Attributes["distinguishedName"].ToString();

            var currentUserHash = BuildUserCacheHashValue(userToFilter);

            if (!_cacheService.ContainsKey(cacheKey))
            {
                // add the value to the cache
                _cacheService.Add(cacheKey, currentUserHash);

                // user is not in the cache...allow through
                return(userToFilter);
            }

            // create a json version of the user and compare to the cached value
            // if they are not the same then the user has been updated
            var cachedUserHash = _cacheService.GetValue(cacheKey);

            if (!currentUserHash.Equals(cachedUserHash, StringComparison.InvariantCulture))
            {
                // update the cache entry
                _cacheService.Add(cacheKey, currentUserHash);
                return(userToFilter);
            }

            return(null);
        }
Example #5
0
        /// <summary>
        /// Builds the cache hash value for the specified user
        /// </summary>
        /// <param name="user">The user to process</param>
        /// <returns>The hash string</returns>
        private string BuildUserCacheHashValue(ActiveDirectoryUser user)
        {
            var sb = new StringBuilder();

            foreach (var key in user.Attributes.Keys)
            {
                var val = user.Attributes[key];
                if (val is string)
                {
                    sb.Append(val);
                }
                else if (val is SortedList <string, string> )
                {
                    var list = (SortedList <string, string>)val;
                    foreach (var item in list)
                    {
                        sb.Append(item.Value);
                    }
                }
            }

            var hash = GetMd5Hash(sb.ToString());

            return(hash);
        }
        /// <summary>
        /// Gets Active Directory user by username
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public ActiveDirectoryUser GetUser(string userName)
        {
            ActiveDirectoryUser user = null;

            try
            {
                using (var ctx = new PrincipalContext(ContextType.Domain, ADDomain, ADUserName, ADPassword))
                {
                    UserPrincipal qbeUser = new UserPrincipal(ctx);
                    qbeUser.SamAccountName = userName;

                    PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
                    UserPrincipal     upr  = srch.FindOne() as UserPrincipal;

                    if (upr != null)
                    {
                        DirectoryEntry de = upr.GetUnderlyingObject() as DirectoryEntry;

                        if (de != null)
                        {
                            user = CreateUserFromDirectoryEntry(de);
                        }
                    }
                }
            }
            catch
            {
                throw;
            }

            return(user);
        }
Example #7
0
        public bool Authorize(Permission permission, IContent content, LocalizedString message)
        {
            // gets the current active directory user.
            var user = new ActiveDirectoryUser();

            // attempts to authorize the active directory user based on their roles
            // and the permissions that their associated roles have.
            if (_authorizationService.TryCheckAccess(permission, user, content))
            {
                // if the user is attempting to access the admin area then they must have
                // a UserPartRecord associated to their username.
                if (permission.Name == AdminPanelAccess)
                {
                    CreateUserForActiveDirectoryUserIfNotExists(user);
                }

                return(true);
            }

            if (message != null)
            {
                _notifier.Error(T("{0}. Current user, {2}, does not have {1} permission.",
                                  message, permission.Name, user.UserName));
            }

            return(false);
        }
 /// <summary>
 /// Gets users using domain name
 /// </summary>
 /// <param name="domainName"></param>
 /// <param name="samAccountName"></param>
 /// <param name="userPrincipals"></param>
 public static void GetUserWhereDomain(string domainName, string samAccountName, XElement userPrincipals)
 {
     foreach (UserPrincipal userPrincipal in (IEnumerable <UserPrincipal>)DomainsManager.GetWhereDomain(domainName, samAccountName))
     {
         userPrincipals.Add((object)ActiveDirectoryUser.ToXElement(userPrincipal));
     }
 }
        public void TestUserCacheFilter()
        {
            var logger          = LogManager.CreateNullLogger();
            var cacheSvcFactory = new CacheServiceFactory();
            var cacheFilter     = new UserCacheFilter(logger, cacheSvcFactory);

            // create the test user
            var testUser = new ActiveDirectoryUser();

            testUser.Attributes[ActiveDirectoryService.AttributeWhenChanged]       = DateTime.Now;
            testUser.Attributes[ActiveDirectoryService.AttributeDistinguishedName] = "cn=Thomas";

            var job = new JobElement
            {
                Name = "TestJob"
            };

            var cachedCheckedUser = cacheFilter.Execute(testUser, job);

            Assert.IsNotNull(cachedCheckedUser);

            // clean up the cache filter...this will cause the cache
            // entries to be persisted to disk
            ((IDisposable)cacheFilter).Dispose();

            // validate that the cache entry is present
            // by trying to filter the user again
            cacheFilter = new UserCacheFilter(logger, cacheSvcFactory);

            cachedCheckedUser = cacheFilter.Execute(testUser, job);
            Assert.IsNull(cachedCheckedUser);
        }
Example #10
0
 private static void MapUser(ActiveDirectoryUser adUser, ref User qpUser)
 {
     qpUser.FirstName = adUser.FirstName ?? DefaultValue;
     qpUser.LastName  = adUser.LastName ?? DefaultValue;
     qpUser.Email     = adUser.Mail ?? DefaultMail;
     qpUser.Disabled  = adUser.IsDisabled;
 }
 /// <summary>
 /// Gets users
 /// </summary>
 /// <param name="samAccountName"></param>
 /// <param name="displayName"></param>
 /// <param name="userPrincipals"></param>
 public static void GetUser(string samAccountName, string displayName, XElement userPrincipals)
 {
     foreach (UserPrincipal userPrincipal in (IEnumerable <UserPrincipal>)ActiveDirectoryUser.Get(samAccountName, displayName))
     {
         userPrincipals.Add((object)ActiveDirectoryUser.ToXElement(userPrincipal));
     }
 }
Example #12
0
        /// <summary>
        /// Gets a JobTitle value
        /// </summary>
        /// <param name="from">The from value to parse.</param>
        /// <param name="division">The id of the division.</param>
        /// <param name="user">The user object that contains the data.</param>
        /// <returns></returns>
        public EntityId GetJobTitleValue(string from, EntityId division, ActiveDirectoryUser user)
        {
            // get the field value for the job title name
            var jobTitleValue = GetFieldValue(from, user);

            if (string.IsNullOrEmpty(jobTitleValue))
            {
                return(null);
            }

            // check the cache
            if (JobTitleCache.ContainsKey(jobTitleValue))
            {
                return(new EntityId(JobTitleCache.GetValue(jobTitleValue)));
            }

            // job title does not exist in the cache...get it from the service
            var jobTitleId = ApiService.GetJobTitleAsync(jobTitleValue, division, AuthToken).GetAwaiter().GetResult();

            if (jobTitleId != null)
            {
                JobTitleCache.Add(jobTitleValue, jobTitleId);
                return(new EntityId(jobTitleId));
            }

            // did not find the job title in the system so add it.
            jobTitleId = ApiService.CreateJobTitleAsync(jobTitleValue, division, AuthToken).GetAwaiter().GetResult();
            if (jobTitleId != null)
            {
                JobTitleCache.Add(jobTitleValue, jobTitleId);
                return(new EntityId(jobTitleId));
            }

            return(null);
        }
Example #13
0
        /// <summary>
        /// Gets the value from the user object
        /// </summary>
        /// <param name="from">The from value to parse</param>
        /// <param name="user">The user object that contains the data.</param>
        /// <returns></returns>
        public string GetFieldValue(string from, ActiveDirectoryUser user)
        {
            var fieldValue = from;
            var regex      = new Regex("{[^}]*}");
            var matches    = regex.Matches(from);

            foreach (Match match in matches)
            {
                try
                {
                    var key = match.Value.Substring(1, match.Value.Length - 2);
                    if (user.Attributes.ContainsKey(key) && !string.IsNullOrEmpty(match.Value))
                    {
                        var val = user.Attributes[key] ?? string.Empty;
                        fieldValue = fieldValue.Replace(match.Value, val.ToString());
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }

            return(fieldValue);
        }
Example #14
0
        public ActiveDirectoryUser Update(ActiveDirectoryUser entity)
        {
            string serverName = _config.ServerName;
            string baseDN     = _config.BaseDN;
            string userName   = _config.Username;
            string password   = _config.Password;

            ActiveDirectoryUserPrincipal user;
            ActiveDirectoryUser          newEntity = null;

            using (var pc = new PrincipalContext(ContextType.Domain, serverName, baseDN, userName, password))
            {
                user = ActiveDirectoryUserPrincipal.FindByIdentity(pc, IdentityType.Guid, entity.ActiveDirectoryKey.ToString());
                if (user != null)
                {
                    //if the user email has changed, we want to drop the old AD and create a new one
                    if (user.Name != entity.Username)
                    {
                        Delete(entity.ActiveDirectoryKey);
                        newEntity = Add(entity);
                    }
                    else
                    {
                        user.SetPassword(entity.Password);
                        user.passwordQuestion = entity.PasswordReminderQuestion;
                        user.passwordAnswer   = entity.PasswordReminderQuestionAnswer;
                        user.Save();
                    }
                }
            }

            return(newEntity);
        }
        public async Task ThenUserShouldBeAddedToTheGroup()
        {
            var userIsInTheGroup = await ActiveDirectoryUser.IsUserInAGroupAsync(_testContext.Config.TestSettings.ExistingUserId,
                                                                                 _testContext.Config.TestSettings.NewGroups.First().DisplayName, _testContext.Tokens.GraphApiBearerToken);

            userIsInTheGroup.Should().BeTrue();
            _testContext.Test.NewGroupId = _testContext.Config.TestSettings.NewGroups.First().GroupId;
        }
Example #16
0
        public ActiveDirectoryUser SearchUsersByUsername(string username)
        {
            DirectorySearcher.Filter = $"(&(objectClass=user)(sAMAccountname={username}))";
            var searchResult = DirectorySearcher.FindOne();
            var user         = new ActiveDirectoryUser(searchResult);

            return(user);
        }
Example #17
0
        public HttpResponseMessage auth(LoginRequestAuth login)
        {
            ActiveDirectoryUser user = null;

            if (login == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            try
            {
                var domName = ActiveDirectoryService.Get_correct_DomainName(login.domain);

                var res = ActiveDirectoryService.User_Logon(login.username, login.password, domName);

                if (res.Autenticated)
                {
                    if (login.includeDomainUserData)
                    {
                        try
                        {
                            user = ActiveDirectoryService.User_Info(login.username, domName);
                        }
                        catch (Exception ex)
                        {
                            res.ErrorMessage = "No fué posible obtener datos del usuario en el dominio. Razon =  " + ex.Message;
                        }
                    }


                    List <ActiveDirectoryGroup> userGroups = null;
                    if (login.includeGroups)
                    {
                        try
                        {
                            userGroups = ActiveDirectoryService.GetGroupsFromUser(login.username, domName);
                        }
                        catch (Exception ex)
                        {
                            res.ErrorMessage = "No fué posible obtener los grupos usuario en el dominio. Razon =  " + ex.Message;
                        }
                    }


                    var jwt = TokenGenerator.GenerateTokenJwt_LDAP(login.username, user, userGroups);

                    res.Token = jwt;
                }

                var resp = apiHelper.fromObject <LoogonUserResult>(res);


                return(resp);
            }
            catch (Exception ex)
            {
                return(apiHelper.fromEx(ex));
            }
        }
Example #18
0
        public ActionResult CreateWizard([Bind(Include = "Id,Title,Step1,Step2,Step3")] WizardViewModel wizardViewModel, HttpPostedFileBase File1, HttpPostedFileBase File2, HttpPostedFileBase File3)
        {
            if (ModelState.IsValid)
            {
                Wizard wizard = new Wizard(wizardViewModel.Title);
                if ((File1 != null && File1.ContentLength > 0) &&
                    (File2 != null && File2.ContentLength > 0) &&
                    (File3 != null && File3.ContentLength > 0))
                {
                    var f1 = new StepViewModel
                    {
                        ImageType = File1.ContentType
                    };
                    var f2 = new StepViewModel
                    {
                        ImageType = File2.ContentType
                    };
                    var f3 = new StepViewModel
                    {
                        ImageType = File3.ContentType
                    };
                    using (var reader1 = new BinaryReader(File1.InputStream))
                    {
                        f1.ImageContent = reader1.ReadBytes(File1.ContentLength);
                    }
                    using (var reader2 = new BinaryReader(File2.InputStream))
                    {
                        f2.ImageContent = reader2.ReadBytes(File2.ContentLength);
                    }
                    using (var reader3 = new BinaryReader(File3.InputStream))
                    {
                        f3.ImageContent = reader3.ReadBytes(File3.ContentLength);
                    }
                    Step s1 = new Step(null, wizardViewModel.Step1, f1.ImageContent, f1.ImageType);
                    Step s2 = new Step(s1, wizardViewModel.Step2, f2.ImageContent, f2.ImageType);
                    Step s3 = new Step(s2, wizardViewModel.Step3, f3.ImageContent, f3.ImageType);

                    ActiveDirectoryReadOnlyRepository ad = new ActiveDirectoryReadOnlyRepository();
                    ActiveDirectoryUser adu = ad.GetUser(HttpContext.User.Identity.Name);

                    User user;
                    user = unitOfWork.UserRepository.GetUserBySamAccountName(HttpContext.User.Identity.Name);
                    if (user == null)
                    {
                        UserName un = new UserName(adu.Name, adu.Surname);
                        user = new User(un, adu.SamAccountName, adu.EmailAddress, "");
                    }

                    wizard.Step     = s1;
                    wizard.CreateBy = user;
                }
                unitOfWork.WizardRepository.Insert(wizard);
                unitOfWork.SaveChanges();
                return(RedirectToAction("Index", "Home"));
            }
            return(View(wizardViewModel));
        }
 public async Task TearDown()
 {
     if (_createdAccount != null)
     {
         TestContext.WriteLine($"Attempting to delete account {_createdAccount.UserId}");
         await ActiveDirectoryUser.DeleteTheUserFromAdAsync(_createdAccount.UserId,
                                                            _graphApiSettings.AccessToken);
     }
 }
Example #20
0
 private User CreateUser(ActiveDirectoryUser user) => new User
 {
     LogOn      = user.AccountName,
     NtLogOn    = user.AccountName,
     Password   = UserRepository.GeneratePassword(),
     LanguageId = _languageId,
     AutoLogOn  = true,
     Groups     = new UserGroup[0]
 };
        public static async Task NewUserClearUp(TestContext context)
        {
            if (string.IsNullOrWhiteSpace(context.Test.NewUserId))
            {
                return;
            }
            await ActiveDirectoryUser.DeleteTheUserFromAdAsync(context.Test.NewUserId, context.Tokens.GraphApiBearerToken);

            context.Test.NewUserId = null;
        }
Example #22
0
        public IActionResult auth(LoginRequestAuth login)
        {
            ActiveDirectoryUser user = null;

            if (login == null)
            {
                return(BadRequest(new ApiErrorResponse(HttpStatusCode.BadRequest, "Los parámetros del loging no son opcionales")));
            }
            try
            {
                var res = ActiveDirectoryService.User_Logon(login.username, login.password, login.domain);

                if (res.Autenticated)
                {
                    if (login.includeDomainUserData)
                    {
                        try
                        {
                            user = ActiveDirectoryService.User_Info(login.username, login.domain);
                        }
                        catch (Exception ex)
                        {
                            res.ErrorMessage = "No fué posible obtener datos del usuario en el dominio. Razon =  " + ex.Message;
                        }
                    }


                    List <ActiveDirectoryGroup> userGroups = null;
                    if (login.includeGroups)
                    {
                        try
                        {
                            userGroups = ActiveDirectoryService.GetGroupsFromUser(login.username, login.domain);
                        }
                        catch (Exception ex)
                        {
                            res.ErrorMessage = "No fué posible obtener los grupos usuario en el dominio. Razon =  " + ex.Message;
                        }
                    }


                    var jwt = TokenGenerator.GenerateTokenJwt_LDAP(login.username, user, userGroups);

                    res.Token = jwt;
                }

                return(Ok(res));
            }
            catch (Exception ex)
            {
                var msg = apiHelper.getMessageException(ex);
                return(BadRequest(new ApiErrorResponse(HttpStatusCode.InternalServerError, msg)));
            }
        }
 public static ActiveDirectoryUser[] GetTestUsers()
 {
     List<ActiveDirectoryUser> testUsers = new List<ActiveDirectoryUser>();
     ActiveDirectoryUser u = new ActiveDirectoryUser();
     u.AddProperty("cn", "tu001");
     u.AddProperty("mail", "*****@*****.**");
     u.AddProperty("sn", "Test");
     u.AddProperty("givenName", "User,MD");
     testUsers.Add(u);
     return testUsers.ToArray();
 }
        private static async Task RemoveGroupFromUserIfExistsAsync(TestContext testContext, Group group)
        {
            var userId           = testContext.Config.TestSettings.ExistingUserId;
            var userIsInTheGroup = await ActiveDirectoryUser.IsUserInAGroupAsync(userId, group.DisplayName, testContext.Tokens.GraphApiBearerToken);

            if (userIsInTheGroup)
            {
                await ActiveDirectoryUser.RemoveTheUserFromTheGroupAsync(userId, group.GroupId, testContext.Tokens.GraphApiBearerToken);
            }
            testContext.Test.NewGroupId = null;
        }
        private static async Task RemoveGroupFromUserIfExists(TestContext context)
        {
            var userIsInTheGroup = await ActiveDirectoryUser.IsUserInAGroupAsync(context.Config.TestSettings.ExistingUserId,
                                                                                 context.Config.TestSettings.NewGroups.First().DisplayName, context.Tokens.GraphApiBearerToken);

            if (userIsInTheGroup)
            {
                await ActiveDirectoryUser.RemoveTheUserFromTheGroupAsync(context.Config.TestSettings.ExistingUserId,
                                                                         context.Config.TestSettings.NewGroups.First().GroupId, context.Tokens.GraphApiBearerToken);
            }
            context.Test.NewGroupId = null;
        }
Example #26
0
        public void SurreyEmailIsSurreyCountyCouncil()
        {
            var user = new ActiveDirectoryUser()
            {
                Mail = "*****@*****.**", Company = String.Empty
            };
            var transformer = new OrbisPartnersDataTransformer();

            transformer.TransformUser(user);

            Assert.AreEqual("Surrey County Council", user.Company);
        }
Example #27
0
        public void SurreyDepartmentSuffixIsRemovedFromName()
        {
            var user = new ActiveDirectoryUser()
            {
                Name = "John Smith BUS"
            };
            var transformer = new OrbisPartnersDataTransformer();

            transformer.TransformUser(user);

            Assert.AreEqual("John Smith", user.Name);
        }
Example #28
0
        public void EsccIsEastSussexCountyCouncil()
        {
            var user = new ActiveDirectoryUser()
            {
                Company = "ESCC"
            };
            var transformer = new OrbisPartnersDataTransformer();

            transformer.TransformUser(user);

            Assert.AreEqual("East Sussex County Council", user.Company);
        }
Example #29
0
        public void ValidPhoneNumberIsUnaltered()
        {
            var user = new ActiveDirectoryUser()
            {
                TelephoneNumber = "01234 456789"
            };
            var transformer = new OrbisPartnersDataTransformer();

            transformer.TransformUser(user);

            Assert.AreEqual("01234 456789", user.TelephoneNumber);
        }
Example #30
0
        public void PhoneNumberPunctuationIsRemoved()
        {
            var user = new ActiveDirectoryUser()
            {
                TelephoneNumber = "(01234) 456789"
            };
            var transformer = new OrbisPartnersDataTransformer();

            transformer.TransformUser(user);

            Assert.AreEqual("01234 456789", user.TelephoneNumber);
        }
Example #31
0
        public void SurreyNoPhoneNumberTextIsRemoved(string phoneNumber)
        {
            var user = new ActiveDirectoryUser()
            {
                TelephoneNumber = phoneNumber
            };
            var transformer = new OrbisPartnersDataTransformer();

            transformer.TransformUser(user);

            Assert.IsEmpty(user.TelephoneNumber);
        }
        public User CreateUser(ActiveDirectoryUser adUser)
        {
            ActiveDirectoryUser[] adUsers = _Service.SearchActiveDirectory(adUser.cn);
            if (adUsers.Length > 1)
            {
                throw new UserCreationException("Multiple user accounts found in Active Directory for " + adUser.cn + ".  Cannot continue.");
            }
            else if (adUsers.Length == 0)
            {
                throw new UserCreationException("No user account found in Active Directory for " + adUser.cn + ".  Cannot continue.");
            }

            ResultsService manager = new ResultsService();
            Level[] levels = manager.GetLevels();
            Transport[] transports = manager.GetTransports();
            Transport smtp = null;
            foreach (Transport transport in transports)
            {
                if (transport.Name == Properties.Settings.Default.SmtpTransportName)
                    smtp = transport;
            }

            User user = new User();
            user.UserName = adUser.mail;
            user.MiddleName = "";

            user.LastName = adUser.sn ?? "";
            user.FirstName = adUser.givenName ?? "";

            user.Enabled = true;

            List<UserTransport> userTransports = new List<UserTransport>();
            if (smtp != null)
            {
                UserTransport userMail = new UserTransport();
                userMail.Address = adUser.mail ?? "";
                userMail.Levels = levels;
                userMail.Transport = smtp;
                userTransports.Add(userMail);
            }

            user.Transports = userTransports.ToArray();
            Extension.DefaultExtension.ExtendUserFromExternalDirectory(user, transports, levels, adUser.mail, adUser.proxyAddresses);

            user = manager.CreateANCRUser(user);

            manager.AssignUserToRole(user.UserName, "Receiver");
            //manager.AccountConfirmation(user.UserName);
            //manager.CreatePassword(user.UserName);

            Setting[] settings = manager.GetSettings_NonWeb("System");
            string defaultAccountDomain = "";
            foreach (Setting setting in settings)
            {
                if (setting.EntryKey == "DefaultAccountDomain")
                    defaultAccountDomain = setting.Value;
            }

            manager.UserEntry(user.UserName, "AuthExt", "Windows", defaultAccountDomain + "\\" + adUser.cn, "");
            return user;
        }
        public static void GetUsersFromAD()
        {
            //if (HttpContext.Current.Cache["ADUSERS"] == null)
            IDatabase cache = MvcApplication.RedisCache.GetDatabase();
            var adUsers = cache.Get<List<ActiveDirectoryUser>>("ADUSERS");
            if (adUsers == null)
            {
                // Graph API Settings
                string graphResourceId = "https://graph.windows.net";
                string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
                string appPassword = ConfigurationManager.AppSettings["ida:Password"];
                Uri audienceUri = new Uri(ConfigurationManager.AppSettings["ida:AudienceUri"]);
                string tenant = audienceUri.Host;
                string Authority = String.Format("https://login.windows.net/{0}", tenant);

                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Authority);
                activeDirectoryUsers = new List<ActiveDirectoryUser>();
                ClientCredential credential = new ClientCredential(clientId, appPassword);
                AuthenticationResult result = null;
                List<User> userList = new List<User>();
                result = authContext.AcquireToken(graphResourceId, credential);

                //Setup Graph API connection and get a list of users
                Guid ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings = new GraphSettings();
                graphSettings.ApiVersion = "2013-11-08";

                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);
                // Get results from all pages into a list
                PagedResults<User> pagedResults = graphConnection.List<User>(null, new FilterGenerator());
                userList.AddRange(pagedResults.Results);
                while (!pagedResults.IsLastPage)
                {
                    pagedResults = graphConnection.List<User>(pagedResults.PageToken, new FilterGenerator());
                    userList.AddRange(pagedResults.Results);
                }
                foreach (var u in userList)
                {
                    var adUser = new ActiveDirectoryUser();
                    adUser.Location = String.Format("{0},{1}", u.City, u.State);
                    adUser.FullName = u.GivenName + " " + u.Surname;
                    adUser.Position = u.JobTitle;
                    adUser.ActiveDirectoryId = u.UserPrincipalName;
                    adUser.ObjectId = u.ObjectId;

                    try
                    {
                        using (Stream ms = graphConnection.GetStreamProperty(u, GraphProperty.ThumbnailPhoto, "image/jpeg"))
                        {
                            if (ms != null)
                            {
                                byte[] b;
                                using (BinaryReader br = new BinaryReader(ms))
                                {
                                    b = br.ReadBytes((int)ms.Length);
                                }
                                adUser.ThumbnailPhoto = b;
                                // Retrieve via the controller
                                adUser.ImageUrl = String.Format("/AdImages/Details/{0}", adUser.ObjectId);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        adUser.ImageUrl = "/images/user-placeholder.png";
                    }
                    activeDirectoryUsers.Add(adUser);
                }
                // HttpContext.Current.Cache.Insert("ADUSERS", activeDirectoryUsers, null, DateTime.Now.AddMinutes(5), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
                cache.Set("ADUSERS", activeDirectoryUsers, TimeSpan.FromMinutes(5));

            }
            else
            {
                //activeDirectoryUsers = (List<ActiveDirectoryUser>)HttpContext.Current.Cache["ADUSERS"];
                activeDirectoryUsers = (List<ActiveDirectoryUser>)cache.Get("ADUSERS");
            }
        }
 public static ActiveDirectoryUser CreateActiveDirectoryUser(string cn, int groupType, int sAMAccountType, long uSNChanged, long uSNCreated, global::System.DateTime whenChanged, global::System.DateTime whenCreated)
 {
     ActiveDirectoryUser activeDirectoryUser = new ActiveDirectoryUser();
     activeDirectoryUser.cn = cn;
     activeDirectoryUser.groupType = groupType;
     activeDirectoryUser.sAMAccountType = sAMAccountType;
     activeDirectoryUser.uSNChanged = uSNChanged;
     activeDirectoryUser.uSNCreated = uSNCreated;
     activeDirectoryUser.whenChanged = whenChanged;
     activeDirectoryUser.whenCreated = whenCreated;
     return activeDirectoryUser;
 }
 public void AddToActiveDirectoryUsers(ActiveDirectoryUser activeDirectoryUser)
 {
     base.AddObject("ActiveDirectoryUsers", activeDirectoryUser);
 }
        private ActiveDirectoryUser[] ParseFull(SearchResultCollection results)
        {
            List<ActiveDirectoryUser> userList = new List<ActiveDirectoryUser>();

            foreach (SearchResult result in results)
            {
                ActiveDirectoryUser u = new ActiveDirectoryUser();
                userList.Add(u);

                DirectoryEntry innerEntry = new DirectoryEntry(result.Path,
                    CriticalResults.Properties.Settings.Default.LDAPUsername,
                    CriticalResults.Properties.Settings.Default.LDAPPassword);
                int proxyAddressCount = 0;
                foreach (string name in innerEntry.Properties.PropertyNames)
                {
                    //Added to retrieve proxy email address from active directory to facilitate partners search
                    //Check if value is array of objects instead of single object
                    if (innerEntry.Properties[name].Value.GetType() == typeof(object[]) && name == "proxyAddresses")
                    {
                        //Get array of values
                        object[] value = (object[])innerEntry.Properties[name].Value;
                        foreach (object obj in value)
                        {
                            //if value is an email address add it to the user object with name of 'mail_x'
                            if (((string)obj).ToLower().Contains("smtp"))
                            {
                                proxyAddressCount++;
                                string property_value = obj as string;
                                string property_name = "mail_" + proxyAddressCount.ToString();
                                u.AddProperty(property_name, property_value);
                            }
                        }
                    }
                    else
                    {
                        string value = innerEntry.Properties[name].Value.ToString();
                        u.AddProperty(name, value);
                    }
                }
                u.AddProperty("Proxy_Address_Count", proxyAddressCount.ToString());
            }
            return userList.ToArray();
        }
        private ActiveDirectoryUser[] ParseSubset(SearchResultCollection results)
        {
            List<ActiveDirectoryUser> userList = new List<ActiveDirectoryUser>();

            foreach (SearchResult result in results)
            {
                ActiveDirectoryUser u = new ActiveDirectoryUser();
                userList.Add(u);

                DirectoryEntry innerEntry = new DirectoryEntry(result.Path,
                    CriticalResults.Properties.Settings.Default.LDAPUsername,
                    CriticalResults.Properties.Settings.Default.LDAPPassword);

                List<string> proxyAddresses = new List<string>();

                object[] proxyAddressesVal = (object[])innerEntry.Properties["proxyAddresses"].Value;
                if (proxyAddressesVal != null)
                {
                    foreach (object obj in proxyAddressesVal)
                    {
                        //if value is an email address add it to the user object with name of 'mail_x'
                        if (((string)obj).ToLower().Contains("smtp"))
                        {
                            proxyAddresses.Add(((string)obj).Replace("smtp:", "").Replace("SMTP:", ""));
                        }
                    }
                }
                u.proxyAddresses = proxyAddresses.ToArray();
                if(innerEntry.Properties["cn"].Value != null)
                    u.cn = innerEntry.Properties["cn"].Value.ToString();
                if(innerEntry.Properties["givenName"].Value != null)
                    u.givenName = innerEntry.Properties["givenName"].Value.ToString();
                if(innerEntry.Properties["sn"].Value != null)
                    u.sn = innerEntry.Properties["sn"].Value.ToString();
                if(innerEntry.Properties["mail"].Value != null)
                    u.mail = innerEntry.Properties["mail"].Value.ToString();
                if(innerEntry.Properties["displayName"].Value != null)
                    u.displayName = innerEntry.Properties["displayName"].Value.ToString();
                if (string.IsNullOrEmpty(u.mail) && u.proxyAddresses.Length > 0)
                {
                    u.mail = u.proxyAddresses[0];
                }
            }
            return userList.ToArray();
        }