• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python security.check_password_hash函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中werkzeug.security.check_password_hash函数的典型用法代码示例。如果您正苦于以下问题:Python check_password_hash函数的具体用法?Python check_password_hash怎么用?Python check_password_hash使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了check_password_hash函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: login

def login(page = 1):
    form = LoginForm()
    user = g.user
    if user is not None and user.is_authenticated():
        return redirect(url_for('index'))
    if form.validate_on_submit():
    	#checks if form is left empty
    	if form.username.data == None or form.password.data == None:
    		return redirect(url_for('index'))
    	#allows user to login with email
    	if form.username.data.find('@') != -1:
    		username = form.username.data.split('@')[0]
    	else:
    		username = form.username.data
    	user = models.User.query.filter_by(username=username).first()
    	#if username cannot be found
    	if user == None:
			flash('User not found.')
			return redirect(url_for('index'))
		#checks if passwords match
    	if check_password_hash(user.password,form.password.data):
    		login_user(user)
    if form.password.data and form.username.data and check_password_hash(user.password,form.password.data):		
    	return render_template('yourposts.html', 
    		title = user.username,
    		user = user,
    		posts = user.posts.order_by("timestamp desc").paginate(page, POSTS_PER_PAGE, False),
			)
    else:
    	flash('Incorrect password')
    	return render_template('index.html',
    		loginform = form,
    		registerform = RegisterForm()
    		)
开发者ID:jbrambleDC,项目名称:flitterFlask,代码行数:34,代码来源:views.py


示例2: validate

    def validate(self):
        ''' validate the form '''
        rv = Form.validate(self)
        if not rv:
            return False

        if self.who.data == "shipper":
            user = Shipper.query.filter_by(
                email=self.email.data
                ).first()
            if user is None:
                self.email.errors.append(u"This email not registered")
                return False
            if not check_password_hash(
                user.passwd,
                self.passwd.data
                ):
                self.passwd.errors.append(u"Username and password don't match")
                return False
        else:
            user = Deliverer.query.filter_by(
                email=self.email.data
                ).first()
            if user is None:
                self.email.errors.append(u"This email not registered")
                return False
            if not check_password_hash(
                user.passwd,
                self.passwd.data
                ):
                self.passwd.errors.append(u"Username and password don't match")
                return False

        self.user = user
        return True
开发者ID:Lan-Yang,项目名称:WeDeliver,代码行数:35,代码来源:forms.py


示例3: login

def login():
    if current_user.is_authenticated():
	return redirect("/index")
    form = LoginForm()
    if form.validate_on_submit():
    	username=form.username.data
	password=form.password.data
	remember=bool(form.rememberme.data)
	c=sqlite3.connect('test.db')
	passcheck=False
	pa=c.execute("SELECT password,email,confirm from users where username=(?)",[username])
	for x in pa:
               	passcheck=check_password_hash(x[0],password)
               	email=x[1]
               	password=x[0]
               	confirm=x[2]
	if not passcheck:
		pa=c.execute("SELECT password,username,confirm from users where email=(?)",[username])
		for x in pa:
			passcheck=check_password_hash(x[0],password)
			email=username
			username=x[1]
			password=x[0]
			confirm=x[2]
	ruser=None
	if passcheck:
		ruser=User(username,password,email,confirm)
	if ruser is None:
		return render_template('login.html',title='sign in error',form=form,error='incorrect username or password')
	login_user(ruser,remember)
	return redirect(request.args.get('next') or '/index')
    return render_template('login.html', 
                           title='Sign In',
                           form=form)
    return render_template('login.html',title='sign in',form=form)
开发者ID:nithintech,项目名称:blog-app-using-flask,代码行数:35,代码来源:views.py


