/// <summary>
        /// Overrides the default behaviour to return an instance of ActiveDirectoryUser
        /// based on the current user in the context if a UserPart hasn't been created for
        /// the active directory user yet.
        /// </summary>
        /// <returns></returns>
        public IUser GetAuthenticatedUser()
        {
            // attempts to get the user from the UserPart data store.
            var user = _membershipService.GetUser(HttpContext.Current.User.Identity.Name);

            // if the user doesn't exist in the UserPart data store, then the
            // current active directory user is returned instead.
            if (user == null)
                user = new ActiveDirectoryUser();

            return user;
        }
        /// <summary>
        /// Overrides the default behaviour to return an instance of ActiveDirectoryUser
        /// based on the current user in the context if a UserPart hasn't been created for
        /// the active directory user yet.
        /// </summary>
        /// <returns></returns>
        public IUser GetAuthenticatedUser()
        {
			IUser user = null;
			//I noticed thousands of errors in the log due to the Context being null, when indexing services are running.
			if (HttpContext.Current != null)
			{
				// attempts to get the user from the UserPart data store.
				var user = _membershipService.GetUser(HttpContext.Current.User.Identity.Name);

				// if the user doesn't exist in the UserPart data store, then the
				// current active directory user is returned instead.
				if (user == null)
					user = new ActiveDirectoryUser();
			}
            return user;
        }
        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 (!_attemptedToSaveUser)
                    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>
        /// Makes an attempt to communicate with LDAP to retrieve the email
        /// of the active directory user.
        /// </summary>
        /// <param name="activeDiretoryUser">Currently logged in active directory user.</param>
        /// <returns>Email address of active directory user if connection can be
        /// made to LDAP, otherwise an empty string is returned.</returns>
        private string GetEmail(ActiveDirectoryUser activeDirectoryUser)
        {
            var domainAndUserName = activeDirectoryUser.UserName.Split('\\');
            var email = "";

            if (domainAndUserName.Length == 2)
            {
                try
                {
                    var ctx = new PrincipalContext(ContextType.Domain, domainAndUserName[0]);
                    var up = UserPrincipal.FindByIdentity(ctx, activeDirectoryUser.UserName);

                    if (up != null && up.EmailAddress != null)
                        email = up.EmailAddress.ToLowerInvariant();
                }
                catch { }
            }

            return email;
        }
        /// <summary>
        /// Does a check to see if there is an Orchard user that represents the active directory user.
        /// If there isn't then one is created with the username from the active directory user.
        /// </summary>
        /// <param name="activeDirectoryUser">Currently logged in active directory user.</param>
        /// <returns>Returns the user that was created, or if one wasn't created then the
        /// UserPart that is already in the database is returned.</returns>
        private IUser CreateUserForActiveDirectoryUserIfNotExists(ActiveDirectoryUser activeDirectoryUser)
        {
            var user = GetUser(activeDirectoryUser.UserName);

            if (user == null && !String.IsNullOrEmpty(activeDirectoryUser.UserName))
            {
                user = CreateUser(new CreateUserParams(activeDirectoryUser.UserName, "password", GetEmail(activeDirectoryUser), String.Empty, String.Empty, true));
                CreateUserRoles(user, activeDirectoryUser.Roles);
            }

            return user;
        }
        public bool TryCheckAccess(Permission permission, IUser user, IContent content)
        {
            user = new ActiveDirectoryUser();

            var context = new CheckAccessContext { Permission = permission, User = user, Content = content };
            _authorizationServiceEventHandler.Checking(context);

            for (var adjustmentLimiter = 0; adjustmentLimiter != 3; ++adjustmentLimiter)
            {
                if (!context.Granted && context.User != null)
                {
                    if (!String.IsNullOrEmpty(_workContextAccessor.GetContext().CurrentSite.SuperUser) &&
                           String.Equals(context.User.UserName, _workContextAccessor.GetContext().CurrentSite.SuperUser, StringComparison.Ordinal))
                    {
                        context.Granted = true;
                    }
                }

                if (!context.Granted)
                {
                    // determine which set of permissions would satisfy the access check
                    var grantingNames = PermissionNames(context.Permission, Enumerable.Empty<string>()).Distinct().ToArray();

                    // determine what set of roles should be examined by the access check
                    IEnumerable<string> rolesToExamine;
                    if (context.User == null)
                    {
                        rolesToExamine = AnonymousRole;
                    }
                    else
                    {
                        //retrieve the UserPart record for the user from the DB (if there is one)
                        UserPart dbUser = null;
                        if (!string.IsNullOrWhiteSpace(context.User.UserName))
                        {
                            dbUser = _contentManager.Query<UserPart, UserPartRecord>().Where(x => x.NormalizedUserName == context.User.UserName.ToLowerInvariant()).List().FirstOrDefault();
                        }

                        // This line has been changed from the core implementation of IAuthorizationService,
                        // because our ActiveDirectoryUser implements the IUserRoles interface instead of having
                        // an UserRolesPart included on the content.
                        rolesToExamine = (context.User as IUserRoles).Roles;

                        //Also adding all the Roles from the UserRolePart, incase We want to use role management that is not part of AD..
                        if (dbUser != null && dbUser.As<IUserRoles>() != null && dbUser.As<IUserRoles>().Roles != null)
                            rolesToExamine = rolesToExamine.Union(dbUser.As<IUserRoles>().Roles);

                        // when it is a simulated anonymous user in the admin
                        if (!rolesToExamine.Contains(AnonymousRole[0]))
                        {
                            rolesToExamine = rolesToExamine.Concat(AuthenticatedRole);
                        }
                    }

                    foreach (var role in rolesToExamine)
                    {
                        foreach (var permissionName in _roleService.GetPermissionsForRoleByName(role))
                        {
                            string possessedName = permissionName;
                            if (grantingNames.Any(grantingName => String.Equals(possessedName, grantingName, StringComparison.OrdinalIgnoreCase)))
                            {
                                context.Granted = true;
                            }

                            if (context.Granted)
                                break;
                        }

                        if (context.Granted)
                            break;
                    }
                }

                context.Adjusted = false;
                _authorizationServiceEventHandler.Adjust(context);
                if (!context.Adjusted)
                    break;
            }

            _authorizationServiceEventHandler.Complete(context);

            return context.Granted;
        }
        public bool TryCheckAccess(Permission permission, IUser user, IContent content)
        {
            user = new ActiveDirectoryUser();

            var context = new CheckAccessContext { Permission = permission, User = user, Content = content };
            _authorizationServiceEventHandler.Checking(context);

            for (var adjustmentLimiter = 0; adjustmentLimiter != 3; ++adjustmentLimiter)
            {
                if (!context.Granted && context.User != null)
                {
                    if (!String.IsNullOrEmpty(_workContextAccessor.GetContext().CurrentSite.SuperUser) &&
                           String.Equals(context.User.UserName, _workContextAccessor.GetContext().CurrentSite.SuperUser, StringComparison.Ordinal))
                    {
                        context.Granted = true;
                    }
                }

                if (!context.Granted)
                {
                    // determine which set of permissions would satisfy the access check
                    var grantingNames = PermissionNames(context.Permission, Enumerable.Empty<string>()).Distinct().ToArray();

                    // determine what set of roles should be examined by the access check
                    IEnumerable<string> rolesToExamine;
                    if (context.User == null)
                    {
                        rolesToExamine = AnonymousRole;
                    }
                    else
                    {
                        // the current user is not null, so get his roles and add "Authenticated" to it.

                        // This line has been changed from the core implementation of IAuthorizationService,
                        // because our ActiveDirectoryUser implements the IUserRoles interface instead of having
                        // an UserRolesPart included on the content.
                        rolesToExamine = (context.User as IUserRoles).Roles;

                        // when it is a simulated anonymous user in the admin
                        if (!rolesToExamine.Contains(AnonymousRole[0]))
                        {
                            rolesToExamine = rolesToExamine.Concat(AuthenticatedRole);
                        }
                    }
   
                    foreach (var role in rolesToExamine)
                    {
                        foreach (var permissionName in _roleService.GetPermissionsForRoleByName(role))
                        {
                            string possessedName = permissionName;
                            if (grantingNames.Any(grantingName => String.Equals(possessedName, grantingName, StringComparison.OrdinalIgnoreCase)))
                            {
                                context.Granted = true;
                            }

                            if (context.Granted)
                                break;
                        }

                        if (context.Granted)
                            break;
                    }
                }

                context.Adjusted = false;
                _authorizationServiceEventHandler.Adjust(context);
                if (!context.Adjusted)
                    break;
            }

            _authorizationServiceEventHandler.Complete(context);

            return context.Granted;
        }