Python bcrypt 模块,hashpw() 实例源码

我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用bcrypt.hashpw()

项目:WeHack2017    作者:Makillya    | 项目源码 | 文件源码
def login(self, userInput):
        # errorList - Keeps tracks of all errors with the validation.
        errorList = []

        mail=userInput['check_email']
        # Checks if the email and password don't match.
        if not mail and not userInput['password']:
            errorList.append('Unsuccessful login. Please fill in the email and password field!\n')
            return False, errorList
        # Check if user is in User table
        print "*************"
        print mail
        if self.filter(email = mail) :
            hashed = self.get(email = mail).password.encode()
            password = userInput['check_password'].encode()
            # Checks if the password is the correct one to the hashed one.
            if bcrypt.hashpw(password, hashed) == hashed:
                return True, self.get(email=mail)

            else:
                errorList.append('Unsuccessful login. Incorrect password!\n')
        else:
            errorList.append('Unsuccessful login. Your email is incorrect!\n')
        return False, errorList
项目:xmpp-cloud-auth    作者:jsxc    | 项目源码 | 文件源码
def auth_update_cache(self):
        if '' in self.ctx.cache_db: # Cache disabled?
            return
        key = self.username + ':' + self.domain
        now = self.now # For tests
        snow = str(now)
        try:
            salt = bcrypt.gensalt(rounds=self.ctx.bcrypt_rounds)
        except TypeError:
            # Old versions of bcrypt() apparently do not support the rounds option
            salt = bcrypt.gensalt()
        pwhash = bcrypt.hashpw(self.password, salt)
        if key in self.ctx.cache_db:
            (ignored, ts1, tsv, tsa, rest) = self.ctx.cache_db[key].split("\t", 4)
            self.ctx.cache_db[key] = "\t".join((pwhash, ts1, snow, snow, rest))
        else:
            self.ctx.cache_db[key] = "\t".join((pwhash, snow, snow, snow, ''))
        self.try_db_sync()
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def _calc_checksum(self, secret):
        # bcrypt behavior:
        #   secret must be bytes
        #   config must be ascii bytes
        #   returns ascii bytes
        secret, ident = self._prepare_digest_args(secret)
        config = self._get_config(ident)
        if isinstance(config, unicode):
            config = config.encode("ascii")
        hash = _bcrypt.hashpw(secret, config)
        assert hash.startswith(config) and len(hash) == len(config)+31, \
            "config mismatch: %r => %r" % (config, hash)
        assert isinstance(hash, bytes)
        return hash[-31:].decode("ascii")

#-----------------------------------------------------------------------
# bcryptor backend
#-----------------------------------------------------------------------
项目:Kameleon    作者:ThinkEE    | 项目源码 | 文件源码
def __setattr__(self, name, value):
        """
        Overide __setattr__ to update dict value and field value at once
        """
        object.__setattr__(self, name, value)

        if name in self.dictValues: # If updating a field value
            if self._meta.fields[name].salt: # field is salt
                # If field is already salt do nothing.
                # XXX Could create a security issue. What happend is value
                # starts with $2b$ but it's not encrypted. Not critical for now
                if not ("$2b$" in value and value[:4] == "$2b$"):
                    value = bcrypt.hashpw(value.encode('utf8'), bcrypt.gensalt())
                    object.__setattr__(self, name, value)

            # If value is an instance of model class and has a relation.
            # Append it to the corresponding field list
            if hasattr(value, "_meta") and self.isForeignKey(self._meta.fields[name]):
                self.dictValues[name] = getattr(value, self._meta.fields[name].reference.name)
                return

            self.dictValues[name] = value
项目:travel_buddy    作者:bribenn    | 项目源码 | 文件源码
def register(request):
    check = User.objects.validateUser(request.POST)
    if request.method != 'POST':
        return redirect('/')
    if check[0] == False:
        for error in check[1]:
            messages.add_message(request, messages.INFO, error, extra_tags="registration")
            return redirect('/')
    if check[0] == True:
        #has password
        hashed_pw = bcrypt.hashpw(request.POST.get('password').encode(), bcrypt.gensalt())
        #create user
        user = User.objects.create(
            first_name = request.POST.get('first_name'),
            last_name = request.POST.get('last_name'),
            email = request.POST.get('email'),  
            password = hashed_pw,
        )

        #add user to session, logging them in
        request.session['user_id'] = user.id
        #route to user profile page
        return redirect('/user')
