Skip to content

Commit

Permalink
(bans) : Add ban condition into login_required_ajax
Browse files Browse the repository at this point in the history
  • Loading branch information
srbh001 committed Oct 10, 2023
1 parent 60d1328 commit afbde9a
Show file tree
Hide file tree
Showing 8 changed files with 93 additions and 24 deletions.
4 changes: 2 additions & 2 deletions bans/admin.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from django.contrib import admin
from bans.models import SSOBans
from bans.models import SSOBan
# Register your models here.


class SSOBansAdmin(admin.ModelAdmin):
list_display = ('banned_user', 'banned_by','id')

admin.site.register(SSOBans, SSOBansAdmin)
admin.site.register(SSOBan, SSOBansAdmin)
18 changes: 18 additions & 0 deletions bans/migrations/0002_rename_ssobans_ssoban.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 3.2.16 on 2023-10-10 12:47

from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
('users', '0040_remove_userprofile_followed_communities'),
('bans', '0001_initial'),
]

operations = [
migrations.RenameModel(
old_name='SSOBans',
new_name='SSOBan',
),
]
20 changes: 20 additions & 0 deletions bans/migrations/0003_alter_ssoban_banned_by.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 3.2.16 on 2023-10-10 13:34

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('users', '0040_remove_userprofile_followed_communities'),
('bans', '0002_rename_ssobans_ssoban'),
]

operations = [
migrations.AlterField(
model_name='ssoban',
name='banned_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='banned_by', to='users.userprofile'),
),
]
12 changes: 4 additions & 8 deletions bans/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,19 @@
]


class SSOBans(models.Model):
class SSOBan(models.Model):
"""Bans imposed on students to access any SSO required View."""
id = models.UUIDField(primary_key=True, default=uuid4, blank=False)
banned_user = models.ForeignKey(to='users.UserProfile', related_name='banned_user', on_delete=models.CASCADE)
time_of_creation = models.DateTimeField(auto_now_add=True)
reason = models.CharField(max_length=30, choices = BAN_REASON_CHOICHES)
detailed_reason = models.TextField(blank=True)
duration_of_ban = models.CharField(max_length=20, choices = BAN_DURATION_CHOICES)
banned_by = models.ForeignKey(to = 'users.UserProfile', related_name='banned_by', on_delete=models.SET_NULL, null=True)
banned_by = models.ForeignKey(to = 'users.UserProfile', related_name='banned_by', on_delete=models.SET_NULL, null=True, blank=True)

def __str__(self) -> str:
return self.user

def save(self):
self.banned_user = self.banned_user.ldap_id

super.save()





4 changes: 2 additions & 2 deletions bans/serializers.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
"""Serializers for Bans """
from rest_framework import serializers
from users.serializers import UserProfileSerializer
from .models import SSOBans
from .models import SSOBan

class SSOBansSerializer(serializers.ModelSerializer):
banned_by = UserProfileSerializer(read_only = False, source = 'name')

class Meta:
model = SSOBans
model = SSOBan
fields = '__all__'
6 changes: 3 additions & 3 deletions bans/urls.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
"""URLs for Bans"""
from django.urls import path
from bans.views import SSOBansViewSet
from bans.views import SSOBanViewSet

urlpatterns =[
path('bans/', SSOBansViewSet.as_view(
path('bans/', SSOBanViewSet.as_view(
{'get':'list', 'post':'create'}
)),
path('bans/<pk>/', SSOBansViewSet.as_view({
path('bans/<pk>/', SSOBanViewSet.as_view({
'put': 'update', 'delete': 'destroy', 'get': 'retrieve', 'patch': 'update'
}))
]
16 changes: 8 additions & 8 deletions bans/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@


from users.models import UserProfile
from .models import SSOBans
from .models import SSOBan
from .serializers import SSOBansSerializer


# Create your views here.


class SSOBansViewSet(viewsets.ModelViewSet):
queryset = SSOBans.objects.all()
class SSOBanViewSet(viewsets.ModelViewSet):
queryset = SSOBan.objects.all()
serializer_class = SSOBansSerializer

@login_required_ajax
Expand All @@ -27,7 +27,7 @@ def list(self, request):
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
else:
return forbidden_no_privileges
return forbidden_no_privileges()

@login_required_ajax
def retrieve(self, request, pk):
Expand All @@ -37,7 +37,7 @@ def retrieve(self, request, pk):
serializer = self.get_serializer(instance)
return Response(serializer.data)
else:
return forbidden_no_privileges
return forbidden_no_privileges()

@login_required_ajax
def create(self, request):
Expand All @@ -62,7 +62,7 @@ def create(self, request):
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
return forbidden_no_privileges
return forbidden_no_privileges()

@login_required_ajax
def update(self, request, pk=None, *args, **kwargs):
Expand All @@ -77,7 +77,7 @@ def update(self, request, pk=None, *args, **kwargs):

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
return forbidden_no_privileges
return forbidden_no_privileges()

@login_required_ajax
def destroy(self, request, pk=None, *args, **kwargs):
Expand All @@ -86,6 +86,6 @@ def destroy(self, request, pk=None, *args, **kwargs):
instance.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
else:
return forbidden_no_privileges
return forbidden_no_privileges()


37 changes: 36 additions & 1 deletion roles/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,32 @@
from rest_framework.response import Response
from bodies.models import Body
from community.models import Community
from bans.models import SSOBan
from users.models import UserProfile
import datetime
from dateutil.relativedelta import relativedelta

def user_is_banned(profile):
try:
ban = SSOBan.objects.get(banned_user = profile.id)
current_time = datetime.datetime.now()
ban_created = ban.time_of_creation
ban_duration = ban.duration_of_ban

if ban_duration == 'Permanent':
return True

else:
duration_month = int(ban_duration.split(" ")[0])
banned_till = ban_created + relativedelta(months=duration_month)

if banned_till > current_time:
return True
return False
except SSOBan.DoesNotExist:
return False



def forbidden_no_privileges():
"""Forbidden due to insufficient privileges."""
Expand Down Expand Up @@ -63,7 +89,16 @@ def login_required_ajax(func):
@add_doc(func.__doc__)
def wrapper(*args, **kw):
if args[1].user.is_authenticated:
return func(*args, **kw)
user = args[1].user
profile = UserProfile.objects.get(user = user)
if not user_is_banned(profile):
return func(*args, **kw)
if user_is_banned:
return Response({
'message':'banned',
'detail' : 'your SSO has been banned/disabled'

})
return Response({
'message': 'unauthenticated',
'detail': 'Log in to continue!'
Expand Down

0 comments on commit afbde9a

Please sign in to comment.