Populate the given profile object flags from AUTH_LDAP_PROFILE_FLAGS_BY_DN_REGEX.
        Returns True if the profile was modified
326698
def _populate_user_from_dn_regex(self):
        
        for field, regex in self.settings.USER_FLAGS_BY_DN_REGEX.items():
            field_value = False
            if re.search(regex, self._get_user_dn(), re.IGNORECASE):
                field_value = True
            setattr(self._user, field, field_value)
872888
def update_user_flags(self, user, claims):
        
        if settings.GROUPS_CLAIM is not None:
            if settings.GROUPS_CLAIM in claims:
                access_token_groups = claims[settings.GROUPS_CLAIM]
                if not isinstance(access_token_groups, list):
                    access_token_groups = [access_token_groups, ]
            else:
                logger.debug("The configured group claim was not found in the access token")
                access_token_groups = []

            for flag, group in settings.GROUP_TO_FLAG_MAPPING.items():
                if hasattr(user, flag):
                    if group in access_token_groups:
                        value = True
                    else:
                        value = False
                    setattr(user, flag, value)
                    logger.debug("Attribute '{}' for user '{}' was set to '{}'.".format(user, flag, value))
                else:
                    msg = "User model has no field named '{}'. Check ADFS boolean claims mapping."
                    raise ImproperlyConfigured(msg.format(flag))

        for field, claim in settings.BOOLEAN_CLAIM_MAPPING.items():
            if hasattr(user, field):
                bool_val = False
                if claim in claims and str(claims[claim]).lower() in ['y', 'yes', 't', 'true', 'on', '1']:
                    bool_val = True
                setattr(user, field, bool_val)
                logger.debug('Attribute "{}" for user "{}" was set to "{}".'.format(user, field, bool_val))
            else:
                msg = "User model has no field named '{}'. Check ADFS boolean claims mapping."
                raise ImproperlyConfigured(msg.format(field))
1154411
def matches(self, regex, flags=0):
        
        return self._generate_test(
            lambda value: re.match(regex, value, flags),
            ('matches', self._path, regex)
        )
126239
def populate_user(self):
        
        user = None

        try:
            # self.attrs will only be non-None if we were able to load this user
            # from the LDAP directory, so this filters out nonexistent users.
            if self.attrs is not None:
                self._get_or_create_user(force_populate=True)

            user = self._user
        except ldap.LDAPError as e:
            results = ldap_error.send(
                self.backend.__class__,
                context="populate_user",
                user=self._user,
                exception=e,
            )
            if len(results) == 0:
                logger.warning(
                    "Caught LDAPError while authenticating {}: {}".format(
                        self._username, pprint.pformat(e)
                    )
                )
        except Exception as e:
            logger.warning("{} while authenticating {}".format(e, self._username))
            raise

        return user
569585
def authenticate(self):
        

        # if authentication has been performed, return last result
        if self._authenticated is not None:
            return self._authenticated

        try:
            self._ldap_conn.simple_bind_s(self._ldap_binddn_fmt.format(ldap.dn.escape_dn_chars(self.username)), self.password)
        except ldap.SERVER_DOWN as exc:
            raise AuthError('Could not connect to LDAP server')
        except (ldap.INVALID_CREDENTIALS, ldap.INVALID_DN_SYNTAX,
                ldap.UNWILLING_TO_PERFORM) as exc:
            # Auth failed
            self._logger.debug('erroneous password for user %s' % self.username)
            self._authenticated = False
            return self._authenticated


        # auth succeeded
        self.authenticated_as = self.username
        self.trusted = False
        self.readonly = False

        try:
            # Create separate connection for search?
            if self._ldap_search_conn is not None:
                self._ldap_search_conn.simple_bind(self._ldap_search_binddn, self._ldap_search_password)
                search_conn = self._ldap_search_conn
            else:
                search_conn = self._ldap_conn

            res = search_conn.search_s(self._ldap_basedn, ldap.SCOPE_SUBTREE, self._ldap_search.format(ldap.dn.escape_dn_chars(self.username)), ['cn','memberOf'])
            if res[0][1]['cn'][0] is not None:
                self.full_name = res[0][1]['cn'][0].decode('utf-8')
            # check for ro_group membership if ro_group is configured
            if self._ldap_ro_group:
                if self._ldap_ro_group in res[0][1].get('memberOf', []):
                    self.readonly = True
            # check for rw_group membership if rw_group is configured
            if self._ldap_rw_group:
                if self._ldap_rw_group in res[0][1].get('memberOf', []):
                    self.readonly = False
                else:
                    # if ro_group is configured, and the user is a member of
                    # neither the ro_group nor the rw_group, fail authentication.
                    if self._ldap_ro_group:
                        if self._ldap_ro_group not in res[0][1].get('memberOf', []):
                            self._authenticated = False
                            return self._authenticated
                    else:
                        self.readonly = True

        except ldap.LDAPError as exc:
            raise AuthError(exc)
        except KeyError:
            raise AuthError('LDAP attribute missing')
        except IndexError:
            self.full_name = ''
            # authentication fails if either ro_group or rw_group are configured
            # and the user is not found.
            if self._ldap_rw_group or self._ldap_ro_group:
                self._authenticated = False
                return self._authenticated

        self._authenticated = True

        self._logger.debug('successfully authenticated as %s, username %s, full_name %s, readonly %s' % (self.authenticated_as, self.username, self.full_name, str(self.readonly)))
        return self._authenticated