项目:DjStarter    作者:mijkal    | 项目源码 | 文件源码
def signup(self, postData):
        errors = []
        response = {}
        #Validate form data
        if not EMAIL_REGEX.match(postData['email']):
            error.append('Email error')
        if postData['password'] != postData['confirm_password']:
            errors.append('Confirm password did not match.')
        elif not PASSWORD_REGEX.match(postData['password']):
            errors.append('Password must blah.')

        #Compile errors and send to response messages
        if errors:
            response['status'] = False
            response['errors'] = errors
        else:
            response['status'] = True
            response['user'] = self.create(
                email=postData['email'],
                first_name=postData['first_name'],
                last_name=postData['last_name'],
                password=bcrypt.hashpw(postData['password'].encode('utf-8'),bcrypt.gensalt())
                )
        return response
项目:polycul.es    作者:makyo    | 项目源码 | 文件源码
def save(self, graph, raw_view_pass, raw_edit_pass, force=False):
        if raw_view_pass:
            view_pass = bcrypt.hashpw(
                raw_view_pass.encode(), bcrypt.gensalt()).decode()
        else:
            view_pass = self.view_pass
        if raw_edit_pass:
            edit_pass = bcrypt.hashpw(
                raw_edit_pass.encode(), bcrypt.gensalt()).decode()
        else:
            edit_pass = self.edit_pass
        cur = self._db.cursor()
        cur.execute('''update polycules
        set graph = ?, view_pass = ?, delete_pass = ?
        where id = ?''', [graph, view_pass, edit_pass, self.id])
        self._db.commit()
        self.graph = graph
        self.view_pass = view_pass
        self.edit_pass = edit_pass
项目:bawk    作者:jttwnsnd    | 项目源码 | 文件源码
def register_submit():
    # first, check to see if the username already exists. SELECT statement.
    check_username_query = "SELECT * FROM user where username = '%s'" % request.form['username']
    cursor.execute(check_username_query)
    check_username_result = cursor.fetchone()
    # second, if it't not taken, then insert the username into mysql
    if (check_username_result is None):
        # no match. insert
        session['username'] = request.form['username']
        real_name = request.form['real_name']
        username = request.form['username']
        password = request.form['password'].encode('utf-8')
        hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())
        email = request.form['email']
        username_insert_query = "INSERT INTO user VALUES (DEFAULT, %s, %s, %s, %s, NULL)"
        cursor.execute(username_insert_query, (real_name, username, hashed_password, email))
        conn.commit()
        return render_template('index.html')
    else:
        # second b, if it is taken, send them back to the register page with a message
        return redirect('/register?username=taken')
项目:bawk    作者:jttwnsnd    | 项目源码 | 文件源码
def register_submit():
    # first, check to see if the username already exists. SELECT statement.
    check_username_query = "SELECT * FROM user where username = '%s'" % request.form['username']
    cursor.execute(check_username_query)
    check_username_result = cursor.fetchone()
    # second, if it't not taken, then insert the username into mysql
    if (check_username_result is None):
        # no match. insert
        session['username'] = request.form['username']
        real_name = request.form['real_name']
        username = request.form['username']
        password = request.form['password'].encode('utf-8')
        hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())
        email = request.form['email']
        username_insert_query = "INSERT INTO user VALUES (DEFAULT, %s, %s, %s, %s, NULL)"
        cursor.execute(username_insert_query, (real_name, username, hashed_password, email))
        conn.commit()
        get_id_query = "SELECT id FROM user where username = '%s'" % request.form['username']
        cursor.execute(get_id_query)
        get_id_result = cursor.fetchone()
        session['id'] = get_id_result[0]
        return render_template('index.html')
    else:
        # second b, if it is taken, send them back to the register page with a message
        return redirect('/register?username=taken')
项目:Quotations    作者:hsono1    | 项目源码 | 文件源码
def val_Login(self, postData):
        user = User.objects.filter(email=postData['email'])
        status = True
        errorlist = []
        if len(postData['email']) < 1 or len(postData['password']) < 1 :
            errorlist.append("Please enter valid email and password")
            return {'errors': errorlist}
        if not EMAIL_REGEX.match(postData['email']):
            errorlist.append("Not a valid email")
            return {'errors': errorlist}
        if len(user) < 1:
            errorlist.append("You need to register first")
            status = False
        if status == False:
            return {'errors': errorlist}
        else:
            if bcrypt.hashpw(postData['password'].encode(), user[0].password.encode()) == user[0].password:
                return {'register': user[0]}
            else:
                errorlist.append("Incorrect Password")
                return {'errors': errorlist}
项目:pydbvolve    作者:Teamworksapp    | 项目源码 | 文件源码
def create_user_table(conn):
    create_sql = """
create table users
(
    id int primary key,
    username text not null,
    hashpw text not null,
    salt text not null,
    last_login_ts timestamp
);
"""
    index_sql = """
create index ix01_users on users(username);
"""

    with conn.cursor() as cur:
        cur.execute(create_sql)
        cur.execute(index_sql)