示例4: verify_password

 def verify_password(self, password):
     if not AccountPolicy.LOCKOUT_POLICY_ENABLED:
         if check_password_hash(self.password_hash, password):
             return True
         else:
             LogEvent.incorrect_password(self)
             return False
     if self.locked or not self.enabled:
         if not check_password_hash(self.password_hash, password):
             LogEvent.incorrect_password(self)
         if self.locked:
             LogEvent.login_attempt_while_account_locked(self)
         if not self.enabled:
             LogEvent.login_attempt_while_account_disabled(self)
         return False
     if check_password_hash(self.password_hash, password):
         self.last_failed_login_attempt = None
         self.failed_login_attempts = 0
         return True
     LogEvent.incorrect_password(self)
     if self.last_failed_login_attempt:
         if ((datetime.utcnow() - self.last_failed_login_attempt) >
                 AccountPolicy.RESET_THRESHOLD_AFTER):
             self.failed_login_attempts = 0
     self.last_failed_login_attempt = datetime.utcnow()
     self.failed_login_attempts += 1
     if self.failed_login_attempts == AccountPolicy.LOCKOUT_THRESHOLD:
         self.locked = True
         LogEvent.account_locked_by_failed_logins(self)
     return False
开发者ID:richgieg,项目名称:flask-now,代码行数:30,代码来源:models.py


示例5: test_check_password

 def test_check_password(self):
     """Ensure given password is correct after un-hashing"""
     author = UserAccount.query.filter_by(email='[email protected]').first()
     self.assertFalse(author.verify_password('admin'))
     self.assertFalse(author.verify_password('another_admin'))
     self.assertTrue(check_password_hash(author.get_password, "password"))
     self.assertFalse(check_password_hash(author.get_password, "foobar"))
开发者ID:BrianLusina,项目名称:Arco,代码行数:7,代码来源:test_models.py


示例6: login

def login():
	error = None
	if not session.get('logged_in'):
		if request.method == 'POST':
			if request.form['username'] == 'admin':
				if check_password_hash(app.config['adminPassword'], request.form['password']):
					session['logged_in'] = True
					log("admin logged in" + time.time())
					return redirect(url_for('admin'))
				else:
					flash('Incorrect Username/password')
					return render_template('login.html')
			else:
				try:
					hashed_password = ''.join(select('SELECT Password FROM Users WHERE Username=\'%s\'' % request.form['username'])[0])
					if check_password_hash(hashed_password, request.form['password']):
						session['logged_in'] = True
						log(request.form['username']+" logged in "+str(time.time()))
						return redirect(url_for('addtrans'))
					else:
						flash(hashed_password)
						return render_template('login.html')
				except:
					flash('no such username')
					return render_template('login.html')
		return render_template('login.html')
	return redirect(url_for('addtrans'))
开发者ID:fhebert-perkins,项目名称:ResourceTracker,代码行数:27,代码来源:app.py


示例7: authenticate

    def authenticate(cls, login, password):
        """A classmethod for authenticating users.
        It returns the user object if the user/password combination is ok.
        If the user has entered too often a wrong password, he will be locked
        out of his account for a specified time.

        :param login: This can be either a username or a email address.
        :param password: The password that is connected to username and email.
        """
        user = cls.query.filter(db.or_(User.username == login,
                                       User.email == login)).first()

        if user is not None:
            if user.check_password(password):
                # reset them after a successful login attempt
                user.login_attempts = 0
                user.save()
                return user

            # user exists, wrong password
            # never had a bad login before
            if user.login_attempts is None:
                user.login_attempts = 1
            else:
                user.login_attempts += 1
            user.last_failed_login = time_utcnow()
            user.save()

        # protection against account enumeration timing attacks
        check_password_hash("dummy password", password)

        raise AuthenticationError
开发者ID:xiaoyu0,项目名称:flaskbb,代码行数:32,代码来源:models.py


示例8: checkAuthenticationCredentials

def checkAuthenticationCredentials(email, passw):
    """Validates user access credentials"""
    user = userData.getUserByEmail(email)
    print "---------------->", user.password
    print "---------------->", check_password_hash( user.password, passw )
    if user and check_password_hash( user.password, passw ):
        return user
    return False
开发者ID:MarcoPires,项目名称:restaurantApp,代码行数:8,代码来源:access_control.py


示例9: test_edit_user

 def test_edit_user(self):
     user = models.User.create('marv', 'pass')
     assert check_password_hash(user.password, 'pass')
     models.User.edit(user.id, username='marv2', password='pass2')
     user = models.User.get(user.id)
     assert not check_password_hash(user.password, 'pass')
     assert check_password_hash(user.password, 'pass2'), user.password
     assert user.username == 'marv2'
开发者ID:spaceexperiment,项目名称:forum-app,代码行数:8,代码来源:test_models.py


