aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to 'okupy/common')
-rw-r--r--okupy/common/auth.py39
-rw-r--r--okupy/common/ldap_helpers.py8
2 files changed, 45 insertions, 2 deletions
diff --git a/okupy/common/auth.py b/okupy/common/auth.py
index aa238fc..9dcf554 100644
--- a/okupy/common/auth.py
+++ b/okupy/common/auth.py
@@ -5,14 +5,53 @@ from django.contrib.auth.backends import ModelBackend
from django.db import IntegrityError
from okupy.accounts.models import LDAPUser
+from okupy.common.ldap_helpers import get_bound_ldapuser
from OpenSSL.crypto import load_certificate, FILETYPE_PEM
+import ldap
import paramiko
import base64
+class LDAPAuthBackend(ModelBackend):
+ """
+ Authentication backend that authenticates against LDAP password.
+ If authentication succeeds, it sets up secondary password
+ for the session.
+ """
+
+ def authenticate(self, request, username, password):
+ # LDAP is case- and whitespace-insensitive
+ # we do normalization to avoid duplicate django db entries
+ # and help mockldap
+ username = username.lower().strip()
+
+ try:
+ bound_ldapuser = get_bound_ldapuser(
+ request=request,
+ username=username,
+ password=password)
+
+ with bound_ldapuser as u:
+ UserModel = get_user_model()
+ attr_dict = {
+ UserModel.USERNAME_FIELD: u.username
+ }
+
+ user = UserModel(**attr_dict)
+ try:
+ user.save()
+ except IntegrityError:
+ user = UserModel.objects.get(**attr_dict)
+ return user
+ except ldap.INVALID_CREDENTIALS:
+ return None
+ except ldap.STRONG_AUTH_REQUIRED:
+ return None
+
+
class SSLCertAuthBackend(ModelBackend):
"""
Authentication backend taht uses client certificate information.
diff --git a/okupy/common/ldap_helpers.py b/okupy/common/ldap_helpers.py
index 43f3e3e..c8ac5dd 100644
--- a/okupy/common/ldap_helpers.py
+++ b/okupy/common/ldap_helpers.py
@@ -8,14 +8,18 @@ from okupy import OkupyError
from okupy.accounts.models import LDAPUser
from okupy.crypto.ciphers import cipher
+from django.conf import settings #debug
+from django.db import connections
-def get_bound_ldapuser(request, password=None):
+
+def get_bound_ldapuser(request, password=None, username=None):
"""
Get LDAPUser with connection bound to the current user.
Uses either provided password or the secondary password saved
in session.
"""
- username = request.user.username
+ if not username:
+ username = request.user.username
if not password:
try:
password = b64encode(cipher.decrypt(