2017-10-14 19:36:13 +02:00
|
|
|
''' 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__():
|
|
|
|
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):
|
2017-10-15 17:09:14 +02:00
|
|
|
def hasCas(user):
|
2017-11-07 14:03:37 +01:00
|
|
|
if user.is_anonymous:
|
|
|
|
return False
|
2017-10-15 17:09:14 +02:00
|
|
|
return CasUser.objects.filter(user=user).count() > 0
|
|
|
|
|
2017-10-14 19:36:13 +02:00
|
|
|
def wrap(user, *args, **kwargs):
|
2017-10-15 17:09:14 +02:00
|
|
|
if not hasCas(user):
|
2017-10-14 19:36:13 +02:00
|
|
|
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()
|
|
|
|
|
|
|
|
|
|
|
|
def forceReevalRhosts(fct):
|
|
|
|
def wrap(req, *args, **kwargs):
|
|
|
|
evalRhostsPrivileges(req.user)
|
|
|
|
return fct(req, *args, **kwargs)
|
|
|
|
return wrap
|