# End create_user_table
项目:ctforge    作者:secgroup    | 项目源码 | 文件源码
def add_user():
    form = ctforge.forms.UserForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            query_handler((
                'INSERT INTO users (team_id, name, surname, mail, '
                '                   password, admin, hidden) '
                'VALUES (%s, %s, %s, %s, %s, %s, %s)'),
                (form.team_id.data, form.name.data,
                 form.surname.data, form.mail.data,
                 bcrypt.hashpw(form.password.data, bcrypt.gensalt()),
                 form.admin.data, form.hidden.data))
        else:
            flash_errors(form)
        return redirect(url_for('admin', tab='users'))
    return render_template('admin/data.html', form=form, target='user',
                           action='add')
项目:commctl    作者:projectatomic    | 项目源码 | 文件源码
def do_passhash(args):
    """
    Uses bcrypt to hash a password.

    :param args: Parsed ArgumentParser args
    :type args: argparse.Namespace
    :returns: The hashed password
    :rtype: str
    """
    import bcrypt

    if args.password is not None:
        pw = args.password
    elif args.file is not None:
        pw = args.file.read()
    else:
        import getpass
        pw = getpass.getpass()
    salt = bcrypt.gensalt(log_rounds=args.rounds)
    return bcrypt.hashpw(pw, salt)
项目:blog    作者:comynli    | 项目源码 | 文件源码
def register(ctx, request):
    try:
        payload = request.json()
        nickname = payload['nickname']
        mail = payload['mail']
        password = payload['password']
    except KeyError as e:
        raise HTTPBadRequest('{} is required'.format(e))
    except Exception as e:
        raise HTTPBadRequest(e)
    user = User.query.filter(or_(User.nickname == nickname, User.mail == mail)).first()
    if user is not None:
        return jsonify(code=400, message='user exist')

    catalog = Catalog(name='notes')
    user = User(nickname=nickname, mail=mail, catalogs=[catalog],
                password=bcrypt.hashpw(password.encode(), bcrypt.gensalt()))
    db.session.add(user)
    try:
        db.session.commit()
        return jsonify(code=200)
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        raise HTTPInternalServerError(e)
项目:Callandtext    作者:iaora    | 项目源码 | 文件源码
def fuzz_verifier_pybcrypt(self):
        # test against py-bcrypt, if available
        from passlib.handlers.bcrypt import IDENT_2, IDENT_2A, IDENT_2X, IDENT_2Y
        from passlib.utils import to_native_str
        try:
            import bcrypt
        except ImportError:
            return
        if hasattr(bcrypt, "_ffi"):
            return
        def check_pybcrypt(secret, hash):
            "pybcrypt"
            secret = to_native_str(secret, self.fuzz_password_encoding)
            if hash.startswith(IDENT_2Y):
                hash = IDENT_2A + hash[4:]
            try:
                return bcrypt.hashpw(secret, hash) == hash
            except ValueError:
                raise ValueError("py-bcrypt rejected hash: %r" % (hash,))
        return check_pybcrypt
项目:Callandtext    作者:iaora    | 项目源码 | 文件源码
def _calc_checksum_bcrypt(self, secret):
        # bcrypt behavior:
        #   hash must be ascii bytes
        #   secret must be bytes
        #   returns bytes
        if self.ident == IDENT_2:
            # bcrypt doesn't support $2$ hashes; but we can fake $2$ behavior
            # using the $2a$ algorithm, by repeating the password until
            # it's at least 72 chars in length.
            if secret:
                secret = repeat_string(secret, 72)
            config = self._get_config(IDENT_2A)
        else:
            config = self._get_config()
        if isinstance(config, unicode):
            config = config.encode("ascii")
        hash = _bcrypt.hashpw(secret, config)
        assert hash.startswith(config) and len(hash) == len(config)+31
        assert isinstance(hash, bytes)
        return hash[-31:].decode("ascii")
项目:electronic-blackboard    作者:SWLBot    | 项目源码 | 文件源码
def check_user_existed_or_signup(user_info):
    try:
        return_msg = {}

        with UserDao() as userDao:
            is_existed = userDao.checkUserExisted(userName=user_info['user_name'])

        if is_existed:
            return_msg['flash'] = 'The name "{name}" has been used'.format(name=user_info['user_name'])
            return return_msg

        hashed_passwd = bcrypt.hashpw(user_info['user_password'].encode('utf-8'),bcrypt.gensalt())
        with UserDao() as userdao:
            userdao.createNewUser(userName=user_info['user_name'],userPassword=hashed_passwd)

        return_msg['flash'] = 'User "{name}" create success!'.format(name=user_info['user_name'])
        return return_msg
    except:
        return_msg["error"] = "Fail to check whether user is existed or create new user"
        return return_msg
