def change_forgotten_password(request, pk, token): User = auth.get_user_model() invalid_message = _("Form link is invalid. Please try again.") expired_message = _("Your link has expired. Please request new one.") try: try: user = User.objects.get(pk=pk) except User.DoesNotExist: raise PasswordChangeFailed(invalid_message) if request.user.is_authenticated() and request.user.id != user.id: raise PasswordChangeFailed(invalid_message) if not is_password_change_token_valid(user, token): raise PasswordChangeFailed(invalid_message) if user.requires_activation: raise PasswordChangeFailed(expired_message) if get_user_ban(user): raise PasswordChangeFailed(expired_message) except PasswordChangeFailed as e: return Response({'detail': e.args[0]}, status=status.HTTP_400_BAD_REQUEST) try: new_password = request.data.get('password', '').strip() validate_password(new_password) user.set_password(new_password) user.save() except ValidationError as e: return Response({'detail': e.messages[0]}, status=status.HTTP_400_BAD_REQUEST) return Response({'username': user.username})
def test_expired_ban(self): """user is not caught by expired ban""" Ban.objects.create(banned_value='bo*', valid_until=date.today() - timedelta(days=7)) self.assertIsNone(get_user_ban(self.user)) self.assertFalse(self.user.ban_cache.is_banned)
def process_request(self, request): if request.user.is_anonymous(): request.user = AnonymousUser() elif not request.user.is_superuser: if get_request_ip_ban(request) or get_user_ban(request.user): logout(request) request.user.ip = request._misago_real_ip
def activate_by_token(request, user_id, token): User = get_user_model() inactive_user = get_object_or_404(User.objects, pk=user_id) try: if not inactive_user.requires_activation: message = _("%(user)s, your account is already active.") message = message % {"user": inactive_user.username} raise ActivationStopped(message) if not is_activation_token_valid(inactive_user, token): message = _("%(user)s, your activation link is invalid. " "Try again or request new activation link.") message = message % {"user": inactive_user.username} raise ActivationError(message) ban = get_user_ban(inactive_user) if ban: raise Banned(ban) except ActivationStopped as e: return render(request, "misago/activation/stopped.html", {"message": e.args[0]}) except ActivationError as e: return render(request, "misago/activation/error.html", {"message": e.args[0]}, status=400) inactive_user.requires_activation = ACTIVATION_REQUIRED_NONE inactive_user.save(update_fields=["requires_activation"]) message = _("%(user)s, your account has been activated!") return render(request, "misago/activation/done.html", {"message": message % {"user": inactive_user.username}})
def test_expired_ban(self): """user is not caught by expired ban""" Ban.objects.create(banned_value='bo*', expires_on=timezone.now() - timedelta(days=7)) self.assertIsNone(get_user_ban(self.user)) self.assertFalse(self.user.ban_cache.is_banned)
def reset_password_form(request, pk, token): requesting_user = get_object_or_404(get_user_model(), pk=pk) try: if (request.user.is_authenticated and request.user.id != requesting_user.id): message = _("%(user)s, your link has expired. " "Please request new link and try again.") message = message % {'user': requesting_user.username} raise ResetError(message) if not is_password_change_token_valid(requesting_user, token): message = _("%(user)s, your link is invalid. " "Please try again or request new link.") message = message % {'user': requesting_user.username} raise ResetError(message) ban = get_user_ban(requesting_user) if ban: raise Banned(ban) except ResetError as e: return render(request, 'misago/forgottenpassword/error.html', { 'message': e.args[0], }, status=400) api_url = reverse('misago:api:change-forgotten-password', kwargs={ 'pk': pk, 'token': token, }) request.frontend_context['CHANGE_PASSWORD_API'] = api_url return render(request, 'misago/forgottenpassword/form.html')
def reset_password_form(request, user_id, token): User = get_user_model() requesting_user = get_object_or_404(User.objects, pk=user_id) try: if (request.user.is_authenticated() and request.user.id != requesting_user.id): message = _("%(user)s, your link has expired. " "Please request new link and try again.") message = message % {'user': requesting_user.username} raise ResetError(message) if not is_password_change_token_valid(requesting_user, token): message = _("%(user)s, your link is invalid. " "Please try again or request new link.") message = message % {'user': requesting_user.username} raise ResetError(message) ban = get_user_ban(requesting_user) if ban: raise Banned(ban) except ResetError as e: return render(request, 'misago/forgottenpassword/error.html', { 'message': e.args[0], }, status=400) api_url = reverse('misago:api:change_forgotten_password', kwargs={ 'user_id': user_id, 'token': token, }) request.frontend_context['CHANGE_PASSWORD_API_URL'] = api_url return render(request, 'misago/forgottenpassword/form.html')
def validate_user_not_banned(strategy, details, backend, user=None, *args, **kwargs): """Pipeline step that interrupts pipeline if found user is non-staff and banned""" if not user or user.is_staff: return None user_ban = get_user_ban(user) if user_ban: raise SocialAuthBanned(backend, user_ban)
def get_context_data(self, request, profile): ban = get_user_ban(profile) request.frontend_context['PROFILE_BAN'] = BanDetailsSerializer(ban).data return { 'ban': ban, }
def user_ban(request, profile): ban = get_user_ban(profile) if not ban: raise Http404() return render(request, 'misago/profile/ban_details.html', { 'profile': profile, 'ban': ban })
def test_permanent_ban(self): """user is caught by permanent ban""" Ban.objects.create(banned_value="bob", user_message="User reason", staff_message="Staff reason") user_ban = get_user_ban(self.user) self.assertIsNotNone(user_ban) self.assertEqual(user_ban.user_message, "User reason") self.assertEqual(user_ban.staff_message, "Staff reason") self.assertTrue(self.user.ban_cache.is_banned)
def user_ban(request, profile): ban = get_user_ban(profile) request.frontend_context['PROFILE_BAN'] = BanDetailsSerializer(ban).data return render(request, 'misago/profile/ban_details.html', { 'profile': profile, 'ban': ban, })
def ban(self, request, pk=None): profile = self.get_user(request, pk) allow_see_ban_details(request.user, profile) ban = get_user_ban(profile) if ban: return Response(BanDetailsSerializer(ban).data) else: return Response({})
def can_see_ban_details(request, profile): if request.user.is_authenticated(): if request.user.acl['can_see_ban_details']: from misago.users.bans import get_user_ban return bool(get_user_ban(profile)) else: return False else: return False
def user_ban(request, profile): ban = get_user_ban(profile) request.frontend_context['PROFILE_BAN'] = ban.get_serialized_message() return render(request, 'misago/profile/ban_details.html', { 'profile': profile, 'ban': ban, })
def ban(self, request, pk=None): profile = self.get_user(pk) allow_see_ban_details(request.user, profile) ban = get_user_ban(profile) if (ban): return Response(BanDetailsSerializer(ban).data) else: return Response({})
def test_ban_user(self): """ban_user utility bans user""" user = UserModel.objects.create_user('Bob', '*****@*****.**', 'pass123') ban = ban_user(user, 'User reason', 'Staff reason') self.assertEqual(ban.user_message, 'User reason') self.assertEqual(ban.staff_message, 'Staff reason') db_ban = get_user_ban(user) self.assertEqual(ban.pk, db_ban.ban_id)
def test_ban_user(self): """ban_user bans user""" User = get_user_model() user = User.objects.create_user("Bob", "*****@*****.**", "pass123") ban = ban_user(user, "User reason", "Staff reason") self.assertEqual(ban.user_message, "User reason") self.assertEqual(ban.staff_message, "Staff reason") db_ban = get_user_ban(user) self.assertEqual(ban.pk, db_ban.ban_id)
def test_permanent_ban(self): """user is caught by permanent ban""" Ban.objects.create(banned_value='bob', user_message='User reason', staff_message='Staff reason') user_ban = get_user_ban(self.user) self.assertIsNotNone(user_ban) self.assertEqual(user_ban.user_message, 'User reason') self.assertEqual(user_ban.staff_message, 'Staff reason') self.assertTrue(self.user.ban_cache.is_banned)
def test_bans_caches_updates(self): """ban caches are updated""" user = UserModel.objects.create_user("Bob", "*****@*****.**", "Pass.123") # ban user Ban.objects.create(banned_value="bob") user_ban = bans.get_user_ban(user) self.assertIsNotNone(user_ban) self.assertEqual(Ban.objects.filter(is_checked=True).count(), 1) # first call didn't touch ban command = invalidatebans.Command() out = StringIO() call_command(command, stdout=out) command_output = out.getvalue().splitlines()[1].strip() self.assertEqual(command_output, 'Ban caches emptied: 0') self.assertEqual(Ban.objects.filter(is_checked=True).count(), 1) # expire bans expired_date = timezone.now() - timedelta(days=10) Ban.objects.all().update( expires_on=expired_date, is_checked=True, ) BanCache.objects.all().update(expires_on=expired_date) # invalidate expired ban cache out = StringIO() call_command(command, stdout=out) command_output = out.getvalue().splitlines()[1].strip() self.assertEqual(command_output, 'Ban caches emptied: 1') self.assertEqual(Ban.objects.filter(is_checked=True).count(), 0) # see if user is banned anymore user = UserModel.objects.get(id=user.id) self.assertIsNone(bans.get_user_ban(user))
def test_temporary_ban(self): """user is caught by temporary ban""" Ban.objects.create(banned_value='bo*', user_message='User reason', staff_message='Staff reason', expires_on=timezone.now() + timedelta(days=7)) user_ban = get_user_ban(self.user) self.assertIsNotNone(user_ban) self.assertEqual(user_ban.user_message, 'User reason') self.assertEqual(user_ban.staff_message, 'Staff reason') self.assertTrue(self.user.ban_cache.is_banned)
def lift_user_ban(request, user): return_path = moderation_return_path(request, user) user_ban = get_user_ban(user).ban user_ban.lift() user_ban.save() Ban.objects.invalidate_cache() message = _("%(user)s's ban has been lifted.") messages.success(request, message % {'user': user.username}) return redirect(return_path)
def test_bans_caches_updates(self): """ban caches are updated""" # create user User = get_user_model() user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123") # ban user Ban.objects.create(banned_value="bob") user_ban = bans.get_user_ban(user) self.assertIsNotNone(user_ban) self.assertEqual(Ban.objects.filter(is_valid=True).count(), 1) # first call didn't touch ban command = bansmaintenance.Command() out = StringIO() command.execute(stdout=out) command_output = out.getvalue().splitlines()[1].strip() self.assertEqual(command_output, 'Ban caches emptied: 0') self.assertEqual(Ban.objects.filter(is_valid=True).count(), 1) # expire bans bans_expired = (timezone.now() - timedelta(days=10)).date() Ban.objects.all().update(valid_until=bans_expired, is_valid=True) BanCache.objects.all().update(valid_until=bans_expired) # invalidate expired ban cache out = StringIO() command.execute(stdout=out) command_output = out.getvalue().splitlines()[1].strip() self.assertEqual(command_output, 'Ban caches emptied: 1') self.assertEqual(Ban.objects.filter(is_valid=True).count(), 0) # see if user is banned anymore user = User.objects.get(id=user.id) self.assertIsNone(bans.get_user_ban(user))
def reset_password_form(request, user_id, token): User = get_user_model() requesting_user = get_object_or_404(User.objects, pk=user_id) try: if requesting_user.requires_activation_by_admin: message = _("%(user)s, administrator has to activate your " "account before you will be able to request " "new password.") message = message % {'user': requesting_user.username} raise ResetStopped(message) if requesting_user.requires_activation_by_user: message = _("%(user)s, you have to activate your account " "before you will be able to request new password.") message = message % {'user': requesting_user.username} raise ResetStopped(message) if get_user_ban(requesting_user): message = _("%(user)s, your account is banned " "and it's password can't be changed.") message = message % {'user': requesting_user.username} raise ResetError(message) if not is_password_reset_token_valid(requesting_user, token): message = _("%(user)s, your link is invalid. " "Try again or request new link.") message = message % {'user': requesting_user.username} raise ResetError(message) except ResetStopped as e: messages.info(request, e.args[0]) return redirect('misago:index') except ResetError as e: messages.error(request, e.args[0]) return redirect('misago:request_password_reset') form = SetNewPasswordForm() if request.method == 'POST': form = SetNewPasswordForm(request.POST) if form.is_valid(): requesting_user.set_password(form.cleaned_data['new_password']) requesting_user.save(update_fields=['password']) message = _("%(user)s, your password has been changed.") message = message % {'user': requesting_user.username} messages.success(request, message) return redirect(settings.LOGIN_URL) return render(request, 'misago/forgottenpassword/reset_password_form.html', { 'requesting_user': requesting_user, 'form': form })
def allow_lift_ban(user, target): if not user.acl_cache['can_lift_bans']: raise PermissionDenied(_("You can't lift bans.")) ban = get_user_ban(target) if not ban: raise PermissionDenied(_("This user is not banned.")) if user.acl_cache['max_lifted_ban_length']: expiration_limit = timedelta(days=user.acl_cache['max_lifted_ban_length']) lift_cutoff = (timezone.now() + expiration_limit).date() if not ban.valid_until: raise PermissionDenied(_("You can't lift permanent bans.")) elif ban.valid_until > lift_cutoff: message = _("You can't lift bans that expire after %(expiration)s.") raise PermissionDenied(message % {'expiration': format_date(lift_cutoff)})
def reset_password_form(request, user_id, token): User = get_user_model() requesting_user = get_object_or_404(User.objects, pk=user_id) try: if requesting_user.requires_activation_by_admin: message = _( "%(user)s, administrator has to activate your " "account before you will be able to request " "new password." ) message = message % {"user": requesting_user.username} raise ResetStopped(message) if requesting_user.requires_activation_by_user: message = _( "%(user)s, you have to activate your account " "before you will be able to request new password." ) message = message % {"user": requesting_user.username} raise ResetStopped(message) if get_user_ban(requesting_user): message = _("%(user)s, your account is banned " "and it's password can't be changed.") message = message % {"user": requesting_user.username} raise ResetError(message) if not is_password_reset_token_valid(requesting_user, token): message = _("%(user)s, your link is invalid. " "Try again or request new link.") message = message % {"user": requesting_user.username} raise ResetError(message) except ResetStopped as e: messages.info(request, e.args[0]) return redirect("misago:index") except ResetError as e: messages.error(request, e.args[0]) return redirect("misago:request_password_reset") form = SetNewPasswordForm() if request.method == "POST": form = SetNewPasswordForm(request.POST) if form.is_valid(): requesting_user.set_password(form.cleaned_data["new_password"]) requesting_user.save(update_fields=["password"]) message = _("%(user)s, your password has been changed.") message = message % {"user": requesting_user.username} messages.success(request, message) return redirect(settings.LOGIN_URL) return render( request, "misago/forgottenpassword/reset_password_form.html", {"requesting_user": requesting_user, "form": form} )
def get_user_status(viewer, user): user_status = { 'is_banned': False, 'is_hidden': user.is_hiding_presence, 'is_online_hidden': False, 'is_offline_hidden': False, 'is_online': False, 'is_offline': False, 'banned_until': None, 'last_click': user.last_login or user.joined_on, } user_ban = get_user_ban(user) if user_ban: user_status['is_banned'] = True user_status['banned_until'] = user_ban.expires_on try: online_tracker = user.online_tracker is_hidden = user.is_hiding_presence and not viewer.acl[ 'can_see_hidden_users'] if online_tracker and not is_hidden: if online_tracker.last_click >= timezone.now() - ACTIVITY_CUTOFF: user_status['is_online'] = True user_status['last_click'] = online_tracker.last_click except Online.DoesNotExist: pass if user_status['is_hidden']: if viewer.acl['can_see_hidden_users']: user_status['is_hidden'] = False if user_status['is_online']: user_status['is_online_hidden'] = True user_status['is_online'] = False else: user_status['is_offline_hidden'] = True user_status['is_offline'] = False else: user_status['is_hidden'] = True else: if user_status['is_online']: user_status['is_online'] = True else: user_status['is_offline'] = True return user_status
def get_user_status(viewer, user): user_status = { 'is_banned': False, 'is_hidden': user.is_hiding_presence, 'is_online_hidden': False, 'is_offline_hidden': False, 'is_online': False, 'is_offline': False, 'banned_until': None, 'last_click': user.last_login or user.joined_on, } user_ban = get_user_ban(user) if user_ban: user_status['is_banned'] = True user_status['banned_until'] = user_ban.expires_on try: online_tracker = user.online_tracker is_hidden = user.is_hiding_presence and not viewer.acl_cache['can_see_hidden_users'] if online_tracker and not is_hidden: if online_tracker.last_click >= timezone.now() - ACTIVITY_CUTOFF: user_status['is_online'] = True user_status['last_click'] = online_tracker.last_click except Online.DoesNotExist: pass if user_status['is_hidden']: if viewer.acl_cache['can_see_hidden_users']: user_status['is_hidden'] = False if user_status['is_online']: user_status['is_online_hidden'] = True user_status['is_online'] = False else: user_status['is_offline_hidden'] = True user_status['is_offline'] = False else: user_status['is_hidden'] = True else: if user_status['is_online']: user_status['is_online'] = True else: user_status['is_offline'] = True return user_status
def change_forgotten_password(request, pk, token): """ POST /auth/change-password/user/token/ with CSRF and new password will change forgotten password """ invalid_message = _("Form link is invalid. Please try again.") expired_message = _("Your link has expired. Please request new one.") try: try: user = UserModel.objects.get(pk=pk, is_active=True) except UserModel.DoesNotExist: raise PasswordChangeFailed(invalid_message) if request.user.is_authenticated and request.user.id != user.id: raise PasswordChangeFailed(invalid_message) if not is_password_change_token_valid(user, token): raise PasswordChangeFailed(invalid_message) if user.requires_activation: raise PasswordChangeFailed(expired_message) if get_user_ban(user): raise PasswordChangeFailed(expired_message) except PasswordChangeFailed as e: return Response( { 'detail': e.args[0], }, status=status.HTTP_400_BAD_REQUEST, ) try: new_password = request.data.get('password', '') validate_password(new_password, user=user) user.set_password(new_password) user.save() except ValidationError as e: return Response( { 'detail': e.messages[0], }, status=status.HTTP_400_BAD_REQUEST, ) return Response({'username': user.username})
def get_user_state(user, acl): user_state = { 'is_banned': False, 'is_hidden': user.is_hiding_presence, 'is_online_hidden': False, 'is_offline_hidden': False, 'is_online': False, 'is_offline': False, 'banned_until': None, 'last_click': user.last_login or user.joined_on, } user_ban = get_user_ban(user) if user_ban: user_state['is_banned'] = True user_state['banned_until'] = user_ban.expires_on ban_expiration_date = user_ban.formatted_expiration_date user_state['formatted_ban_expiration_date'] = ban_expiration_date try: if not user.is_hiding_presence or acl['can_see_hidden_users']: online_tracker = user.online_tracker if online_tracker.last_click >= timezone.now() - ACTIVITY_CUTOFF: user_state['is_online'] = True user_state['last_click'] = online_tracker.last_click except Online.DoesNotExist: pass if user_state['is_hidden']: if acl['can_see_hidden_users']: if user_state['is_online']: user_state['is_online_hidden'] = True else: user_state['is_offline_hidden'] = True else: user_state['is_hidden'] = True else: if user_state['is_online']: user_state['is_online'] = True else: user_state['is_offline'] = True return user_state
def activate_by_token(request, pk, token): inactive_user = get_object_or_404(UserModel, pk=pk, is_active=True) try: if not inactive_user.requires_activation: message = _("%(user)s, your account is already active.") raise ActivationStopped(message % {'user': inactive_user.username}) if not is_activation_token_valid(inactive_user, token): message = _( "%(user)s, your activation link is invalid. " "Try again or request new activation link." ) raise ActivationError(message % {'user': inactive_user.username}) ban = get_user_ban(inactive_user) if ban: raise Banned(ban) except ActivationStopped as e: return render(request, 'misago/activation/stopped.html', { 'message': e.args[0], }) except ActivationError as e: return render( request, 'misago/activation/error.html', { 'message': e.args[0], }, status=400, ) inactive_user.requires_activation = UserModel.ACTIVATION_NONE inactive_user.save(update_fields=['requires_activation']) message = _("%(user)s, your account has been activated!") return render( request, 'misago/activation/done.html', { 'message': message % { 'user': inactive_user.username, }, } )
def get_user_state(user, acl): user_state = { "is_banned": False, "is_hidden": user.is_hiding_presence, "is_online_hidden": False, "is_offline_hidden": False, "is_online": False, "is_offline": False, "banned_until": None, "last_click": user.last_login or user.joined_on, } user_ban = get_user_ban(user) if user_ban: user_state["is_banned"] = True user_state["banned_until"] = user_ban.expires_on try: if not user.is_hiding_presence or acl["can_see_hidden_users"]: online_tracker = user.online_tracker if online_tracker.last_click >= timezone.now() - ACTIVITY_CUTOFF: user_state["is_online"] = True user_state["last_click"] = online_tracker.last_click except Online.DoesNotExist: pass if user_state["is_hidden"]: if acl["can_see_hidden_users"]: if user_state["is_online"]: user_state["is_online_hidden"] = True else: user_state["is_offline_hidden"] = True else: user_state["is_hidden"] = True else: if user_state["is_online"]: user_state["is_online"] = True else: user_state["is_offline"] = True return user_state
def change_forgotten_password(request, user_id, token): User = auth.get_user_model() invalid_message = _("Form link is invalid. Please try again.") expired_message = _("Your link has expired. Please request new one.") try: try: user = User.objects.get(pk=user_id) except User.DoesNotExist: raise PasswordChangeFailed(invalid_message) if request.user.is_authenticated() and request.user.id != user.id: raise PasswordChangeFailed(invalid_message) if not is_password_change_token_valid(user, token): raise PasswordChangeFailed(invalid_message) if user.requires_activation: raise PasswordChangeFailed(expired_message) if get_user_ban(user): raise PasswordChangeFailed(expired_message) except PasswordChangeFailed as e: return Response({ 'detail': e.args[0] }, status=status.HTTP_400_BAD_REQUEST) try: new_password = request.data.get('password', '').strip() validate_password(new_password) user.set_password(new_password) user.save() except ValidationError as e: return Response({ 'detail': e.messages[0] }, status=status.HTTP_400_BAD_REQUEST) return Response({ 'username': user.username })
def confirm_user_not_banned(self, user): self.user_ban = get_user_ban(user) if self.user_ban: if self.user_ban.expires_on: if self.user_ban.user_message: message = _("%(user)s, your account is " "banned until %(date)s for:") else: message = _("%(user)s, your account " "is banned until %(date)s.") date_format = {'date': self.user_ban.formatted_expiration_date} message = message % date_format else: if self.user_ban.user_message: message = _("%(user)s, your account is banned for:") else: message = _("%(user)s, your account is banned.") raise ValidationError( message % {'user': self.user_cache.username}, code='banned', )
def activate_by_token(request, user_id, token): User = get_user_model() inactive_user = get_object_or_404(User.objects, pk=user_id) try: if not inactive_user.requires_activation: message = _("%(user)s, your account is already active.") message = message % {'user': inactive_user.username} raise ActivationStopped(message) if inactive_user.requires_activation_by_admin: message = _("%(user)s, your account can be activated " "only by one of the administrators.") message = message % {'user': inactive_user.username} raise ActivationStopped(message) if get_user_ban(inactive_user): message = _("%(user)s, your account is banned " "and can't be activated.") message = message % {'user': inactive_user.username} raise ActivationError(message) if not is_activation_token_valid(inactive_user, token): message = _("%(user)s, your activation link is invalid. " "Try again or request new activation message.") message = message % {'user': inactive_user.username} raise ActivationError(message) except ActivationStopped as e: messages.info(request, e.args[0]) return redirect('misago:index') except ActivationError as e: messages.error(request, e.args[0]) return redirect('misago:request_activation') inactive_user.requires_activation = ACTIVATION_REQUIRED_NONE inactive_user.save(update_fields=['requires_activation']) message = _("%(user)s, your account has been activated!") message = message % {'user': inactive_user.username} messages.success(request, message) return redirect(settings.LOGIN_URL)
def confirm_user_not_banned(self, user): self.user_ban = get_user_ban(user) if self.user_ban: if self.user_ban.valid_until: if self.user_ban.user_message: message = _("%(user)s, your account is " "banned until %(date)s for:") else: message = _("%(user)s, your account " "is banned until %(date)s.") date_format = {'date': format_date(self.user_ban.valid_until)} message = message % date_format else: if self.user_ban.user_message: message = _("%(user)s, your account is banned for:") else: message = _("%(user)s, your account is banned.") raise ValidationError( message % {'user': self.user_cache.username}, code='banned', )
def reset_password_form(request, pk, token): requesting_user = get_object_or_404(get_user_model(), pk=pk, is_active=True) try: if (request.user.is_authenticated and request.user.id != requesting_user.id): message = _( "%(user)s, your link has expired. Please request new link and try again." ) raise ResetError(message % {'user': requesting_user.username}) if not is_password_change_token_valid(requesting_user, token): message = _( "%(user)s, your link is invalid. Please try again or request new link." ) raise ResetError(message % {'user': requesting_user.username}) ban = get_user_ban(requesting_user) if ban: raise Banned(ban) except ResetError as e: return render(request, 'misago/forgottenpassword/error.html', { 'message': e.args[0], }, status=400) request.frontend_context['store'].update({ 'forgotten_password': { 'id': pk, 'token': token, }, }) return render(request, 'misago/forgottenpassword/form.html')
def activate_by_token(request, user_id, token): User = get_user_model() inactive_user = get_object_or_404(User.objects, pk=user_id) try: if not inactive_user.requires_activation: message = _("%(user)s, your account is already active.") message = message % {"user": inactive_user.username} raise ActivationStopped(message) if inactive_user.requires_activation_by_admin: message = _("%(user)s, your account can be activated " "only by one of the administrators.") message = message % {"user": inactive_user.username} raise ActivationStopped(message) if get_user_ban(inactive_user): message = _("%(user)s, your account is banned " "and can't be activated.") message = message % {"user": inactive_user.username} raise ActivationError(message) if not is_activation_token_valid(inactive_user, token): message = _("%(user)s, your activation link is invalid. " "Try again or request new activation message.") message = message % {"user": inactive_user.username} raise ActivationError(message) except ActivationStopped as e: messages.info(request, e.args[0]) return redirect("misago:index") except ActivationError as e: messages.error(request, e.args[0]) return redirect("misago:request_activation") inactive_user.requires_activation = ACTIVATION_REQUIRED_NONE inactive_user.save(update_fields=["requires_activation"]) message = _("%(user)s, your account has been activated!") message = message % {"user": inactive_user.username} messages.success(request, message) return redirect(settings.LOGIN_URL)
def get_user_ban(self, user): if user.is_staff: return None return get_user_ban(user)
def confirm_user_not_banned(self, user): if not user.is_staff: self.user_ban = get_user_ban(user) if self.user_ban: raise ValidationError('', code='banned')
def test_no_ban(self): """user is not caught by ban""" self.assertIsNone(get_user_ban(self.user)) self.assertFalse(self.user.ban_cache.is_banned)
def confirm_user_not_banned(self, user): self.user_ban = get_user_ban(user) if self.user_ban: raise ValidationError('', code='banned')