]> sipb.mit.edu Git - snippets/.git/blobdiff - __init__.py
Wrappers for safely calling commands in a new PAG
[snippets/.git] / __init__.py
index 6b727108c8093c40e2c099ad3838adaa2a3fff53..8f9356d04f4e774aa48ab88b9456a44a9798450a 100644 (file)
@@ -1,3 +1,4 @@
+import os
 import subprocess
 import ldap
 import ldap.filter
@@ -9,6 +10,8 @@ from django.contrib.auth import REDIRECT_FIELD_NAME
 from django.http import HttpResponseRedirect
 from django.contrib import auth
 from django.core.exceptions import ObjectDoesNotExist
+from django.core.validators import URLValidator, ValidationError
+
 import settings
 
 def zephyr(msg, clas='message', instance='log', rcpt='nobody',):
@@ -18,6 +21,41 @@ def zephyr(msg, clas='message', instance='log', rcpt='nobody',):
     )
     proc.communicate(msg)
 
+def UrlOrAfsValidator(value):
+    if value.startswith('/mit/') or value.startswith('/afs/'):
+        return
+    else:
+        try:
+            URLValidator()(value)
+        except ValidationError:
+            raise ValidationError('Provide a valid URL or AFS path')
+
+def pag_check_helper(fn, args, aklog=False, ccname=None, **kwargs):
+    if 'executable' in kwargs:
+        raise ValueError('"executable" not supported with pag_check_*')
+
+    env = None
+    if 'env' in kwargs:
+        env = kwargs['env']
+        del kwargs['env']
+    if ccname:
+        if env is not None:
+            env = dict(env)
+        else:
+            env = dict(os.environ)
+        env['KRB5CCNAME'] = ccname
+
+    pagsh_cmd = 'exec "$@"'
+    if aklog: pagsh_cmd = "aklog && " + pagsh_cmd
+    args = ['pagsh', '-c', pagsh_cmd, 'exec', ] + args
+
+    return fn(args, env=env, **kwargs)
+
+def pag_check_call(args, **kwargs):
+    return pag_check_helper(subprocess.check_call, args, **kwargs)
+def pag_check_output(args, **kwargs):
+    return pag_check_helper(subprocess.check_output, args, **kwargs)
+
 class ScriptsRemoteUserMiddleware(RemoteUserMiddleware):
     header = 'SSL_CLIENT_S_DN_Email'
 
@@ -41,7 +79,10 @@ class ScriptsRemoteUserBackend(RemoteUserBackend):
         if len(result) == 1:
             user.first_name = result[0][1]['givenName'][0]
             user.last_name = result[0][1]['sn'][0]
-            user.email = result[0][1]['mail'][0]
+            try:
+                user.email = result[0][1]['mail'][0]
+            except KeyError:
+                user.email = username + '@mit.edu'
             try:
                 user.groups.add(auth.models.Group.objects.get(name='mit'))
             except ObjectDoesNotExist:
@@ -55,6 +96,24 @@ class ScriptsRemoteUserBackend(RemoteUserBackend):
         user.save()
         return user
 
+def get_or_create_mit_user(username, ):
+    """
+    Given an MIT username, return a Django user object for them.
+    If necessary, create (and save) the Django user for them.
+    If the MIT user doesn't exist, raises ValueError.
+    """
+    user, created = auth.models.User.objects.get_or_create(username=username, )
+    if created:
+        backend = ScriptsRemoteUserBackend()
+        # Raises ValueError if the user doesn't exist
+        try:
+            return backend.configure_user(user), created
+        except ValueError:
+            user.delete()
+            raise
+    else:
+        return user, created
+
 def scripts_login(request, **kwargs):
     host = request.META['HTTP_HOST'].split(':')[0]
     if host == 'localhost':