#
项目:jamdb    作者:CenterForOpenScience    | 项目源码 | 文件源码
def _authenticate(self, data):
        namespace = manager.get_namespace(data['namespace'])
        collection = namespace.get_collection(data['collection'])

        if not UserPlugin.is_enabled(collection):
            raise exceptions.PluginNotEnabled(UserPlugin.NAME)

        if not (
            collection.schema
            and 'password' in collection.schema._schema.get('required', [])
            and collection.schema._schema['properties']['password'] == self.PASSWORD_SCHEMA
        ):
            raise exceptions.BadRequest(title='Bad password schema', detail='The schema for password must be {} and must be a required field'.format(self.PASSWORD_SCHEMA))

        # TODO validate retrieved document
        doc = collection.read(data['username'])
        password = doc.data['password'].encode()

        hashed = await asyncio.get_event_loop().run_in_executor(None, lambda: bcrypt.hashpw(data['password'].encode(), password))

        if hashed == password:
            return SelfAuthProvider.type, '{}:{}'.format(namespace.ref, collection.ref), data['username'], 8
        raise exceptions.Unauthorized()
项目:Searchable-Symmetric-Encryption    作者:IanVanHoudt    | 项目源码 | 文件源码
def initKeys(self):
        # initialize keys k & kPrime
        # k used for PRF; kPrime used for Enc/Dec
        # return (k, kPrime)

        #hashed = bcrypt.hashpw(self.password, bcrypt.gensalt())
        hashed = bcrypt.hashpw(self.password, self.salt)

        if(DEBUG > 1):
            print("len of k = %d" % len(hashed))
            print("k = %s" % hashed)

        # Currently k and kPrime are equal
        # TODO: Sort out requirements of k and kPrime
        # Research uses both, but not sure the difference
        return (hashed, hashed)
项目:ecommercesiteComplete    作者:Daz4ever    | 项目源码 | 文件源码
def signUp():
    # Get data from sign up form on front-end (in JSON format)
    custEntry = request.get_json()
    entered_password = custEntry['password']
    entered_password2 = custEntry['password2']
    if entered_password == entered_password2:
        # Encrypt the password entered by the user
        salt = bcrypt.gensalt()
        encrypted_password = bcrypt.hashpw(entered_password.encode('utf-8'), salt)
        # Store the user information as a new entry (with the encrypted_password)
        result = db.insert('customer', username=custEntry['username'], email=custEntry['email'], password=encrypted_password, first_name=custEntry['first_name'], last_name=custEntry['last_name'])
        # Returns the user entered information
        return jsonify(result)
    else:
        # If passwords don't match
        return 'login failed', 401

# Allows a user to login to the site
项目:pets-api    作者:fromzeroedu    | 项目源码 | 文件源码
def post(self):
        if not "app_id" in request.json or not "app_secret" in request.json:
            error = {
                "code": "MISSING_APP_ID_OR_APP_SECRET"
            }
            return jsonify({'error': error}), 400
        existing_app = App.objects.filter(app_id=request.json.get('app_id')).first()
        if existing_app:
            error = {
                "code": "APP_ID_ALREADY_EXISTS"
            }
            return jsonify({'error': error}), 400
        else:
            # create the credentials
            salt = bcrypt.gensalt()
            hashed_password = bcrypt.hashpw(request.json.get('app_secret'), salt)
            app = App(
                app_id=request.json.get('app_id'),
                app_secret=hashed_password
            ).save()
            return jsonify({'result': 'ok'})
项目:Sudoku-Solver    作者:ayush1997    | 项目源码 | 文件源码
def fuzz_verifier_pybcrypt(self):
        # test against py-bcrypt, if available
        from passlib.handlers.bcrypt import IDENT_2, IDENT_2A, IDENT_2B, IDENT_2X, IDENT_2Y, _detect_pybcrypt
        from passlib.utils import to_native_str
        try:
            import bcrypt
        except ImportError:
            return
        if not _detect_pybcrypt():
            return
        def check_pybcrypt(secret, hash):
            """pybcrypt"""
            secret = to_native_str(secret, self.fuzz_password_encoding)
            if len(secret) > 200:  # vulnerable to wraparound bug
                secret = secret[:200]
            if hash.startswith((IDENT_2B, IDENT_2Y)):
                hash = IDENT_2A + hash[4:]
            try:
                return bcrypt.hashpw(secret, hash) == hash
            except ValueError:
                raise ValueError("py-bcrypt rejected hash: %r" % (hash,))
        return check_pybcrypt