示例10: test_password_hash

    def test_password_hash(self):
        """Test password hasher."""
        from werkzeug.security import check_password_hash,\
            generate_password_hash
        p = 'passwd'
        h = generate_password_hash(p)

        self.assertTrue(check_password_hash(h, p))
        self.assertFalse(check_password_hash(h, p + '1'))
开发者ID:coorasse,项目名称:vilfredo-core,代码行数:9,代码来源:_models.py


示例11: test_password_hashing

def test_password_hashing():
    hash0 = generate_password_hash('default')
    assert check_password_hash(hash0, 'default')
    assert hash0.startswith('pbkdf2:sha256:50000$')

    hash1 = generate_password_hash('default', 'sha1')
    hash2 = generate_password_hash(u'default', method='sha1')
    assert hash1 != hash2
    assert check_password_hash(hash1, 'default')
    assert check_password_hash(hash2, 'default')
    assert hash1.startswith('sha1$')
    assert hash2.startswith('sha1$')

    with pytest.raises(ValueError):
        check_password_hash('$made$up$', 'default')

    with pytest.raises(ValueError):
        generate_password_hash('default', 'sha1', salt_length=0)

    fakehash = generate_password_hash('default', method='plain')
    assert fakehash == 'plain$$default'
    assert check_password_hash(fakehash, 'default')

    mhash = generate_password_hash(u'default', method='md5')
    assert mhash.startswith('md5$')
    assert check_password_hash(mhash, 'default')

    legacy = 'md5$$c21f969b5f03d33d43e04f8f136e7682'
    assert check_password_hash(legacy, 'default')

    legacy = u'md5$$c21f969b5f03d33d43e04f8f136e7682'
    assert check_password_hash(legacy, 'default')
开发者ID:brunoais,项目名称:werkzeug,代码行数:32,代码来源:test_security.py


示例12: login

    def login(username, password):
        user = UserQueries.get_by_login(username)

        if user is not None:  # cool, we found a user.
            if check_password_hash(user.password, password):  # does the password match.
                login_user(user)
                return True
        else:
            check_password_hash(password, password)  # Say no timing attacks.

        return False
开发者ID:jacqueswww,项目名称:features,代码行数:11,代码来源:user_services.py


示例13: check_login

def check_login(username, password):
    user = get_user(username)
    print "user: " + str(user)
    if user == None:
        return False
    print "password to be checked: " + password
    print "current password hash: " + user['password']
    print check_password_hash(user['password'], password)
    if check_password_hash(user['password'], password):
        return True
    return False
开发者ID:zhoubw,项目名称:Bizcuits,代码行数:11,代码来源:database.py


示例14: check_login

def check_login(user_name, password):
    print user_name + " : " + password
    user = User.query.filter(User.user_name == user_name).first()
    if not user:
	return None
    print check_password_hash(user.password, password)
    if check_password_hash(user.password, password):
        print "logged"
        return user
        
    return None
开发者ID:thabaptiser,项目名称:karibu,代码行数:11,代码来源:karibu.py


示例15: testSetPassword

    def testSetPassword(self):

        '''
        Test password hashing.
        '''

        user = User('username', 'password', True)

        # Check the hash comparer.
        correct = check_password_hash(user.password_hash, 'password')
        self.assertTrue(correct)
        incorrect = check_password_hash(user.password_hash, 'wrong')
        self.assertFalse(incorrect)
开发者ID:davidmcclure,项目名称:eh_old_2,代码行数:13,代码来源:_testUserModel.py


示例16: checkPass

 def checkPass(self, password, rdb):
     ''' Check if the password supplied is valid '''
     results = r.table('users').get(self.uid).run(rdb)
     data = results
     if not data:
         return "No data found"
     else:
        if check_password_hash(data['password'], password):
           self.setPass(password, rdb)
           return True
        else:
           password = self.saltPass(password)
           return check_password_hash(data['password'], password)
开发者ID:tjcunliffe,项目名称:runbook,代码行数:13,代码来源:users.py


