From: Alex Dehnert Date: Sun, 18 Dec 2011 05:49:59 +0000 (-0500) Subject: Function to create an MIT user with LDAP data X-Git-Url: https://snippets.scripts.mit.edu/gitweb.cgi/Scripts/git/.git/commitdiff_plain/d4bd5af8ca7dc0954e7886e45e7ff55e901113b6 Function to create an MIT user with LDAP data This adds a function get_or_create_mit_user. As with the "get_or_create" methods on managers, this returns an object satisfying some conditions, creating it if necessary. In this case, we return a User object that's populated using data from MIT's LDAP. If the user does not exist and cannot be found in LDAP, we raise an exception. --- diff --git a/__init__.py b/__init__.py index 6b72710..725d660 100644 --- a/__init__.py +++ b/__init__.py @@ -55,6 +55,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':