项目:best-ever-chat    作者:lazymeadow    | 项目源码 | 文件源码
def post(self):
        if not self.check_unique_user(self.get_argument("parasite")):
            self.render2("create_user.html")
        if self.get_argument("password") == self.get_argument("password2"):
            hashed_password = yield executor.submit(
                bcrypt.hashpw, escape.utf8(self.get_argument("password")),
                bcrypt.gensalt())
            parasite_id = self.db.execute(
                "INSERT INTO parasite (id, email, password, username) "
                "VALUES (%s, %s, %s, %s)",
                self.get_argument("parasite"), self.get_argument("email"), hashed_password,
                self.get_argument("parasite"))
            self.set_secure_cookie("parasite", str(parasite_id), expires_days=182)
            self.redirect(self.get_argument("next", "/"))
        else:
            self.render2("create_user.html", error="incorrect password")
项目:best-ever-chat    作者:lazymeadow    | 项目源码 | 文件源码
def post(self):
        token = self.get_argument("token")
        try:
            from tornado_chat import SECRET_KEY
            serializer = URLSafeTimedSerializer(SECRET_KEY)
            parasite = serializer.loads(token, max_age=86400)  # do i really have to do 24hrs in secs?
            parasiteId = self.db.get("SELECT id, reset_token FROM parasite WHERE id = %s", parasite)
            if parasiteId is not None and self.get_argument("password") == self.get_argument(
                    "password2") and parasiteId.reset_token == token:
                hashed_password = yield executor.submit(
                    bcrypt.hashpw, tornado.escape.utf8(self.get_argument("password")),
                    bcrypt.gensalt())
                self.db.execute("UPDATE parasite SET password = %s, reset_token='' WHERE id = %s", hashed_password,
                                parasite)
                self.redirect("login?error=Password reset. Please login.")
            else:
                self.redirect("login?error=Password reset failed.")
        except:
            self.redirect("login?error=Password reset failed.")
项目:best-ever-chat    作者:lazymeadow    | 项目源码 | 文件源码
def change_user_password(self, user, password_list):
        """
        Update a user's password to the given value. Requires that the value be sent with a confirmation entry (two
        identical values)
        :param user: user with the password change
        :param password_list: list containing password and confirmation
        :return: for exiting if necessary information is not available
        """
        if user != self.username or not password_list or len(password_list) != 2 or password_list[0] != password_list[
            1]:
            return

        updating_participants = get_matching_participants(self.participants, self.current_user['id'])

        hashed_password = yield executor.submit(
            bcrypt.hashpw, tornado.escape.utf8(password_list[0]),
            bcrypt.gensalt())
        if self.current_user.password != hashed_password:
            self.http_server.db.execute("UPDATE parasite SET password = %s WHERE id = %s", hashed_password,
                                        self.current_user['id'])

        self.broadcast_from_server(updating_participants, 'PASSWORD CHANGED! I hope that\'s what you wanted.')
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
def _calc_checksum(self, secret):
        # bcrypt behavior:
        #   secret must be bytes
        #   config must be ascii bytes
        #   returns ascii bytes
        secret, ident = self._prepare_digest_args(secret)
        config = self._get_config(ident)
        if isinstance(config, unicode):
            config = config.encode("ascii")
        hash = _bcrypt.hashpw(secret, config)
        assert hash.startswith(config) and len(hash) == len(config)+31, \
            "config mismatch: %r => %r" % (config, hash)
        assert isinstance(hash, bytes)
        return hash[-31:].decode("ascii")

#-----------------------------------------------------------------------
# bcryptor backend
#-----------------------------------------------------------------------
项目:Cloud-Native-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def do_admin_login():
    users = mongo.db.users
    api_list=[]
    login_user = users.find({'username': request.form['username']})
    for i in login_user:
        api_list.append(i)
    print (api_list)
    if api_list != []:
        #print (api_list[0]['password'].decode('utf-8'), bcrypt.hashpw(request.form['password'].encode('utf-8'), api_list[0]['password']).decode('utf-8'))
        if api_list[0]['password'].decode('utf-8') == bcrypt.hashpw(request.form['password'].encode('utf-8'), api_list[0]['password']).decode('utf-8'):
            session['logged_in'] = api_list[0]['username']
            return redirect(url_for('index'))
        return 'Invalide username/password!'
    else:
        flash("Invalid Authentication")

    return 'Invalid User!'
