Browse Source

sign in and middleware tests for admin access via #639

Rafał Pitoń 8 years ago
parent
commit
395b166e7d

+ 1 - 1
misago/admin/auth.py

@@ -21,7 +21,7 @@ def is_admin_session(request):
     if request.user.is_anonymous():
     if request.user.is_anonymous():
         return False
         return False
 
 
-    if not (request.user.is_staff and request.user.is_superuser):
+    if not request.user.is_staff:
         return False
         return False
 
 
     admin_token = request.session.get(KEY_TOKEN)
     admin_token = request.session.get(KEY_TOKEN)

+ 93 - 7
misago/admin/tests/test_admin_views.py

@@ -54,15 +54,64 @@ class AdminLoginViewTests(TestCase):
             reverse('misago:admin:index'),
             reverse('misago:admin:index'),
             data={'username': 'Nope', 'password': 'Nope'})
             data={'username': 'Nope', 'password': 'Nope'})
 
 
-        self.assertContains(response, 'Login or password is incorrect.')
-        self.assertContains(response, 'Sign in')
-        self.assertContains(response, 'Username or e-mail')
-        self.assertContains(response, 'Password')
+        self.assertContains(response, "Login or password is incorrect.")
+        self.assertContains(response, "Sign in")
+        self.assertContains(response, "Username or e-mail")
+        self.assertContains(response, "Password")
+
+    def test_login_denies_non_staff_non_superuser(self):
+        """login rejects user thats non staff and non superuser"""
+        User = get_user_model()
+        user = User.objects.create_user('Bob', 'bob@test.com', 'Pass.123')
+
+        user.is_staff = False
+        user.is_superuser = False
+        user.save()
+
+        response = self.client.post(
+            reverse('misago:admin:index'),
+            data={'username': 'Bob', 'password': 'Pass.123'})
+
+        self.assertContains(response, "Your account does not have admin privileges.")
+
+    def test_login_denies_non_staff_superuser(self):
+        """login rejects user thats non staff and superuser"""
+        User = get_user_model()
+        user = User.objects.create_user('Bob', 'bob@test.com', 'Pass.123')
+
+        user.is_staff = False
+        user.is_superuser = True
+        user.save()
+
+        response = self.client.post(
+            reverse('misago:admin:index'),
+            data={'username': 'Bob', 'password': 'Pass.123'})
+
+        self.assertContains(response, "Your account does not have admin privileges.")
+
+    def test_login_signs_in_staff_non_superuser(self):
+        """login passess user thats staff and non superuser"""
+        User = get_user_model()
+        user = User.objects.create_user('Bob', 'bob@test.com', 'Pass.123')
+
+        user.is_staff = True
+        user.is_superuser = False
+        user.save()
 
 
-    def test_login_returns_200_on_valid_post(self):
-        """form handles valid data correctly"""
+        response = self.client.post(
+            reverse('misago:admin:index'),
+            data={'username': 'Bob', 'password': 'Pass.123'})
+
+        self.assertEqual(response.status_code, 302)
+
+    def test_login_signs_in_staff_superuser(self):
+        """login passess user thats staff and superuser"""
         User = get_user_model()
         User = get_user_model()
