summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAlexander Sulfrian <alex@spline.inf.fu-berlin.de>2013-09-04 15:30:25 +0000
committerpad <pad@vm-pad-b.spline.inf.fu-berlin.de>2013-09-04 15:40:52 +0000
commit6ef92894a3a0c693837f6152aee03a64d8d44659 (patch)
tree2af0080ae607b94c52c7992d0a837f125bfbc408
parent2c82353eb617feed964a6a1ae97b32678d43a714 (diff)
downloadpadlite-teams-6ef92894a3a0c693837f6152aee03a64d8d44659.tar.gz
padlite-teams-6ef92894a3a0c693837f6152aee03a64d8d44659.tar.bz2
padlite-teams-6ef92894a3a0c693837f6152aee03a64d8d44659.zip
auth: add custom flask_peewee auth module for ldap auth
-rw-r--r--auth.py59
-rw-r--r--settings.py.default5
2 files changed, 64 insertions, 0 deletions
diff --git a/auth.py b/auth.py
new file mode 100644
index 0000000..0ab23cc
--- /dev/null
+++ b/auth.py
@@ -0,0 +1,59 @@
+from flask_peewee.auth import Auth
+from models import User
+from app import app, db, pad
+from datetime import datetime
+import ldap
+
+class LdapAuth(Auth):
+ def get_user_model(self):
+ return User
+
+ def authenticate(self, username, password):
+ ldap.protocol_version = 3
+ l = ldap.initialize(app.config['LDAP']['host'])
+ l.set_option( ldap.OPT_X_TLS_DEMAND, True )
+ try:
+ user_dn = self._format_dn([('uid', username)])
+ l.simple_bind_s(user_dn, password)
+ except ldap.INVALID_CREDENTIALS:
+ return False
+
+ try:
+ user = User.get(User.username == username)
+ except User.DoesNotExist:
+ user_data = l.search_s(user_dn, ldap.SCOPE_BASE)
+ if (len(user_data) != 1):
+ return False
+
+ (dn, user_data) = user_data[0]
+ user = User.create(
+ username = username,
+ email = user_data['mail'][0],
+ api_id = pad.createAuthorIfNotExistsFor(user_dn, username))
+
+ return user
+
+ def login_user(self, user):
+ user.last_login = datetime.now()
+ user.save()
+ super(LdapAuth, self).login_user(user)
+
+ def _format_dn(self, attr, with_base_dn = True):
+ if with_base_dn:
+ attr.extend(app.config['LDAP']['base_dn'])
+
+ dn = ['%s=%s' % (item[0], self._escape(item[1])) for item in attr]
+
+ return ','.join(dn)
+
+ def _escape(self, s, wildcard=False):
+ chars_to_escape = ['\\',',','=','+','<','>',';','"','\'','#','(',')','\0']
+
+ if not wildcard:
+ chars_to_escape.append('*')
+
+ escape = lambda x,y: x.replace(y,'\%02X' % ord(y))
+
+ return reduce(escape, chars_to_escape, s)
+
+auth = LdapAuth(app, db, user_model=User)
diff --git a/settings.py.default b/settings.py.default
index 902f39e..3379f94 100644
--- a/settings.py.default
+++ b/settings.py.default
@@ -3,6 +3,11 @@ PAD = {
'host': 'localhost'
}
+LDAP = {
+ 'host': 'ldaps://host',
+ 'base_dn': [('ou', 'people'), ('dc', 'example'), ('dc', 'org')],
+}
+
DATABASE = {
'name': 'example.db',
'engine': 'peewee.SqliteDatabase',