项目:Cloud-Native-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def signup():
    if request.method=='POST':
        users = mongo.db.users
        api_list=[]
        existing_user = users.find({'$or':[{"username":request.form['username']} ,{"email":request.form['email']}]})
        for i in existing_user:
            # print (str(i))
            api_list.append(str(i))

        # print (api_list)
        if api_list == []:
            users.insert({
            "email": (request.form['email']).lower(),
            "id": random.randint(1,1000),
            "name": request.form['name'],
            "password": bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt()),
            "username": request.form['username']
            })
            session['username'] = request.form['username']
            return redirect(url_for('home'))

        return 'That user already exists'
    else :
        return render_template('signup.html')
项目:Cloud-Native-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def do_admin_login():
    users = mongo.db.users
    api_list=[]
    login_user = users.find({'username': request.form['username']})
    for i in login_user:
        api_list.append(i)
    print (api_list)
    if api_list != []:
        # print (api_list[0]['password'].decode('utf-8'), bcrypt.hashpw(request.form['password'].encode('utf-8'), api_list[0]['password']).decode('utf-8'))
        if api_list[0]['password'].decode('utf-8') == bcrypt.hashpw(request.form['password'].encode('utf-8'), api_list[0]['password']).decode('utf-8'):
            session['logged_in'] = api_list[0]['username']
            return redirect(url_for('index'))
        return 'Invalide username/password!'
    else:
        flash("Invalid Authentication")

    return 'Invalid User!'
项目:Cloud-Native-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def signup():
    if request.method=='POST':
        users = mongo.db.users
        api_list=[]
        existing_user = users.find({'$or':[{"username":request.form['username']} ,{"email":request.form['email']}]})
        for i in existing_user:
            # print (str(i))
            api_list.append(str(i))

        # print (api_list)
        if api_list == []:
            users.insert({
            "email": request.form['email'],
            "id": random.randint(1,1000),
            "name": request.form['name'],
            "password": bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt()),
            "username": request.form['username']
            })
            session['username'] = request.form['username']
            return redirect(url_for('home'))

        return 'That user already exists'
    else :
        return render_template('signup.html')
项目:Cloud-Native-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def signup():
    if request.method=='POST':
        users = mongo.db.users
        api_list=[]
        existing_user = users.find({'$or':[{"username":request.form['username']} ,{"email":request.form['email']}]})
        for i in existing_user:
            # print (str(i))
            api_list.append(str(i))

        # print (api_list)
        if api_list == []:
            users.insert({
            "email": (request.form['email']).lower(),
            "id": random.randint(1,1000),
            "name": request.form['name'],
            "password": bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt()),
            "username": request.form['username']
            })
            session['username'] = request.form['username']
            return redirect(url_for('home'))

        return 'That user already exists'
    else :
        return render_template('signup.html')
项目:Cloud-Native-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def do_admin_login():
    users = mongo.db.users
    api_list=[]
    login_user = users.find({'username': request.form['username']})
    for i in login_user:
        api_list.append(i)
    print (api_list)
    if api_list != []:
        #print (api_list[0]['password'].decode('utf-8'), bcrypt.hashpw(request.form['password'].encode('utf-8'), api_list[0]['password']).decode('utf-8'))
        if api_list[0]['password'].decode('utf-8') == bcrypt.hashpw(request.form['password'].encode('utf-8'), api_list[0]['password']).decode('utf-8'):
            session['logged_in'] = api_list[0]['username']
            return redirect(url_for('index'))
        return 'Invalide username/password!'
    else:
        flash("Invalid Authentication")

    return 'Invalid User!'
项目:Cloud-Native-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def signup():
    if request.method=='POST':
        users = mongo.db.users
        api_list=[]
        existing_user = users.find({'$or':[{"username":request.form['username']} ,{"email":request.form['email']}]})
        for i in existing_user:
            # print (str(i))
            api_list.append(str(i))

        # print (api_list)
        if api_list == []:
            users.insert({
            "email": (request.form['email']).lower(),
            "id": random.randint(1,1000),
            "name": request.form['name'],
            "password": bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt()),
            "username": request.form['username']
            })
            session['username'] = request.form['username']
            return redirect(url_for('home'))

        return 'That user already exists'
    else :
        return render_template('signup.html')
项目:Cloud-Native-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def signup():
    if request.method=='POST':
        users = mongo.db.users
        api_list=[]
        existing_user = users.find({'$or':[{"username":request.form['username']} ,{"email":request.form['email']}]})
        for i in existing_user:
            # print (str(i))
            api_list.append(str(i))

        # print (api_list)
        if api_list == []:
            users.insert({
            "email": (request.form['email']).lower(),
            "id": random.randint(1,1000),
            "name": request.form['name'],
            "password": bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt()),
            "username": request.form['username']
            })
            session['username'] = request.form['username']
            return redirect(url_for('home'))

        return 'That user already exists'
    else :
        return render_template('signup.html')