443046
public static void populateSubject(final LinkedHashMap<String, CommonProfile> profiles) {
        if (profiles != null && profiles.size() > 0) {
            final List<CommonProfile> listProfiles = ProfileHelper.flatIntoAProfileList(profiles);
            try {
                if (IS_FULLY_AUTHENTICATED_AUTHORIZER.isAuthorized(null, listProfiles)) {
                    SecurityUtils.getSubject().login(new Pac4jToken(listProfiles, false));
                } else if (IS_REMEMBERED_AUTHORIZER.isAuthorized(null, listProfiles)) {
                    SecurityUtils.getSubject().login(new Pac4jToken(listProfiles, true));
                }
            } catch (final HttpAction e) {
                throw new TechnicalException(e);
            }
        }
    }
564154
def profile(request):
    '''
    
    '''
    serializer_class = registration_settings.PROFILE_SERIALIZER_CLASS
    if request.method in ['POST', 'PUT', 'PATCH']:
        partial = request.method == 'PATCH'
        serializer = serializer_class(
            instance=request.user,
            data=request.data,
            partial=partial,
        )
        serializer.is_valid(raise_exception=True)
        serializer.save()
    else:  # request.method == 'GET':
        serializer = serializer_class(instance=request.user)

    return Response(serializer.data)
1011848
function verifyProfile(profile, profileKey) {
    if (!profile.file && !profile.url) {
        throw new Error(`[${profileKey}] Must specify a file or url in the configuration.`);
    }
    if (!profile.output) {
        throw new Error(`[${profileKey}] Must specify an output file path in the configuration.`);
    }
    if (!profile.generator) {
        throw new Error(`[${profileKey}] Must specify a generator in the configuration.`);
    }
    if (profile.generator.toLowerCase() === 'core') {
        throw new Error(`[${profileKey}] Invalid generator ${profile.generator}. This name is reserved.`);
    }
    if (profile.generator.match(/^[\w-]+-language$/i)) {
        throw new Error(`[${profileKey}] Invalid generator ${profile.generator}. The -language suffix is reserved for language helper packages.`);
    }
    profile.debug = profile.debug || {};
    profile.filters = profile.filters || {};
    profile.transforms = profile.transforms || {};
    profile.options = profile.options || {};
}
154412
def restoreSettings(self, settings, merge=False, loadProfile=True):
        
        value = unwrapVariant(settings.value('profile_toolbar'))
        if not value:
            return
        
        self.loadString(value, merge, loadProfile=loadProfile)
863566
def __load_unique_identities(self, uidentities, matcher, match_new,
                                 reset, verbose):
        """"""

        self.new_uids.clear()

        n = 0

        if reset:
            self.__reset_unique_identities()

        self.log("Loading unique identities...")

        for uidentity in uidentities:
            self.log("\n=====", verbose)
            self.log("+ Processing %s" % uidentity.uuid, verbose)

            try:
                stored_uuid = self.__load_unique_identity(uidentity, verbose)
            except LoadError as e:
                self.error("%s Skipping." % str(e))
                self.log("=====", verbose)
                continue

            stored_uuid = self.__load_identities(uidentity.identities, stored_uuid,
                                                 verbose)

            try:
                self.__load_profile(uidentity.profile, stored_uuid, verbose)
            except Exception as e:
                self.error("%s. Loading %s profile. Skipping profile." %
                           (str(e), stored_uuid))

            self.__load_enrollments(uidentity.enrollments, stored_uuid,
                                    verbose)

            if matcher and (not match_new or stored_uuid in self.new_uids):
                stored_uuid = self._merge_on_matching(stored_uuid, matcher,
                                                      verbose)

            self.log("+ %s (old %s) loaded" % (stored_uuid, uidentity.uuid),
                     verbose)
            self.log("=====", verbose)
            n += 1

        self.log("%d/%d unique identities loaded" % (n, len(uidentities)))
