Raises an exception if the given username is not valid.
544139
def __verify_username(self, username):
        """"""

        if len(username) > self.__max_length or len(username) < 3:
            raise ValueError(
                f"Username must be between 3 and {self.__max_length} characters."
            )
        if any(c not in string.ascii_letters + string.digits for c in username):
            raise ValueError("Usernames can only contain alphanumeric characters.")
440099
def assert_valid(self, instance, value=None):
        
        if value is None:
            value = instance._get(self.name)
        if (
                value is not None and
                not self.equal(value, self.validate(instance, value))
        ):
            message = 'Invalid value for property: {}: {}'.format(
                self.name, value
            )
            raise ValidationError(message, 'invalid', self.name, instance)
        return True
711902
def CheckIfUserIsAdmin(self, username):
    """"""

    user_obj = data_store.REL_DB.ReadGRRUser(username)
    if user_obj.user_type != user_obj.UserType.USER_TYPE_ADMIN:
      raise access_control.UnauthorizedAccess("User %s is not an admin." %
                                              username)
188330
def check_basic_auth(self, username, password):
        
        valid = self.users.check_password(
            username, password
        )
        if not valid:
            log.warning('Invalid login from %s', username)
            valid = False
        return (
            valid,
            username
        )
1187617
def a_send_username(username, ctx):
    """"""
    if username:
        ctx.ctrl.sendline(username)
        return True
    else:
        ctx.ctrl.disconnect()
        raise ConnectionAuthenticationError("Username not provided", ctx.ctrl.hostname)
124231
def _validate(self, value):
        """"""
        if self.values and value not in self.values:
            raise ValueError(
                '{} is not a valid value for {}'.format(value, self.name))
840716
def _validate(self, args, kwargs):
    """"""
    def error(exception_type, arg_name=None, **msg_kwargs):
      if arg_name is None:
        arg_name = args[0] if args else '<unknown>'
      raise exception_type(self.scope, arg_name, **msg_kwargs)

    if not args:
      error(NoOptionNames)
    # validate args.
    for arg in args:
      if not arg.startswith('-'):
        error(OptionNameDash, arg_name=arg)
      if not arg.startswith('--') and len(arg) > 2:
        error(OptionNameDoubleDash, arg_name=arg)

    # Validate kwargs.
    if 'implicit_value' in kwargs and kwargs['implicit_value'] is None:
      error(ImplicitValIsNone)

    # Note: we check for list here, not list_option, because we validate the provided kwargs,
    # not the ones we modified.  However we temporarily also allow list_option, until the
    # deprecation is complete.
    if 'member_type' in kwargs and kwargs.get('type', str) not in [list, list_option]:
      error(MemberTypeNotAllowed, type_=kwargs.get('type', str).__name__)

    if kwargs.get('member_type', str) not in self._allowed_member_types:
      error(InvalidMemberType, member_type=kwargs.get('member_type', str).__name__)

    for kwarg in kwargs:
      if kwarg not in self._allowed_registration_kwargs:
        error(InvalidKwarg, kwarg=kwarg)

      # Ensure `daemon=True` can't be passed on non-global scopes (except for `recursive=True`).
      if (kwarg == 'daemon' and self._scope != GLOBAL_SCOPE and kwargs.get('recursive') is False):
        error(InvalidKwargNonGlobalScope, kwarg=kwarg)

    removal_version = kwargs.get('removal_version')
    if removal_version is not None:
      validate_deprecation_semver(removal_version, 'removal version')
1266799
def change_username(self, username):
        

        def cb():

            if self.login_method == "username" and "@" in username:
                raise exceptions.AuthError(_("Username can't be an email"))
            elif self.login_method == "email" and "@" not in username:
                raise exceptions.AuthError(_("Invalid email login"))
            if "@" in username:
                if not utils.is_email_valid(username):
                    raise exceptions.AuthError("Email address invalid")
            elif not utils.is_username_valid(username):
                raise exceptions.AuthError("Username invalid")

            # Change both email and
            if self.login_method == "email":
                if not models.AuthUser.get_by_username(username) \
                        and not models.AuthUser.get_by_email(username):
                    self.user.change_username(username)
                    self.user.change_email(username)
            else:
                self.user.change_username(username)
            return username

        return signals.user_update(self, ACTIONS["USERNAME"], cb)
1137195
def clean_username(self):
    

    data = self.cleaned_data['username']
    if User.objects.filter(username=data).exists():
      if not (self.instance.pk is not None and self.instance.user.username == data):
        raise forms.ValidationError(_('Usuario "%(username)s" ocupado'), code='invalid', params={'username': data})
    return data
186990
def authentication_validation(username, password, access_token):
    '''
    
    '''
    if bool(username) is not bool(password):
        raise Exception("Basic authentication requires a username AND"
                        " password.")
    if (username and access_token) or (password and access_token):
        raise Exception("Cannot use both Basic Authentication and"
                        " OAuth2.0. Please use only one authentication"
                        " method.")
693732
def validate_name(name)
      raise InvalidIntrospectionData if name.bytesize > 255
      raise InvalidIntrospectionData if name =~ /^\./ || name =~ /\.$/
      raise InvalidIntrospectionData if name =~ /\.\./
      raise InvalidIntrospectionData if name !~ /\./
      name.split(".").each do |element|
        raise InvalidIntrospectionData if element !~ INTERFACE_ELEMENT_RE
      end
    end
959216
def validate_login(ctx, param, value):
    """"""
    # pylint: disable=unused-argument
    value = value.strip()
    if not value:
        raise click.BadParameter("The value cannot be blank.", param=param)
    return value
634514
def validate_uuid(value):
    

    if value and not isinstance(value, UUID):
        try:
            return UUID(str(value), version=4)
        except (AttributeError, ValueError):
            raise ValidationError('not a valid UUID')
    return value
1282515
function userExists(user) {
  if (_.isEmpty(findUser(user, {refresh: true, throwIfNotFound: false}))) {
    return false;
  } else {
    return true;
  }
}
837237
def authenticate(self, username, password):
        

        r = self._query_('/users/authenticate', 'POST',
                         params={'username': username,
                                 'password': password})
        if r.status_code == 201:
            return r.text.strip('"')
        else:
            raise ValueError('Authentication invalid.')
352788
def clean_username(self):
        
        try:
            user = get_user_model().objects.get(username__iexact=self.cleaned_data['username'])
        except get_user_model().DoesNotExist:
            pass
        else:
            if userena_settings.USERENA_ACTIVATION_REQUIRED and UserenaSignup.objects.filter(user__username__iexact=self.cleaned_data['username']).exclude(activation_key=userena_settings.USERENA_ACTIVATED):
                raise forms.ValidationError(_('This username is already taken but not confirmed. Please check your email for verification steps.'))
            raise forms.ValidationError(_('This username is already taken.'))
        if self.cleaned_data['username'].lower() in userena_settings.USERENA_FORBIDDEN_USERNAMES:
            raise forms.ValidationError(_('This username is not allowed.'))
        return self.cleaned_data['username']
1139968
def validate_username(username):
    

    # Check username looks ok

    if not username.islower():
        raise UsernameInvalid(six.u('Username must be all lowercase'))
    if len(username) < 2:
        raise UsernameInvalid(six.u('Username must be at least 2 characters'))
    if not username_re.search(username):
        raise UsernameInvalid(settings.USERNAME_VALIDATION_ERROR_MSG)

    return username