本文整理汇总了Python中passlib.hash.sha256_crypt.verify方法的典型用法代码示例。如果您正苦于以下问题:Python sha256_crypt.verify方法的具体用法?Python sha256_crypt.verify怎么用?Python sha256_crypt.verify使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类passlib.hash.sha256_crypt
的用法示例。
在下文中一共展示了sha256_crypt.verify方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: authenticate_user
# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def authenticate_user(username, password):
""" Authenticate a user """
try:
user = User.query.filter_by(username=username).first()
except OperationalError:
db.create_all()
user = User.query.filter_by(username=username).first()
authenticated = False
if user:
authenticated = sha256_crypt.verify(password, user.password)
else:
time.sleep(1)
logger.info("Authentication Error: User not found in DB: %s", username)
return False
if authenticated:
logger.debug("Successfully Authenticated user: %s", username)
else:
logger.info("Authentication Failed: %s", username)
return authenticated
示例2: setUp
# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def setUp(self):
super(_ExtensionTest, self).setUp()
self.require_TEST_MODE("default")
if not DJANGO_VERSION:
raise self.skipTest("Django not installed")
elif not has_min_django:
raise self.skipTest("Django version too old")
# reset to baseline, and verify it worked
self.unload_extension()
# and do the same when the test exits
self.addCleanup(self.unload_extension)
#=============================================================================
# extension tests
#=============================================================================
示例3: authenticate_user
# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def authenticate_user(username, passwd):
""" Authenticate a user """
user = User.query.filter_by(username=username).first()
authenticated = False
if user:
authenticated = sha256_crypt.verify(passwd, user.password)
else:
time.sleep(1)
logger.info("Authentication Error: User not found in DB: %s", username)
return False
if authenticated:
logger.debug("Successfully Authenticated user: %s", username)
else:
logger.info("Authentication Failed: %s", username)
return authenticated
示例4: login
# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def login(username, password):
user = User.objects(username=username).first()
if user is None:
raise AuthenticationError("Invalid user")
elif not sha256_crypt.verify(password, user.sha256_hash):
raise AuthenticationError("Invalid password")
else:
return user.login()
示例5: post
# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def post(self):
getusername = self.get_argument("username")
getpassword = self.get_argument("password")
user_data = self.database.get_user_data(getusername)
if user_data and user_data["password"] and crypt.verify(getpassword, user_data["password"]):
self.set_secure_cookie("user", self.get_argument("username"))
self.redirect(self.get_argument("next",
self.reverse_url("main")))
else:
self.redirect(self.reverse_url("login"))
示例6: verify
# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def verify(txt, hash):
return sha256_crypt.verify(txt, hash)
示例7: place_login_cookie
# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def place_login_cookie(pw):
if verify(pw, ADMIN_PW):
session['pwhash'] = _xor_encrypt(ADMIN_PW, SECRET_KEY)
return True
else:
return False
示例8: check_credentials
# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def check_credentials(db_engine, username, password):
async with db_engine.acquire() as conn:
where = sa.and_(db.users.c.login == username,
sa.not_(db.users.c.disabled))
query = db.users.select().where(where)
ret = await conn.execute(query)
user = await ret.fetchone()
if user is not None:
hashed = user[2]
return sha256_crypt.verify(password, hashed)
return False
示例9: _iter_patch_candidates
# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def _iter_patch_candidates(cls):
"""helper to scan for monkeypatches.
returns tuple containing:
* object (module or class)
* attribute of object
* value of attribute
* whether it should or should not be patched
"""
# XXX: this and assert_unpatched() could probably be refactored to use
# the PatchManager class to do the heavy lifting.
from django.contrib.auth import models, hashers
user_attrs = ["check_password", "set_password"]
model_attrs = ["check_password", "make_password"]
hasher_attrs = ["check_password", "make_password", "get_hasher", "identify_hasher",
"get_hashers"]
objs = [(models, model_attrs),
(models.User, user_attrs),
(hashers, hasher_attrs),
]
for obj, patched in objs:
for attr in dir(obj):
if attr.startswith("_"):
continue
value = obj.__dict__.get(attr, UNSET) # can't use getattr() due to GAE
if value is UNSET and attr not in patched:
continue
value = get_method_function(value)
source = getattr(value, "__module__", None)
if source:
yield obj, attr, source, (attr in patched)
#===================================================================
# verify current patch state
#===================================================================
示例10: assert_patched
# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def assert_patched(self, context=None):
"""helper to ensure django HAS been patched, and is using specified config"""
# make sure we're currently patched
mod = sys.modules.get("passlib.ext.django.models")
self.assertTrue(mod and mod.adapter.patched, "patch should have been enabled")
# make sure only the expected objects have been patched
for obj, attr, source, patched in self._iter_patch_candidates():
if patched:
self.assertTrue(source == "passlib.ext.django.utils",
"obj=%r attr=%r should have been patched: %r" %
(obj, attr, source))
else:
self.assertFalse(source.startswith("passlib."),
"obj=%r attr=%r should not have been patched: %r" %
(obj, attr, source))
# check context matches
if context is not None:
context = CryptContext._norm_source(context)
self.assertEqual(mod.password_context.to_dict(resolve=True),
context.to_dict(resolve=True))
#===================================================================
# load / unload the extension (and verify it worked)
#===================================================================
示例11: test_01_overwrite_detection
# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def test_01_overwrite_detection(self):
"""test detection of foreign monkeypatching"""
# NOTE: this sets things up, and spot checks two methods,
# this should be enough to verify patch manager is working.
# TODO: test unpatch behavior honors flag.
# configure plugin to use sample context
config = "[passlib]\nschemes=des_crypt\n"
self.load_extension(PASSLIB_CONFIG=config)
# setup helpers
import django.contrib.auth.models as models
from passlib.ext.django.models import adapter
def dummy():
pass
# mess with User.set_password, make sure it's detected
orig = models.User.set_password
models.User.set_password = dummy
with self.assertWarningList("another library has patched.*User\.set_password"):
adapter._manager.check_all()
models.User.set_password = orig
# mess with models.check_password, make sure it's detected
orig = models.check_password
models.check_password = dummy
with self.assertWarningList("another library has patched.*models:check_password"):
adapter._manager.check_all()
models.check_password = orig
示例12: test_02_handler_wrapper
# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def test_02_handler_wrapper(self):
"""test Hasher-compatible handler wrappers"""
from django.contrib.auth import hashers
passlib_to_django = DjangoTranslator().passlib_to_django
# should return native django hasher if available
if DJANGO_VERSION > (1,10):
self.assertRaises(ValueError, passlib_to_django, "hex_md5")
else:
hasher = passlib_to_django("hex_md5")
self.assertIsInstance(hasher, hashers.UnsaltedMD5PasswordHasher)
hasher = passlib_to_django("django_bcrypt")
self.assertIsInstance(hasher, hashers.BCryptPasswordHasher)
# otherwise should return wrapper
from passlib.hash import sha256_crypt
hasher = passlib_to_django("sha256_crypt")
self.assertEqual(hasher.algorithm, "passlib_sha256_crypt")
# and wrapper should return correct hash
encoded = hasher.encode("stub")
self.assertTrue(sha256_crypt.verify("stub", encoded))
self.assertTrue(hasher.verify("stub", encoded))
self.assertFalse(hasher.verify("xxxx", encoded))
# test wrapper accepts options
encoded = hasher.encode("stub", "abcd"*4, rounds=1234)
self.assertEqual(encoded, "$5$rounds=1234$abcdabcdabcdabcd$"
"v2RWkZQzctPdejyRqmmTDQpZN6wTh7.RUy9zF2LftT6")
self.assertEqual(hasher.safe_summary(encoded),
{'algorithm': 'sha256_crypt',
'salt': u('abcdab**********'),
'rounds': 1234,
'hash': u('v2RWkZ*************************************'),
})
#===================================================================
# PASSLIB_CONFIG settings
#===================================================================
示例13: login
# 需要导入模块: from passlib.hash import sha256_crypt [as 别名]
# 或者: from passlib.hash.sha256_crypt import verify [as 别名]
def login():
if request.method == 'POST':
# Get Form Fields
username = request.form['username']
password_candidate = request.form['password']
# Create cursor
cur = mysql.connection.cursor()
# Get user by username
result = cur.execute("SELECT * FROM users WHERE username = %s", [username])
if result > 0:
# Get stored hash
data = cur.fetchone()
password = data['password']
# Compare Passwords
if sha256_crypt.verify(password_candidate, password):
# Passed
session['logged_in'] = True
session['username'] = username
flash('You are now logged in', 'success')
return redirect(url_for('dashboard'))
else:
error = 'Invalid login'
return render_template('login.html', error=error)
# Close connection
cur.close()
else:
error = 'Username not found'
return render_template('login.html', error=error)
return render_template('login.html')
# Check if user logged in