1291732
def _get_userprofile_from_registry(user, sid):
    '''
    
    '''
    profile_dir = __utils__['reg.read_value'](
        'HKEY_LOCAL_MACHINE',
        'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\{0}'.format(sid),
        'ProfileImagePath'
    )['vdata']
    log.debug(
        'user %s with sid=%s profile is located at "%s"',
        user, sid, profile_dir
    )
    return profile_dir
261352
def member_of_ldap_group?(groups)
      return false unless respond_to? :ldap_lookup_key
      return false if LDAPGroupsLookup.service.nil?
      groups = [groups] if groups.is_a? String
      dn = LDAPGroupsLookup.lookup_dn ldap_lookup_key
      return LDAPGroupsLookup.walk_ldap_members(groups, dn)
    end
374634
def __create_profile_from_identities(self, identities, uuid, verbose):
        """"""

        import re

        EMAIL_ADDRESS_REGEX = r"^(?P<email>[^\s@]+@[^\s@.]+\.[^\s@]+)$"
        NAME_REGEX = r"^\w+\s\w+"

        name = None
        email = None
        username = None

        for identity in identities:
            if not name and identity.name:
                m = re.match(NAME_REGEX, identity.name)

                if m:
                    name = identity.name

            if not email and identity.email:
                m = re.match(EMAIL_ADDRESS_REGEX, identity.email)

                if m:
                    email = identity.email

            if not username:
                if identity.username and identity.username != 'None':
                    username = identity.username

        # We need a name for each profile, so if no one was defined,
        # use email or username to complete it.
        if not name:
            if email:
                name = email.split('@')[0]
            elif username:
                # filter email addresses on username fields
                name = username.split('@')[0]
            else:
                name = None

        kw = {'name': name,
              'email': email}

        api.edit_profile(self.db, uuid, **kw)

        self.log("-- profile %s updated" % uuid, verbose)
461960
def _fetch_profile_opts(
        cfg, virtualname,
        __salt__,
        _options,
        profile_attr,
        profile_attrs
    ):
    

    if (not profile_attr) or (profile_attr not in _options):
        return {}

    # Using a profile and it is in _options

    creds = {}
    profile = _options[profile_attr]
    if profile:
        log.info('Using profile %s', profile)

        if 'config.option' in __salt__:
            creds = cfg(profile)
        else:
            creds = cfg.get(profile)

    if not creds:
        return {}

    return dict(
        (
            pattr,
            creds.get('{0}.{1}'.format(virtualname, profile_attrs[pattr]))
        )
        for pattr in profile_attrs
        )
1009437
def _config(key, mandatory=True, opts=None):
    '''
    
    '''
    try:
        if opts:
            value = opts['auth.ldap.{0}'.format(key)]
        else:
            value = __opts__['auth.ldap.{0}'.format(key)]
    except KeyError:
        try:
            value = __defopts__['auth.ldap.{0}'.format(key)]
        except KeyError:
            if mandatory:
                msg = 'missing auth.ldap.{0} in master config'.format(key)
                raise SaltInvocationError(msg)
            return False
    return value
1373350
def _load_user_dn(self):
        
        if self._using_simple_bind_mode():
            self._user_dn = self._construct_simple_user_dn()
        else:
            if self.settings.CACHE_TIMEOUT > 0:
                cache_key = valid_cache_key(
                    "django_auth_ldap.user_dn.{}".format(self._username)
                )
                self._user_dn = cache.get_or_set(
                    cache_key, self._search_for_user_dn, self.settings.CACHE_TIMEOUT
                )
            else:
                self._user_dn = self._search_for_user_dn()
1226450
def add_member(self, member, dn=False):
        

        if dn:
            if self.check_member(member, dn=True):
                return
            mod = (ldap.MOD_ADD, 'member', member.encode('ascii'))
        else:
            if self.check_member(member):
                return
            mod = (ldap.MOD_ADD, 'member', member.get_dn().encode('ascii'))

        if self.__lib__.__batch_mods__:
            self.__lib__.enqueue_mod(self.__dn__, mod)
        elif not self.__lib__.__ro__:
            mod_attrs = [mod]
            self.__con__.modify_s(self.__dn__, mod_attrs)
        else:
            print("ADD VALUE member = {} FOR {}".format(mod[2], self.__dn__))