示例#1
0
文件: auth.py 项目: pylixm/Misago
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})
示例#2
0
    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)
示例#3
0
 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
示例#4
0
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}})
示例#5
0
    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)
示例#6
0
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')
示例#7
0
    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)
示例#8
0
 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
示例#9
0
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')
示例#10
0
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)
示例#11
0
    def get_context_data(self, request, profile):
        ban = get_user_ban(profile)

        request.frontend_context['PROFILE_BAN'] = BanDetailsSerializer(ban).data

        return {
            'ban': ban,
        }
示例#12
0
    def get_context_data(self, request, profile):
        ban = get_user_ban(profile)

        request.frontend_context['PROFILE_BAN'] = BanDetailsSerializer(ban).data

        return {
            'ban': ban,
        }
示例#13
0
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
    })
示例#14
0
    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)
示例#15
0
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,
    })
示例#16
0
    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({})
示例#17
0
 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
示例#18
0
文件: profile.py 项目: nescode/Misago
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,
    })
示例#19
0
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,
    })
示例#20
0
文件: users.py 项目: Didan/Misago
    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({})
示例#21
0
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
    })
示例#22
0
    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 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)
示例#24
0
    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)
示例#25
0
    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)
示例#26
0
    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))
示例#27
0
    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)
示例#28
0
    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)
示例#29
0
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)
示例#30
0
    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))
示例#31
0
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)
示例#32
0
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
                  })
示例#33
0
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)})
示例#34
0
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}
    )
示例#35
0
文件: utils.py 项目: jasonlife/Misago
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
示例#36
0
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
示例#37
0
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})
示例#38
0
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
示例#39
0
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})
示例#40
0
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,
            },
        }
    )
示例#41
0
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
示例#42
0
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
示例#43
0
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
        })
示例#44
0
    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',
            )
示例#45
0
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)
示例#46
0
文件: auth.py 项目: qhhonx/Misago
    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',
            )
示例#47
0
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')
示例#48
0
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)
示例#49
0
 def get_user_ban(self, user):
     if user.is_staff:
         return None
     return get_user_ban(user)
示例#50
0
 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')
示例#51
0
 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)
示例#52
0
 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)
示例#53
0
 def confirm_user_not_banned(self, user):
     self.user_ban = get_user_ban(user)
     if self.user_ban:
         raise ValidationError('', code='banned')