106 lines
2.4 KiB
Python
106 lines
2.4 KiB
Python
""" Reads a .rhosts file """
|
|
|
|
from django.conf import settings
|
|
from django.contrib.auth.models import Group
|
|
|
|
from .models import CasUser
|
|
|
|
|
|
def hasUser(user, allowed_domains=[]):
|
|
"""Check that `user` appears in the rhosts file.
|
|
If `allowed_domains` is not empty, also checks that the user belongs to one
|
|
of the specified domains."""
|
|
|
|
def clearLine(line):
|
|
line = line.strip()
|
|
hashPos = line.find("#")
|
|
if hashPos >= 0:
|
|
line = line[:hashPos]
|
|
return line
|
|
|
|
with open(settings.RHOSTS_PATH, "r") as handle:
|
|
for line in handle:
|
|
line = clearLine(line)
|
|
if not line:
|
|
continue
|
|
|
|
spl = line.split()
|
|
if len(spl) != 2:
|
|
continue # Not a login line
|
|
|
|
domain, login = spl
|
|
if login != user: # Not the ones we're looking for
|
|
continue
|
|
|
|
if domain[:2] != "+@": # Not a valid domain
|
|
continue
|
|
domain = domain[2:]
|
|
|
|
if allowed_domains != [] and domain not in allowed_domains:
|
|
continue
|
|
|
|
return True
|
|
return False
|
|
|
|
|
|
def default_allowed(user):
|
|
return hasUser(user, allowed_domains=["eleves"])
|
|
|
|
|
|
class NoBOcalException(Exception):
|
|
def __str__(self):
|
|
return "The BOcal group was not created"
|
|
|
|
|
|
def bocalGroup():
|
|
qs = Group.objects.filter(name="BOcal")
|
|
if qs.count() != 1:
|
|
raise NoBOcalException
|
|
return qs[0]
|
|
|
|
|
|
def stripCasPrivileges(user):
|
|
user.groups.remove(bocalGroup())
|
|
user.is_staff = False
|
|
user.save()
|
|
|
|
|
|
def grantBOcalPrivileges(user):
|
|
user.is_staff = True
|
|
user.groups.add(bocalGroup())
|
|
user.save()
|
|
|
|
|
|
def requireCasUser(fct):
|
|
def hasCas(user):
|
|
if user.is_anonymous:
|
|
return False
|
|
return CasUser.objects.filter(user=user).count() > 0
|
|
|
|
def wrap(user, *args, **kwargs):
|
|
if not hasCas(user):
|
|
return
|
|
return fct(user, *args, **kwargs)
|
|
|
|
return wrap
|
|
|
|
|
|
@requireCasUser
|
|
def evalRhostsPrivileges(user):
|
|
if default_allowed(user.username):
|
|
grantBOcalPrivileges(user)
|
|
else:
|
|
stripCasPrivileges(user)
|
|
|
|
|
|
@requireCasUser
|
|
def logout(user):
|
|
stripCasPrivileges(user)
|
|
|
|
|
|
def forceReevalRhosts(fct):
|
|
def wrap(request, *args, **kwargs):
|
|
evalRhostsPrivileges(request.user)
|
|
return fct(request, *args, **kwargs)
|
|
|
|
return wrap
|