项目:TalkToMe    作者:glenjantz    | 项目源码 | 文件源码
def login(self, postData):
        status = True
        errorlist = []
        user = User.objects.filter(username = postData['username'])
        if len(postData['username']) < 1:
            errorlist.append('Must fill in Username!')
            status = False
        if len(postData['password']) < 1:
            errorlist.append('Must fill in Password!')
            status = False
        else:
            if len(user) < 1:
                errorlist.append('Username not registered!')
                status = False
        if status == False:
            return {'errors': errorlist}
        else:
            if bcrypt.hashpw(postData['password'].encode(), user[0].password.encode()) == user[0].password:
                return {'login': True}
            else:
                status = False
                errorlist.append('Password does not match username!')
                return {'errors': errorlist}
项目:enkiWS    作者:juliettef    | 项目源码 | 文件源码
def fuzz_verifier_pybcrypt(self):
        # test against py-bcrypt, if available
        from passlib.handlers.bcrypt import IDENT_2, IDENT_2A, IDENT_2X, IDENT_2Y
        from passlib.utils import to_native_str
        try:
            import bcrypt
        except ImportError:
            return
        if hasattr(bcrypt, "_ffi"):
            return
        def check_pybcrypt(secret, hash):
            "pybcrypt"
            secret = to_native_str(secret, self.fuzz_password_encoding)
            if hash.startswith(IDENT_2Y):
                hash = IDENT_2A + hash[4:]
            try:
                return bcrypt.hashpw(secret, hash) == hash
            except ValueError:
                raise ValueError("py-bcrypt rejected hash: %r" % (hash,))
        return check_pybcrypt
项目:enkiWS    作者:juliettef    | 项目源码 | 文件源码
def _calc_checksum_bcrypt(self, secret):
        # bcrypt behavior:
        #   hash must be ascii bytes
        #   secret must be bytes
        #   returns bytes
        if self.ident == IDENT_2:
            # bcrypt doesn't support $2$ hashes; but we can fake $2$ behavior
            # using the $2a$ algorithm, by repeating the password until
            # it's at least 72 chars in length.
            if secret:
                secret = repeat_string(secret, 72)
            config = self._get_config(IDENT_2A)
        else:
            config = self._get_config()
        if isinstance(config, unicode):
            config = config.encode("ascii")
        hash = _bcrypt.hashpw(secret, config)
        assert hash.startswith(config) and len(hash) == len(config)+31
        assert isinstance(hash, bytes)
        return hash[-31:].decode("ascii")
项目:Pycourses    作者:billz96    | 项目源码 | 文件源码
def register():
    username = loggedIn(session, LoggedIn)
    if username != False:
        return render_template('index.html', username=username)

    form = RegisterForm()
    if form.validate_on_submit():
        hashedPwd = hashpw(str(request.form['password']).encode('utf-8'), gensalt()) # encrypt user's password
        user = User(username=request.form['username'], password=hashedPwd) # create user
        db.session.add(user)
        db.session.commit() # save new user in User table

        new_user = User.query.filter_by(username=request.form['username']).first() # new profile
        user_profile = Profile(user_id=new_user.id, name="no-name", surname="no-surname", avatar="saitama-batman.jpg", description="no-description", skills="no-skills,")
        db.session.add(user_profile)
        db.session.commit() # save new profile in Profile table

        return render_template('registration_success.html', username=request.form['username'])
    return render_template('register.html', form=form)
项目:baroness    作者:ulrichknecht    | 项目源码 | 文件源码
def manage_users_add():
    if request.method == 'POST':
        u = User()
        error = None
        u.name = request.form['username'].lower()
        if u.name is None:
            error = "Username not unique!"

        if request.form['password1'] == request.form['password2']:
            #u.password = request.form['password1']
            u.password = bcrypt.hashpw(request.form['password1'], bcrypt.gensalt())
        else:
            error = "Passwords do not match!"
        u.longname = request.form['longname']
        u.email = request.form['email']
        u.rfid_id = request.form['rfid_id']

        if error is None:
            add_user(u)
            return render_template('manage_users_add.html', success="User created!", user=get_user_by_name(session.get('name')));

        return render_template('manage_users_add.html', error=error, user=get_user_by_name(session.get('name')))
    return render_template('manage_users_add.html', user=get_user_by_name(session.get('name')))
