settings: Enable (phpbb) authentication.
[matthijs/projects/dorestad-bookings.git] / auth.py
diff --git a/auth.py b/auth.py
new file mode 100644 (file)
index 0000000..00c106d
--- /dev/null
+++ b/auth.py
@@ -0,0 +1,107 @@
+from django.conf import settings
+from django.contrib.auth.models import User, check_password
+import md5
+import MySQLdb
+
+
+"""
+This auth backend allows django to authenticate against an external phpbb
+database. If authentication is successful, the corresponding User from the
+normal django database is returned (linked on the username field). If no such
+User exists, it is created automatically.
+
+This class uses the following variables from you django settings:
+    PHPBB_DATABASE_HOST
+    PHPBB_DATABASE_PORT
+    PHPBB_DATABASE_USER
+    PHPBB_DATABASE_PASSWORD
+    PHPBB_DATABASE_NAME
+
+If any of these settings are missing, the corresponding setting from Django's
+own database settings are used. This means, that, usually, you only have to
+specify the database name where phpbb lives.
+"""
+class PhpBBBackend:
+    def connect(self):
+        host     = getattr(settings, 'PHPBB_DATABASE_HOST',     settings.DATABASE_HOST)
+        port     = getattr(settings, 'PHPBB_DATABASE_PORT',     settings.DATABASE_PORT)
+        user     = getattr(settings, 'PHPBB_DATABASE_USER',     settings.DATABASE_USER)
+        password = getattr(settings, 'PHPBB_DATABASE_PASSWORD', settings.DATABASE_PASSWORD)
+        name     = getattr(settings, 'PHPBB_DATABASE_NAME',     settings.DATABASE_NAME)
+
+        # This code was shamelessly stolen from
+        # django.db.backends.mysql.base.cursor
+        kwargs = {
+            #'conv': django_conversions,
+            'charset': 'utf8',
+            'use_unicode': False,
+        }
+        if user:
+            kwargs['user'] = user
+        if name:
+            kwargs['db'] = name
+        if password:
+            kwargs['passwd'] = password
+        if host.startswith('/'):
+            kwargs['unix_socket'] = host
+        elif host:
+            kwargs['host'] = host
+        if port:
+            kwargs['port'] = int(port)
+
+        conn = MySQLdb.connect (**kwargs)
+        # End stolen code
+
+        return conn
+
+    def check_login(self, username, password):
+        conn = self.connect()
+
+        # Get some data
+        cursor = conn.cursor ()
+        cursor.execute ("SELECT user_password,user_email FROM users WHERE username=%s", username)
+
+        # No data? No login.
+        if (cursor.rowcount == 0):
+            conn.close()
+            return False
+       
+        # Check password
+        row = cursor.fetchone()
+        conn.close()
+
+        if (md5.new(password).hexdigest() == row[0]):
+            return row[1]
+        else:
+            return False
+            
+
+    """
+    Authenticate against a PhpBB database.
+
+    Most of this code has been taken from Django's user auth tutorial.
+    """
+    def authenticate(self, username=None, password=None):
+        email = self.check_login(username, password)
+        if email:
+            try:
+                user = User.objects.get(username=username)
+            except User.DoesNotExist:
+                # Create a new user. Note that we can set password
+                # to anything, because it won't be checked; the password
+                # from settings.py will.
+                user = User(username=username, password='get from settings.py')
+                user.email = email
+                user.set_unusable_password()
+                user.save()
+            return user
+        else:
+            return None
+
+    def get_user(self, user_id):
+        try:
+            return User.objects.get(pk=user_id)
+        except User.DoesNotExist:
+            return None
+    
+# vim: set sts=4 sw=4 expandtab: