本文整理汇总了Python中student.models.PasswordHistory.should_user_reset_password_now方法的典型用法代码示例。如果您正苦于以下问题:Python PasswordHistory.should_user_reset_password_now方法的具体用法?Python PasswordHistory.should_user_reset_password_now怎么用?Python PasswordHistory.should_user_reset_password_now使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类student.models.PasswordHistory
的用法示例。
在下文中一共展示了PasswordHistory.should_user_reset_password_now方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_disabled_feature
# 需要导入模块: from student.models import PasswordHistory [as 别名]
# 或者: from student.models.PasswordHistory import should_user_reset_password_now [as 别名]
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))
示例2: _check_forced_password_reset
# 需要导入模块: from student.models import PasswordHistory [as 别名]
# 或者: from student.models.PasswordHistory import should_user_reset_password_now [as 别名]
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.'))
示例3: test_no_forced_password_change
# 需要导入模块: from student.models import PasswordHistory [as 别名]
# 或者: from student.models.PasswordHistory import should_user_reset_password_now [as 别名]
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))
示例4: post
# 需要导入模块: from student.models import PasswordHistory [as 别名]
# 或者: from student.models.PasswordHistory import should_user_reset_password_now [as 别名]
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)
示例5: test_forced_password_change
# 需要导入模块: from student.models import PasswordHistory [as 别名]
# 或者: from student.models.PasswordHistory import should_user_reset_password_now [as 别名]
def test_forced_password_change(self):
"""
Assert when passwords must be reset
"""
student = self._user_factory_with_history()
staff = self._user_factory_with_history(is_staff=True)
grandfathered_student = self._user_factory_with_history(set_initial_history=False)
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=1)
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.assertTrue(PasswordHistory.should_user_reset_password_now(staff))
self._change_password(staff, 'Different')
self.assertFalse(PasswordHistory.should_user_reset_password_now(staff))
student_reset_time = timezone.now() + timedelta(days=5)
with freeze_time(student_reset_time):
self.assertTrue(PasswordHistory.should_user_reset_password_now(student))
self.assertTrue(PasswordHistory.should_user_reset_password_now(grandfathered_student))
self.assertTrue(PasswordHistory.should_user_reset_password_now(staff))
self._change_password(student, 'Different')
self.assertFalse(PasswordHistory.should_user_reset_password_now(student))
self._change_password(grandfathered_student, 'Different')
self.assertFalse(PasswordHistory.should_user_reset_password_now(grandfathered_student))
self._change_password(staff, 'Different')
self.assertFalse(PasswordHistory.should_user_reset_password_now(staff))
示例6: post
# 需要导入模块: from student.models import PasswordHistory [as 别名]
# 或者: from student.models.PasswordHistory import should_user_reset_password_now [as 别名]
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:
#.........这里部分代码省略.........
示例7: post
# 需要导入模块: from student.models import PasswordHistory [as 别名]
# 或者: from student.models.PasswordHistory import should_user_reset_password_now [as 别名]
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:
#
# Create a new session directly with the SESSION_ENGINE
# We don't call the django.contrib.auth login() method
# because it is bound with the HTTP request.
#
# Since we are a server-to-server API, we shouldn't
# be stateful with respect to the HTTP request
# and anything that might come with it, as it could
# violate our RESTfulness
#
engine = import_module(settings.SESSION_ENGINE)
new_session = engine.SessionStore()
new_session.create()
# These values are expected to be set in any new session
new_session[SESSION_KEY] = user.id
new_session[BACKEND_SESSION_KEY] = user.backend
new_session.save()
response_data['token'] = new_session.session_key
response_data['expires'] = new_session.get_expiry_age()
user_dto = UserSerializer(user)
response_data['user'] = user_dto.data
response_data['uri'] = '{}/{}'.format(base_uri, new_session.session_key)
response_status = status.HTTP_201_CREATED
# generate a CSRF tokens for any web clients that may need to
# call into the LMS via Ajax (for example Notifications)
response_data['csrftoken'] = RequestContext(request, {}).get('csrf_token')
# update the last_login fields in the auth_user table for this user
user.last_login = timezone.now()
user.save()
# 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)