项目:python-flask-security    作者:weinbergdavid    | 项目源码 | 文件源码
def fuzz_verifier_pybcrypt(self):
        # test against py-bcrypt, if available
        from passlib.handlers.bcrypt import IDENT_2, IDENT_2A, IDENT_2B, IDENT_2X, IDENT_2Y, _detect_pybcrypt
        from passlib.utils import to_native_str
        try:
            import bcrypt
        except ImportError:
            return
        if not _detect_pybcrypt():
            return
        def check_pybcrypt(secret, hash):
            """pybcrypt"""
            secret = to_native_str(secret, self.fuzz_password_encoding)
            if len(secret) > 200:  # vulnerable to wraparound bug
                secret = secret[:200]
            if hash.startswith((IDENT_2B, IDENT_2Y)):
                hash = IDENT_2A + hash[4:]
            try:
                return bcrypt.hashpw(secret, hash) == hash
            except ValueError:
                raise ValueError("py-bcrypt rejected hash: %r" % (hash,))
        return check_pybcrypt
项目:PhoenixNow    作者:ECGHelloWorld    | 项目源码 | 文件源码
def reset_password(token):
  form = ResetForm()

  tokenemail = confirm_token(token)
  if tokenemail is False:
    flash('The confirmation link is invalid or has expired.', 'danger')
    return redirect(url_for('regular.home'))

  user = User.query.filter_by(email = tokenemail).first()
  if user:
    if request.method == 'POST':
      if form.validate_on_submit():
        user.pw_hash = bcrypt.hashpw(form.password.data.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
        db.session.commit()
        login_user(user,remember=True)
        flash('Your password has been reset.')
        return redirect(url_for('regular.home'))
      else:
        return render_template('reset.html', form=form, token=token)
    elif request.method == 'GET':
      return render_template('reset.html', form=form, token=token)
  else:
    flash('The confirmation link is invalid or has expired.', 'danger')
项目:planty    作者:agnaite    | 项目源码 | 文件源码
def process_login():
    """Processes user input and either logs user in if input is in database"""

    # gets the user input from the username field and looks it up in the database
    username = request.form.get('username')
    user = User.query.filter_by(username=username).first()

    # if username entered exists in db, gets the password entered and compares
    # it to the one in the database
    if user:
        # if password is correct, adds user to the current session and redirects to home page
        if bcrypt.hashpw(request.form.get('password').encode('utf-8'), user.password.encode('utf-8')).decode() == user.password:
            session['logged_in'] = user.user_id
            print 'logged in'
            return jsonify(session)
        # if password is incorrect, redirects to login page
        else:
            return 'error'
    # if username is not in the database, redirects to the registration form
    else:
        return 'error'
项目:planty    作者:agnaite    | 项目源码 | 文件源码
def update_user():
    """Saves updated user info."""

    user_id = request.form.get('id')
    user_to_update = User.query.get(int(user_id))

    if bcrypt.hashpw(request.form.get('password').encode('utf-8'), user_to_update.password.encode('utf-8')).decode() == user_to_update.password:
        if request.form.get('email'):
            user_to_update.email = request.form.get('email')
        if request.form.get('phone'):
            user_to_update.phone = request.form.get('phone')
    else:
        return "bad password"

    db.session.commit()

    return "ok"


# PlantUser Routes *********************************
项目:IotCenter    作者:panjanek    | 项目源码 | 文件源码
def post(self):
        username = tornado.escape.xhtml_escape(self.get_argument("username", ""))
        password = tornado.escape.xhtml_escape(self.get_argument("password", "")).encode('utf-8')   
        returnUrl = self.get_argument("returnUrl", "/")
        self.logger.info("login request with username={0} from ip={1}".format(username, self.request.remote_ip))
        if username == "admin" and bcrypt.hashpw(password, self.adminPasswordHash) == self.adminPasswordHash:
            self.set_secure_cookie("user", username, expires_days=1)
            self.redirect(returnUrl)
        else:
            self.logger.warning("Invalid login/password request with username={0} from ip={1}".format(username, self.request.remote_ip))
            self.render("views/login.html", errormsg="Invalid username or password.", returnUrl=returnUrl)
项目:python-seminar-4    作者:babjo    | 项目源码 | 文件源码
def hash_password(password):
    print(password, bcrypt.hashpw(password, bcrypt.gensalt()))
项目:picoCTF    作者:picoCTF    | 项目源码 | 文件源码
def confirm_password(attempt, password_hash):
    """
    Verifies the password attempt

    Args:
        attempt: the password attempt
        password_hash: the real password pash
    """
    return bcrypt.hashpw(attempt.encode('utf-8'), password_hash) == password_hash
项目:picoCTF    作者:picoCTF    | 项目源码 | 文件源码
def hash_password(password):
    """
    Hash plaintext password.

    Args:
        password: plaintext password
    Returns:
        Secure hash of password.
    """

    return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(8))