本文整理汇总了Python中student.models.PasswordHistory类的典型用法代码示例。如果您正苦于以下问题:Python PasswordHistory类的具体用法?Python PasswordHistory怎么用?Python PasswordHistory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PasswordHistory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate_password_security
def validate_password_security(password, user):
"""
Check password reuse and similar operational security policy considerations.
"""
# Check reuse
if not PasswordHistory.is_allowable_password_reuse(user, password):
if user.is_staff:
num_distinct = settings.ADVANCED_SECURITY_CONFIG['MIN_DIFFERENT_STAFF_PASSWORDS_BEFORE_REUSE']
else:
num_distinct = settings.ADVANCED_SECURITY_CONFIG['MIN_DIFFERENT_STUDENT_PASSWORDS_BEFORE_REUSE']
raise SecurityPolicyError(ungettext(
"You are re-using a password that you have used recently. "
"You must have {num} distinct password before reusing a previous password.",
"You are re-using a password that you have used recently. "
"You must have {num} distinct passwords before reusing a previous password.",
num_distinct
).format(num=num_distinct))
# Check reset frequency
if PasswordHistory.is_password_reset_too_soon(user):
num_days = settings.ADVANCED_SECURITY_CONFIG['MIN_TIME_IN_DAYS_BETWEEN_ALLOWED_RESETS']
raise SecurityPolicyError(ungettext(
"You are resetting passwords too frequently. Due to security policies, "
"{num} day must elapse between password resets.",
"You are resetting passwords too frequently. Due to security policies, "
"{num} days must elapse between password resets.",
num_days
).format(num=num_days))
示例2: _change_password
def _change_password(self, user, password):
"""
Helper method to change password on user and record in the PasswordHistory
"""
user.set_password(password)
user.save()
history = PasswordHistory()
history.create(user)
示例3: _update_password
def _update_password(self, email, new_password):
"""
Helper method to reset a password
"""
user = User.objects.get(email=email)
user.set_password(new_password)
user.save()
history = PasswordHistory()
history.create(user)
示例4: test_pbkdf2_sha256_password_reuse
def test_pbkdf2_sha256_password_reuse(self):
"""
Assert against the password reuse policy but using the normal Django PBKDF2
"""
user = self._user_factory_with_history()
staff = self._user_factory_with_history(is_staff=True)
# students need to user at least one different passwords before reuse
self.assertFalse(PasswordHistory.is_allowable_password_reuse(user, "test"))
self.assertTrue(PasswordHistory.is_allowable_password_reuse(user, "different"))
self._change_password(user, "different")
self.assertTrue(PasswordHistory.is_allowable_password_reuse(user, "test"))
# staff needs to use at least two different passwords before reuse
self.assertFalse(PasswordHistory.is_allowable_password_reuse(staff, "test"))
self.assertTrue(PasswordHistory.is_allowable_password_reuse(staff, "different"))
self._change_password(staff, "different")
self.assertFalse(PasswordHistory.is_allowable_password_reuse(staff, "test"))
self.assertFalse(PasswordHistory.is_allowable_password_reuse(staff, "different"))
self.assertTrue(PasswordHistory.is_allowable_password_reuse(staff, "third"))
self._change_password(staff, "third")
self.assertTrue(PasswordHistory.is_allowable_password_reuse(staff, "test"))
示例5: test_too_frequent_password_resets
def test_too_frequent_password_resets(self):
"""
Assert that a user should not be able to password reset too frequently
"""
student = self._user_factory_with_history()
grandfathered_student = self._user_factory_with_history(set_initial_history=False)
self.assertTrue(PasswordHistory.is_password_reset_too_soon(student))
self.assertFalse(PasswordHistory.is_password_reset_too_soon(grandfathered_student))
staff_reset_time = timezone.now() + timedelta(days=100)
with freeze_time(staff_reset_time):
self.assertFalse(PasswordHistory.is_password_reset_too_soon(student))
示例6: test_disabled_feature
def test_disabled_feature(self):
"""
Test that behavior is normal when this feature is not turned on
"""
user = UserFactory()
staff = AdminFactory()
# if feature is disabled user can keep reusing same password
self.assertTrue(PasswordHistory.is_allowable_password_reuse(user, "test"))
self.assertTrue(PasswordHistory.is_allowable_password_reuse(staff, "test"))
self.assertFalse(PasswordHistory.should_user_reset_password_now(user))
self.assertFalse(PasswordHistory.should_user_reset_password_now(staff))
示例7: _user_factory_with_history
def _user_factory_with_history(self, is_staff=False, set_initial_history=True):
"""
Helper method to generate either an Admin or a User
"""
if is_staff:
user = AdminFactory()
else:
user = UserFactory()
user.date_joined = timezone.now()
if set_initial_history:
history = PasswordHistory()
history.create(user)
return user
示例8: test_disabled_too_frequent_password_resets
def test_disabled_too_frequent_password_resets(self):
"""
Verify properly default behavior when feature is disabled
"""
student = self._user_factory_with_history()
self.assertFalse(PasswordHistory.is_password_reset_too_soon(student))
示例9: _check_forced_password_reset
def _check_forced_password_reset(user):
"""
See if the user must reset his/her password due to any policy settings
"""
if user and PasswordHistory.should_user_reset_password_now(user):
raise AuthFailedError(_('Your password has expired due to password policy on this account. You must '
'reset your password before you can log in again. Please click the '
'"Forgot Password" link on this page to reset your password before logging in again.'))
示例10: post
def post(self, request):
"""
POST /api/user/v1/accounts/retire_misc/
{
'username': 'user_to_retire'
}
Retires the user with the given username in the LMS.
"""
username = request.data['username']
try:
retirement = UserRetirementStatus.get_retirement_for_retirement_action(username)
RevisionPluginRevision.retire_user(retirement.user)
ArticleRevision.retire_user(retirement.user)
PendingNameChange.delete_by_user_value(retirement.user, field='user')
PasswordHistory.retire_user(retirement.user.id)
course_enrollments = CourseEnrollment.objects.filter(user=retirement.user)
ManualEnrollmentAudit.retire_manual_enrollments(course_enrollments, retirement.retired_email)
CreditRequest.retire_user(retirement.original_username, retirement.retired_username)
ApiAccessRequest.retire_user(retirement.user)
CreditRequirementStatus.retire_user(retirement.user.username)
# This signal allows code in higher points of LMS to retire the user as necessary
USER_RETIRE_LMS_MISC.send(sender=self.__class__, user=retirement.user)
# This signal allows code in higher points of LMS to unsubscribe the user
# from various types of mailings.
USER_RETIRE_MAILINGS.send(
sender=self.__class__,
email=retirement.original_email,
new_email=retirement.retired_email,
user=retirement.user
)
except UserRetirementStatus.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
except RetirementStateError as exc:
return Response(text_type(exc), status=status.HTTP_400_BAD_REQUEST)
except Exception as exc: # pylint: disable=broad-except
return Response(text_type(exc), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return Response(status=status.HTTP_204_NO_CONTENT)
示例11: test_retirement
def test_retirement(self):
"""
Verify that the user's password history contains no actual
passwords after retirement is called.
"""
user = self._user_factory_with_history()
# create multiple rows in the password history table
self._change_password(user, "different")
self._change_password(user, "differentagain")
# ensure the rows were actually created and stored the passwords
self.assertTrue(PasswordHistory.objects.filter(user_id=user.id).exists())
for row in PasswordHistory.objects.filter(user_id=user.id):
self.assertFalse(row.password == "")
# retire the user and ensure that the rows are still present, but with no passwords
PasswordHistory.retire_user(user.id)
self.assertTrue(PasswordHistory.objects.filter(user_id=user.id).exists())
for row in PasswordHistory.objects.filter(user_id=user.id):
self.assertEqual(row.password, "")
示例12: test_no_forced_password_change
def test_no_forced_password_change(self):
"""
Assert that if we skip configuration, then user will never have to force reset password
"""
student = self._user_factory_with_history()
staff = self._user_factory_with_history(is_staff=True)
# also create a user who doesn't have any history
grandfathered_student = UserFactory()
grandfathered_student.date_joined = timezone.now()
self.assertFalse(PasswordHistory.should_user_reset_password_now(student))
self.assertFalse(PasswordHistory.should_user_reset_password_now(staff))
self.assertFalse(PasswordHistory.should_user_reset_password_now(grandfathered_student))
staff_reset_time = timezone.now() + timedelta(days=100)
with freeze_time(staff_reset_time):
self.assertFalse(PasswordHistory.should_user_reset_password_now(student))
self.assertFalse(PasswordHistory.should_user_reset_password_now(grandfathered_student))
self.assertFalse(PasswordHistory.should_user_reset_password_now(staff))
示例13: password_reset_confirm_wrapper
def password_reset_confirm_wrapper(request, uidb36=None, token=None):
"""
A wrapper around django.contrib.auth.views.password_reset_confirm.
Needed because we want to set the user as active at this step.
We also optionally do some additional password policy checks.
"""
# convert old-style base36-encoded user id to base64
uidb64 = uidb36_to_uidb64(uidb36)
platform_name = {
"platform_name": configuration_helpers.get_value('platform_name', settings.PLATFORM_NAME)
}
try:
uid_int = base36_to_int(uidb36)
user = User.objects.get(id=uid_int)
except (ValueError, User.DoesNotExist):
# if there's any error getting a user, just let django's
# password_reset_confirm function handle it.
return password_reset_confirm(
request, uidb64=uidb64, token=token, extra_context=platform_name
)
if UserRetirementRequest.has_user_requested_retirement(user):
# Refuse to reset the password of any user that has requested retirement.
context = {
'validlink': True,
'form': None,
'title': _('Password reset unsuccessful'),
'err_msg': _('Error in resetting your password.'),
}
context.update(platform_name)
return TemplateResponse(
request, 'registration/password_reset_confirm.html', context
)
if waffle().is_enabled(PREVENT_AUTH_USER_WRITES):
context = {
'validlink': False,
'form': None,
'title': _('Password reset unsuccessful'),
'err_msg': SYSTEM_MAINTENANCE_MSG,
}
context.update(platform_name)
return TemplateResponse(
request, 'registration/password_reset_confirm.html', context
)
if request.method == 'POST':
password = request.POST['new_password1']
try:
validate_password(password, user=user)
except ValidationError as err:
# We have a password reset attempt which violates some security
# policy, or any other validation. Use the existing Django template to communicate that
# back to the user.
context = {
'validlink': True,
'form': None,
'title': _('Password reset unsuccessful'),
'err_msg': err.message,
}
context.update(platform_name)
return TemplateResponse(
request, 'registration/password_reset_confirm.html', context
)
# remember what the old password hash is before we call down
old_password_hash = user.password
response = password_reset_confirm(
request, uidb64=uidb64, token=token, extra_context=platform_name
)
# If password reset was unsuccessful a template response is returned (status_code 200).
# Check if form is invalid then show an error to the user.
# Note if password reset was successful we get response redirect (status_code 302).
if response.status_code == 200:
form_valid = response.context_data['form'].is_valid() if response.context_data['form'] else False
if not form_valid:
log.warning(
u'Unable to reset password for user [%s] because form is not valid. '
u'A possible cause is that the user had an invalid reset token',
user.username,
)
response.context_data['err_msg'] = _('Error in resetting your password. Please try again.')
return response
# get the updated user
updated_user = User.objects.get(id=uid_int)
# did the password hash change, if so record it in the PasswordHistory
if updated_user.password != old_password_hash:
entry = PasswordHistory()
entry.create(updated_user)
else:
response = password_reset_confirm(
request, uidb64=uidb64, token=token, extra_context=platform_name
)
#.........这里部分代码省略.........
示例14: post
def post(self, request):
response_data = {}
# Add some rate limiting here by re-using the RateLimitMixin as a helper class
limiter = BadRequestRateLimiter()
if limiter.is_rate_limit_exceeded(request):
response_data['message'] = _('Rate limit exceeded in api login.')
return Response(response_data, status=status.HTTP_403_FORBIDDEN)
base_uri = generate_base_uri(request)
try:
existing_user = User.objects.get(username=request.DATA['username'])
except ObjectDoesNotExist:
existing_user = None
# see if account has been locked out due to excessive login failures
if existing_user and LoginFailures.is_feature_enabled():
if LoginFailures.is_user_locked_out(existing_user):
response_status = status.HTTP_403_FORBIDDEN
response_data['message'] = _('This account has been temporarily locked due to excessive login failures. '
'Try again later.')
return Response(response_data, status=response_status)
# see if the user must reset his/her password due to any policy settings
if existing_user and PasswordHistory.should_user_reset_password_now(existing_user):
response_status = status.HTTP_403_FORBIDDEN
response_data['message'] = _(
'Your password has expired due to password policy on this account. '
'You must reset your password before you can log in again.'
)
return Response(response_data, status=response_status)
if existing_user:
user = authenticate(username=existing_user.username, password=request.DATA['password'])
if user is not None:
# successful login, clear failed login attempts counters, if applicable
if LoginFailures.is_feature_enabled():
LoginFailures.clear_lockout_counter(user)
if user.is_active:
login(request, user)
response_data['token'] = request.session.session_key
response_data['expires'] = request.session.get_expiry_age()
user_dto = UserSerializer(user)
response_data['user'] = user_dto.data
response_data['uri'] = '{}/{}'.format(base_uri, request.session.session_key)
response_status = status.HTTP_201_CREATED
# add to audit log
AUDIT_LOG.info(u"API::User logged in successfully with user-id - {0}".format(user.id))
else:
response_status = status.HTTP_403_FORBIDDEN
else:
limiter.tick_bad_request_counter(request)
# tick the failed login counters if the user exists in the database
if LoginFailures.is_feature_enabled():
LoginFailures.increment_lockout_counter(existing_user)
response_status = status.HTTP_401_UNAUTHORIZED
AUDIT_LOG.warn(u"API::User authentication failed with user-id - {0}".format(existing_user.id))
else:
AUDIT_LOG.warn(u"API::Failed login attempt with unknown email/username")
response_status = status.HTTP_404_NOT_FOUND
return Response(response_data, status=response_status)
示例15: post
def post(request, error=""): # pylint: disable-msg=too-many-statements,unused-argument
"""AJAX request to log in the user."""
backend_name = None
email = None
password = None
redirect_url = None
response = None
running_pipeline = None
third_party_auth_requested = settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH') and pipeline.running(request)
third_party_auth_successful = False
trumped_by_first_party_auth = bool(request.POST.get('email')) or bool(request.POST.get('password'))
user = None
if 'email' not in request.POST or 'password' not in request.POST:
return JsonResponse({
"success": False,
"value": _('There was an error receiving your login information. Please email us.'), # TODO: User error message
}) # TODO: this should be status code 400 # pylint: disable=fixme
email = request.POST['email']
password = request.POST['password']
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
AUDIT_LOG.warning(u"Login failed - Unknown user email")
else:
AUDIT_LOG.warning(u"Login failed - Unknown user email: {0}".format(email))
# see if account has been locked out due to excessive login failures
user_found_by_email_lookup = user
if user_found_by_email_lookup and LoginFailures.is_feature_enabled():
if LoginFailures.is_user_locked_out(user_found_by_email_lookup):
return JsonResponse({
"success": False,
"value": _('This account has been temporarily locked due to excessive login failures. Try again later.'),
}) # TODO: this should be status code 429 # pylint: disable=fixme
# see if the user must reset his/her password due to any policy settings
if PasswordHistory.should_user_reset_password_now(user_found_by_email_lookup):
return JsonResponse({
"success": False,
"value": _('Your password has expired due to password policy on this account. You must '
'reset your password before you can log in again. Please click the '
'"Forgot Password" link on this page to reset your password before logging in again.'),
}) # TODO: this should be status code 403 # pylint: disable=fixme
# if the user doesn't exist, we want to set the username to an invalid
# username so that authentication is guaranteed to fail and we can take
# advantage of the ratelimited backend
username = user.username if user else ""
if not third_party_auth_successful:
try:
user = authenticate(username=username, password=password, request=request)
# this occurs when there are too many attempts from the same IP address
except RateLimitException:
return JsonResponse({
"success": False,
"value": _('Too many failed login attempts. Try again later.'),
}) # TODO: this should be status code 429 # pylint: disable=fixme
if user is None:
# tick the failed login counters if the user exists in the database
if user_found_by_email_lookup and LoginFailures.is_feature_enabled():
LoginFailures.increment_lockout_counter(user_found_by_email_lookup)
# if we didn't find this username earlier, the account for this email
# doesn't exist, and doesn't have a corresponding password
if username != "":
if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
loggable_id = user_found_by_email_lookup.id if user_found_by_email_lookup else "<unknown>"
AUDIT_LOG.warning(u"Login failed - password for user.id: {0} is invalid".format(loggable_id))
else:
AUDIT_LOG.warning(u"Login failed - password for {0} is invalid".format(email))
return JsonResponse({
"success": False,
"value": _('Email or password is incorrect.'),
}) # TODO: this should be status code 400 # pylint: disable=fixme
# successful login, clear failed login attempts counters, if applicable
if LoginFailures.is_feature_enabled():
LoginFailures.clear_lockout_counter(user)
if user is not None and user.is_active:
try:
# We do not log here, because we have a handler registered
# to perform logging on successful logins.
login(request, user)
if request.POST.get('remember') == 'true':
request.session.set_expiry(604800)
log.debug("Setting user session to never expire")
else:
request.session.set_expiry(0)
except Exception as e:
#.........这里部分代码省略.........