-        User.objects.create_superuser('Bob', 'bob@test.com', 'Pass.123')
+        user = User.objects.create_user('Bob', 'bob@test.com', 'Pass.123')
+
+        user.is_staff = True
+        user.is_superuser = True
+        user.save()
 
 
         response = self.client.post(
         response = self.client.post(
             reverse('misago:admin:index'),
             reverse('misago:admin:index'),
@@ -95,6 +144,43 @@ class AdminLogoutTests(AdminTestCase):
         self.assertContains(response, "Sign in")
         self.assertContains(response, "Sign in")
 
 
 
 
+class AdminViewAccessTests(AdminTestCase):
+    def test_admin_denies_non_staff_non_superuser(self):
+        """admin middleware rejects user thats non staff and non superuser"""
+        self.user.is_staff = False
+        self.user.is_superuser = False
+        self.user.save()
+
+        response = self.client.get(reverse('misago:admin:index'))
+        self.assertContains(response, "Sign in")
+
+    def test_admin_denies_non_staff_superuser(self):
+        """admin middleware rejects user thats non staff and superuser"""
+        self.user.is_staff = False
+        self.user.is_superuser = True
+        self.user.save()
+
+        response = self.client.get(reverse('misago:admin:index'))
+        self.assertContains(response, "Sign in")
+
+    def test_admin_passess_in_staff_non_superuser(self):
+        """admin middleware passess user thats staff and non superuser"""
+        self.user.is_staff = True
+        self.user.is_superuser = False
+        self.user.save()
+
+        response = self.client.get(reverse('misago:admin:index'))
+        self.assertContains(response, self.user.username)
+
+    def test_admin_passess_in_staff_superuser(self):
+        """admin middleware passess user thats staff and superuser"""
+        self.user.is_staff = True
+        self.user.is_superuser = True
+        self.user.save()
+
+        response = self.client.get(reverse('misago:admin:index'))
+        self.assertContains(response, self.user.username)
+
 class AdminIndexViewTests(AdminTestCase):
 class AdminIndexViewTests(AdminTestCase):
     def test_view_returns_200(self):
     def test_view_returns_200(self):
         """admin index view returns 200"""
         """admin index view returns 200"""

+ 27 - 35
misago/users/forms/auth.py

@@ -24,15 +24,11 @@ class MisagoAuthMixin(object):
     def confirm_user_active(self, user):
     def confirm_user_active(self, user):
         if user.requires_activation_by_admin:
         if user.requires_activation_by_admin:
             raise ValidationError(
             raise ValidationError(
-                self.error_messages['inactive_admin'],
-                code='inactive_admin',
-            )
+                self.error_messages['inactive_admin'], code='inactive_admin')
 
 
         if user.requires_activation_by_user:
         if user.requires_activation_by_user:
             raise ValidationError(
             raise ValidationError(
-                self.error_messages['inactive_user'],
-                code='inactive_user',
-            )
+                self.error_messages['inactive_user'], code='inactive_user')
 
 
     def confirm_user_not_banned(self, user):
     def confirm_user_not_banned(self, user):
         self.user_ban = get_user_ban(user)
         self.user_ban = get_user_ban(user)
@@ -57,31 +53,33 @@ class AuthenticationForm(MisagoAuthMixin, BaseAuthenticationForm):
     Base class for authenticating users, Floppy-forms and
     Base class for authenticating users, Floppy-forms and
     Misago login field comliant
     Misago login field comliant
     """
     """
-    username = forms.CharField(label=_("Username or e-mail"),
-                               required=False,
-                               max_length=254)
-    password = forms.CharField(label=_("Password"), required=False,
-                               widget=forms.PasswordInput)
+    username = forms.CharField(
+        label=_("Username or e-mail"),
+        required=False,
+        max_length=254
+    )
+    password = forms.CharField(
+        label=_("Password"),
+        required=False,
+        widget=forms.PasswordInput
+    )
 
 
     def clean(self):
     def clean(self):
         username = self.cleaned_data.get('username')
         username = self.cleaned_data.get('username')
         password = self.cleaned_data.get('password')
         password = self.cleaned_data.get('password')
 
 
         if username and password:
         if username and password:
-            self.user_cache = authenticate(username=username,
-                                           password=password)
+            self.user_cache = authenticate(
+                username=username, password=password)
+
             if self.user_cache is None or not self.user_cache.is_active:
             if self.user_cache is None or not self.user_cache.is_active:
                 raise ValidationError(
                 raise ValidationError(
-                    self.error_messages['invalid_login'],
-                    code='invalid_login',
-                )
+                    self.error_messages['invalid_login'], code='invalid_login')
             else:
             else:
                 self.confirm_login_allowed(self.user_cache)
                 self.confirm_login_allowed(self.user_cache)
         else:
         else:
             raise ValidationError(
             raise ValidationError(
-                self.error_messages['empty_data'],
-                code='empty_data',
-            )
+                self.error_messages['empty_data'], code='empty_data')
 
 
         return self.cleaned_data
         return self.cleaned_data
 
 
@@ -96,16 +94,14 @@ class AdminAuthenticationForm(AuthenticationForm):
     def __init__(self, *args, **kwargs):
     def __init__(self, *args, **kwargs):
         self.error_messages.update({
         self.error_messages.update({
             'not_staff': _("Your account does not have admin privileges.")
             'not_staff': _("Your account does not have admin privileges.")
-            })
+        })
 
 
         super(AdminAuthenticationForm, self).__init__(*args, **kwargs)
         super(AdminAuthenticationForm, self).__init__(*args, **kwargs)
 
 
     def confirm_login_allowed(self, user):
     def confirm_login_allowed(self, user):
         if not user.is_staff:
         if not user.is_staff:
             raise forms.ValidationError(
             raise forms.ValidationError(
-                self.error_messages['not_staff'],
-                code='not_staff',
-            )
+                self.error_messages['not_staff'], code='not_staff')
 
 
 
 
 class GetUserForm(MisagoAuthMixin, forms.Form):
 class GetUserForm(MisagoAuthMixin, forms.Form):
@@ -117,15 +113,13 @@ class GetUserForm(MisagoAuthMixin, forms.Form):
         email = data.get('email')
         email = data.get('email')
         if not email or len(email) > 250:
         if not email or len(email) > 250:
             raise forms.ValidationError(
             raise forms.ValidationError(
-                _("Enter e-mail address."),
-                code='empty_email')
+                _("Enter e-mail address."), code='empty_email')
 
 
         try:
         try:
             validate_email(email)
             validate_email(email)
         except forms.ValidationError:
         except forms.ValidationError:
             raise forms.ValidationError(
             raise forms.ValidationError(
-                _("Entered e-mail is invalid."),
-                code='invalid_email')
+                _("Entered e-mail is invalid."), code='invalid_email')
 
 
         try:
         try:
             User = get_user_model()
             User = get_user_model()
@@ -133,8 +127,7 @@ class GetUserForm(MisagoAuthMixin, forms.Form):
             self.user_cache = user
             self.user_cache = user
         except User.DoesNotExist:
         except User.DoesNotExist:
             raise forms.ValidationError(
             raise forms.ValidationError(
-                _("No user with this e-mail exists."),
-                code='not_found')
+                _("No user with this e-mail exists."), code='not_found')
 
 
         self.confirm_allowed(user)
         self.confirm_allowed(user)
 
 
@@ -150,14 +143,13 @@ class ResendActivationForm(GetUserForm):
 
 
         if not user.requires_activation:
         if not user.requires_activation:
             message = _("%(user)s, your account is already active.")
             message = _("%(user)s, your account is already active.")
-            raise forms.ValidationError(message % username_format,
-                                        code='already_active')
+            raise forms.ValidationError(
+                message % username_format, code='already_active')
 
 
         if user.requires_activation_by_admin:
         if user.requires_activation_by_admin:
-            message = _("%(user)s, only administrator may activate "
-                        "your account.")
-            raise forms.ValidationError(message % username_format,
-                                        code='inactive_admin')
+            message = _("%(user)s, only administrator may activate your account.")
+            raise forms.ValidationError(
+                message % username_format, code='inactive_admin')
 
 
 
 
 class ResetPasswordForm(GetUserForm):
 class ResetPasswordForm(GetUserForm):

+ 2 - 0
misago/users/models/user.py

@@ -201,10 +201,12 @@ class User(AbstractBaseUser, PermissionsMixin):
     rank = models.ForeignKey('Rank', null=True, blank=True, on_delete=models.deletion.PROTECT)
     rank = models.ForeignKey('Rank', null=True, blank=True, on_delete=models.deletion.PROTECT)
     title = models.CharField(max_length=255, null=True, blank=True)
     title = models.CharField(max_length=255, null=True, blank=True)
     requires_activation = models.PositiveIntegerField(default=ACTIVATION_REQUIRED_NONE)
     requires_activation = models.PositiveIntegerField(default=ACTIVATION_REQUIRED_NONE)
+
     is_staff = models.BooleanField(_('staff status'),
     is_staff = models.BooleanField(_('staff status'),
         default=False,
         default=False,
         help_text=_('Designates whether the user can log into admin sites.'),
         help_text=_('Designates whether the user can log into admin sites.'),
     )
     )
+
     roles = models.ManyToManyField('misago_acl.Role')
     roles = models.ManyToManyField('misago_acl.Role')
     acl_key = models.CharField(max_length=12, null=True, blank=True)
     acl_key = models.CharField(max_length=12, null=True, blank=True)