示例17: login_view

 def login_view(self):
     form = LoginForm(request.form)
     if helpers.validate_form_on_submit(form):
         user = form.get_user()
         if user is None:
             flash('用户名不存在!')
         elif not check_password_hash(user.password, form.password.data):
             flash('密码错误!')
         elif user is not None and check_password_hash(user.password, form.password.data):
             login_user(user)
     if current_user.is_authenticated:
         return redirect(url_for('admin.index'))
     self._template_args['form'] = form
     #self._template_args['link'] = link
     return super(MyAdminIndexView, self).index()
开发者ID:qxbug,项目名称:zsky,代码行数:15,代码来源:manage.py


示例18: authenticate

def authenticate(project_id=None):
    """Authentication form"""
    form = AuthenticationForm()
    # Try to get project_id from token first
    token = request.args.get('token')
    if token:
        project_id = Project.verify_token(token, token_type='non_timed_token')
        token_auth = True
    else:
        if not form.id.data and request.args.get('project_id'):
            form.id.data = request.args['project_id']
        project_id = form.id.data
        token_auth = False
    if project_id is None:
        # User doesn't provide project identifier or a valid token
        # return to authenticate form
        msg = _("You either provided a bad token or no project identifier.")
        form.errors["id"] = [msg]
        return render_template("authenticate.html", form=form)

    project = Project.query.get(project_id)
    if not project:
        # If the user try to connect to an unexisting project, we will
        # propose him a link to the creation form.
        return render_template("authenticate.html", form=form, create_project=project_id)

    # if credentials are already in session, redirect
    if session.get(project_id):
        setattr(g, 'project', project)
        return redirect(url_for(".list_bills"))

    # else do form authentication or token authentication
    is_post_auth = request.method == "POST" and form.validate()
    if is_post_auth and check_password_hash(project.password, form.password.data) or token_auth:
        # maintain a list of visited projects
        if "projects" not in session:
            session["projects"] = []
        # add the project on the top of the list
        session["projects"].insert(0, (project_id, project.name))
        session[project_id] = True
        session.update()
        setattr(g, 'project', project)
        return redirect(url_for(".list_bills"))
    if is_post_auth and not check_password_hash(project.password, form.password.data):
        msg = _("This private code is not the right one")
        form.errors['password'] = [msg]

    return render_template("authenticate.html", form=form)
开发者ID:Glandos,项目名称:ihatemoney,代码行数:48,代码来源:web.py


示例19: login_screen_submit

def login_screen_submit():
    """handle the login form submit"""
    # try to find user by username
    user_details = site_user.get_by_username({
        'username': request.form.get('username')}).get()

    # not found so lets bail to the login screen
    if not user_details:
        flash('Failed to login with that username and password, please retry.')
        return redirect('/login')

    # now lets verify the users password, and bail if its wrong
    pw_hash = generate_password_hash(request.form.get('password'))
    if check_password_hash(pw_hash, user_details.get('password')):
        flash('Failed to login with that username and password, please retry.')
        return redirect('/login')

    #login user and redirect to profile
    login_user(
        User(user_details.get('user_id'))
    )

    flash('You have successfully logged in !')
    site_user.update_last_login().execute({'id': user_details.get('user_id')})

    # logged in but no E-Mail so lets ask the user for there email.
    if not user_details.get('email'):
        return redirect('/profile/change_email')

    return redirect('/profile')
开发者ID:maidstone-hackspace,项目名称:maidstone-hackspace,代码行数:30,代码来源:login_pages.py


示例20: load_user_from_request

def load_user_from_request(request, session=None):
    auth_value = request.headers.get('Authorization')

    if not auth_value:
        return

    # Login using api key
    if auth_value.startswith('Token'):
        try:
            token = auth_value.replace('Token ', '', 1)
            return session.query(User).filter(User.token == token).first()
        except (TypeError, ValueError):
            pass

    # Login using basic auth
    if auth_value.startswith('Basic'):
        try:
            credentials = base64.b64decode(auth_value.replace('Basic ', '', 1))
            username, password = credentials.split(':')
            user = session.query(User).filter(User.name == username).first()
            if user and user.password and check_password_hash(user.password, password):
                return user
            else:
                return None
        except (TypeError, ValueError):
            pass
开发者ID:awesome-python,项目名称:Flexget,代码行数:26,代码来源:authentication.py



注:本文中的werkzeug.security.check_password_hash函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python security.gen_salt函数代码示例发布时间:2022-05-26
下一篇:
Python routing.Rule类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap