This snippet implements an authentication backend for MoinMoin user accounts. If you have a MoinMoin running on the same server which has users, you can allow those users to sign into a Django site with the same username and password.
To use, define the following settings:
MOIN_DATA_DIR = "/path/to/moinmoin/data/dir"
AUTH_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'<this snippet module>.MoinMoinBackend',
)
# optional list of groups that authenticating users must be in
MOIN_AUTH_GROUPS = ["EditorGroup",]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | import re
import os
import base64
import hashlib
from django.conf import settings
from django.contrib.auth.models import User
class MoinMoinBackend:
"""
Authenticate based on MoinMoin users. Two settings control its function:
settings.MOIN_DATA_DIR: required
Full path to a MoinMoin installation's data directory. "user" and
"pages" should be members of this directory.
settings.MOIN_AUTH_GROUPS: optional
List of groups to verify that a user is in before authenticating.
e.g. ["EditorGroup", "AdminGroup"]
"""
def authenticate(self, username=None, password=None):
base = os.path.join(settings.MOIN_DATA_DIR, "user")
for filename in os.listdir(base):
fh = open(os.path.join(base, filename))
moin_user_file = fh.read()
fh.close()
if not re.search("^name=%s$" % username, moin_user_file, re.M):
continue
pw_enc = re.search("^enc_password=\{SSHA\}(.*)$", moin_user_file, re.M)
if not pw_enc:
continue
# This logic taken from MoinMoin.user.User._validatePassword
data = base64.decodestring(pw_enc.group(1))
salt = data[20:]
hash = hashlib.sha1(password)
hash.update(salt)
if hash.digest() != data[:20]:
return None
# Check that we're in the required groups, if any.
for group in getattr(settings, 'MOIN_AUTH_GROUPS', []):
fh = open(os.path.join(settings.MOIN_DATA_DIR, "pages", group, "current"))
rev = fh.read().strip()
fh.close()
fh = open(os.path.join(settings.MOIN_DATA_DIR, "pages", group, "revisions", rev))
group_members = fh.read()
fh.close()
if not re.search("(^|\s)%s(\s|$)" % username, group_members, re.M):
return None
return User.objects.get_or_create(username=username)[0]
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 8 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
Please login first before commenting.