本文整理匯總了Python中zxcvbn.zxcvbn方法的典型用法代碼示例。如果您正苦於以下問題:Python zxcvbn.zxcvbn方法的具體用法?Python zxcvbn.zxcvbn怎麽用?Python zxcvbn.zxcvbn使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類zxcvbn
的用法示例。
在下文中一共展示了zxcvbn.zxcvbn方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: zxcvbn
# 需要導入模塊: import zxcvbn [as 別名]
# 或者: from zxcvbn import zxcvbn [as 別名]
def zxcvbn(self):
"""Password strength estimaton usuing Dropbox' zxcvbn."""
if not ZXCVBN:
self.msg.warning("python3-zxcvbn not present, skipping check")
return []
weak = []
for path, entry in self.data.items():
self.msg.verbose("Checking %s" % path)
if entry.get('password', '') == '':
continue
password = entry['password']
user_input = list(entry.values()) + path.split(os.sep)
if password in user_input:
user_input.remove(password)
results = zxcvbn(password, user_inputs=user_input)
if results['score'] <= 2:
weak.append((path, password, results))
return weak
示例2: check_password_strength
# 需要導入模塊: import zxcvbn [as 別名]
# 或者: from zxcvbn import zxcvbn [as 別名]
def check_password_strength(password: str) -> bool:
"""
Returns True if the password is strong enough,
False otherwise.
"""
if len(password) < settings.PASSWORD_MIN_LENGTH:
return False
if password == '':
# zxcvbn throws an exception when passed the empty string, so
# we need a special case for the empty string password here.
return False
if int(zxcvbn(password)['guesses']) < settings.PASSWORD_MIN_GUESSES:
return False
return True
示例3: score_password_strength
# 需要導入模塊: import zxcvbn [as 別名]
# 或者: from zxcvbn import zxcvbn [as 別名]
def score_password_strength(password: str) -> int:
return zxcvbn(password=password)['score']
示例4: validate
# 需要導入模塊: import zxcvbn [as 別名]
# 或者: from zxcvbn import zxcvbn [as 別名]
def validate(self, password, user=None):
results = zxcvbn(password, user_inputs=[user])
# score to the password, from 0 (terrible) to 4 (great)
if results['score'] < 3:
str = 'This password is not complex enough.'
if results['feedback']['warning']:
str += f"\nwarning: {results['feedback']['warning']}"
raise ValidationError(_(str), code='password_not_complex')
示例5: get_password_strength
# 需要導入模塊: import zxcvbn [as 別名]
# 或者: from zxcvbn import zxcvbn [as 別名]
def get_password_strength(password):
if len(password) < 8:
return 0
result = zxcvbn(password)
return result["score"] + 1
示例6: add_user
# 需要導入模塊: import zxcvbn [as 別名]
# 或者: from zxcvbn import zxcvbn [as 別名]
def add_user():
"""
Create a new user.
Notes
-----
Expects json of the form {"username":<username>, "password":<password>, "is_admin":<bool>}.
Passwords will be tested for strength, and usernames must be unique.
Returns the new user's id and group_id.
"""
json = request.get_json()
try:
if zxcvbn(json["password"])["score"] > 3:
user = User(**json)
else:
raise InvalidUsage(
"Password not complex enough.", payload={"bad_field": "password"}
)
except (KeyError, IndexError):
raise InvalidUsage(
"Password must be provided.", payload={"bad_field": "password"}
)
if User.query.filter(User.username == json["username"]).first() is not None:
raise InvalidUsage(
"Username already exists.", payload={"bad_field": "username"}
)
else:
user_group = Group(name=user.username, user_group=True)
user.groups.append(user_group)
db.session.add(user)
db.session.add(user_group)
db.session.commit()
return jsonify({"id": user.id, "group_id": user_group.id})
示例7: set_password
# 需要導入模塊: import zxcvbn [as 別名]
# 或者: from zxcvbn import zxcvbn [as 別名]
def set_password():
"""
Set a new password for the logged in user..
Notes
-----
Expects json containing 'password' and 'newPassword' keys.
Checks the password is the same as the existing one and that
the new password is strong.
"""
edits = request.get_json()
current_app.logger.debug("User tried to change password.")
try:
old_pass = edits["password"]
except KeyError:
raise InvalidUsage("Missing old password.", payload={"bad_field": "password"})
try:
new_pass = edits["newPassword"]
except KeyError:
raise InvalidUsage(
"Missing new password.", payload={"bad_field": "newPassword"}
)
if current_user.is_correct_password(old_pass):
if len(new_pass) == 0 or zxcvbn(new_pass)["score"] < 4:
raise InvalidUsage(
"Password not complex enough.", payload={"bad_field": "newPassword"}
)
current_user.password = new_pass
db.session.add(current_user)
db.session.commit()
current_app.logger.debug("User password changed.")
return jsonify({}), 200
else:
raise InvalidUsage("Password incorrect.", payload={"bad_field": "password"})
示例8: password_complexity_validator
# 需要導入模塊: import zxcvbn [as 別名]
# 或者: from zxcvbn import zxcvbn [as 別名]
def password_complexity_validator(password, is_register, **kwargs):
""" Test password for complexity.
Currently just supports 'zxcvbn'.
:param password: Plain text password to check
:param is_register: if True then kwargs are arbitrary additional info. (e.g.
info from a registration form). If False, must be a SINGLE key "user" that
corresponds to the current_user. All string values will be extracted and
sent to the complexity checker.
:param kwargs:
:return: ``None`` if password is complex enough, a list of error/suggestions if not.
Be aware that zxcvbn does not (easily) provide a way to localize messages.
.. versionadded:: 3.4.0
"""
if config_value("PASSWORD_COMPLEXITY_CHECKER") == "zxcvbn":
import zxcvbn
user_info = []
if not is_register:
for v in kwargs["user"].__dict__.values():
if v and isinstance(v, str):
user_info.append(v)
else:
# This is usually all register form values that are in the user_model
if kwargs:
user_info = kwargs.values()
results = zxcvbn.zxcvbn(password, user_inputs=user_info)
if results["score"] > 2:
# Good or Strong
return None
# Should we return suggestions? Default forms don't really know what to do.
if results["feedback"]["warning"]:
# Note that these come from zxcvbn and
# aren't localizable via Flask-Security
return [results["feedback"]["warning"]]
return [get_message("PASSWORD_TOO_SIMPLE")[0]]
else:
return None
示例9: main
# 需要導入模塊: import zxcvbn [as 別名]
# 或者: from zxcvbn import zxcvbn [as 別名]
def main(argv):
verbose = False
tests_file = ""
try:
tests_file = argv[0]
opts, args = getopt.getopt(argv[1:],"v")
except getopt.GetoptError:
print (""""test_compatibility <path/to/tests.json> [options]
options:
-v: verbose""")
for opt, arg in opts:
if opt == '-v':
verbose = True
with open(tests_file) as json_data:
d = json.load(json_data)
number_of_passwords = len(d)
scores_collision = 0
guesses_collision = 0
refresh_rate = number_of_passwords/100
i = 0
for js_zxcvbn_score in d:
if i%refresh_rate== 0:
update_console_status(i*100/number_of_passwords)
i += 1
py_zxcvbn_scroe = dict()
py_zxcvbn_scroe_full = zxcvbn(js_zxcvbn_score['password'])
py_zxcvbn_scroe["password"] = py_zxcvbn_scroe_full["password"]
py_zxcvbn_scroe["guesses"] = py_zxcvbn_scroe_full["guesses"]
py_zxcvbn_scroe["score"] = py_zxcvbn_scroe_full["score"]
if (abs(py_zxcvbn_scroe["guesses"] - Decimal(js_zxcvbn_score["guesses"])) > MIN_NUMBER_FOR_ACCURACY and
py_zxcvbn_scroe["guesses"] < MAX_NUMBER_FOR_ACCURACY):
guesses_collision += 1
if verbose:
print ("""\033[91m==========================================
expected:
%s
results:
%s\033[00m""")%(js_zxcvbn_score, py_zxcvbn_scroe)
if py_zxcvbn_scroe["score"] != js_zxcvbn_score["score"]:
scores_collision += 1
if (guesses_collision or scores_collision):
print ("""\033[91mFailed!
guesses_collision:%d
guesses_score:%d""")%(guesses_collision, scores_collision)
else:
print ("\033[92mPassed!")
示例10: edit_user
# 需要導入模塊: import zxcvbn [as 別名]
# 或者: from zxcvbn import zxcvbn [as 別名]
def edit_user(user_id):
"""
Modify an existing user.
Parameters
----------
user_id : int
Notes
-----
Will not allow you to revoke admin access if that would leave no
admins.
Expects json of the same form as `add_user`, but all parts are
optional.
See Also
--------
add_user
"""
user = User.query.filter(User.id == user_id).first_or_404()
user_group = [g for g in user.groups if g.user_group][0]
edits = request.get_json()
if "username" in edits:
if len(edits["username"]) > 0:
user.username = edits["username"]
else:
raise InvalidUsage("Username too short.", payload={"bad_field": "username"})
if "password" in edits:
if len(edits["password"]) > 0:
if zxcvbn(edits["password"])["score"] > 3:
user.password = edits["password"]
else:
raise InvalidUsage(
"Password not complex enough.", payload={"bad_field": "password"}
)
if "is_admin" in edits:
if (
not edits["is_admin"]
and user.is_admin
and len(User.query.filter(User.is_admin).all()) == 1
):
raise InvalidUsage(
"Removing this user's admin rights would leave no admins.",
payload={"bad_field": "is_admin"},
)
else:
user.is_admin = edits["is_admin"]
if "require_two_factor" in edits:
user.require_two_factor = edits["require_two_factor"]
if (
"has_two_factor" in edits
and not edits["has_two_factor"]
and user.two_factor_auth is not None
):
db.session.delete(user.two_factor_auth)
db.session.add(user)
db.session.commit()
return jsonify({"id": user.id, "group_id": user_group.id})
示例11: update_stats
# 需要導入模塊: import zxcvbn [as 別名]
# 或者: from zxcvbn import zxcvbn [as 別名]
def update_stats(self, text): # noqa: max-complexity=11 XXX
if not text:
self.time_label.setText("")
self.rating_label.setText("")
self.progressbar.setValue(0)
return
res = zxcvbn(text)
t = res["crack_times_display"]["offline_slow_hashing_1e4_per_second"]
self.time_label.setText("Time to crack: {}".format(t))
s = res["crack_times_seconds"]["offline_slow_hashing_1e4_per_second"]
seconds = int(s)
if seconds == 0:
self.rating_label.setText("Very weak")
self.update_color("lightgray")
self.rating_label.setStyleSheet("QLabel { color: gray }")
self.progressbar.setValue(1)
elif seconds < 86400: # 1 day
self.rating_label.setText("Weak")
self.update_color("red")
self.progressbar.setValue(1)
elif seconds < 2592000: # 1 month
self.rating_label.setText("Alright")
self.update_color("orange")
self.progressbar.setValue(2)
elif seconds < 3153600000: # 100 years
self.rating_label.setText("Good")
self.update_color("#9CC259")
self.progressbar.setValue(3)
else: # > 100 years
self.rating_label.setText("Excellent")
self.update_color("#00B400")
self.progressbar.setValue(4)
warning = res["feedback"]["warning"]
try:
suggestion = "Suggestion: " + res["feedback"]["suggestions"][0]
except IndexError:
suggestion = None
if warning and suggestion:
self.rating_label.setToolTip(warning + "\n\n" + suggestion)
elif warning:
self.rating_label.setToolTip(warning)
elif suggestion:
self.rating_label.setToolTip(suggestion)
else:
self.rating_label.setToolTip(None)