100 lines
2.3 KiB
Python
100 lines
2.3 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__():
|
||
|
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 wrap(user, *args, **kwargs):
|
||
|
qs = CasUser.objects.filter(user=user)
|
||
|
if not qs.count() > 0:
|
||
|
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
|