Cleanup, add modlist

This commit is contained in:
Nico Schottelius 2019-01-27 13:00:45 +01:00
parent 93677e6ad6
commit 2fd7bf3041

View file

@ -22,6 +22,7 @@ import os
# Use ldap, like django_auth_backend
import ldap
import ldap.modlist as modlist
from django.conf import settings
@ -46,36 +47,43 @@ class LDAP(object):
if settings.AUTH_LDAP_START_TLS:
self.conn.start_tls_s()
print("{} {} {}".format(self.uri, self.user, self.password))
self.conn.bind_s(self.user, self.password)
def check_user_exists(self, username):
exists = False
result = self.conn.search_s(self.search_base,
self.search_scope,
self.dn.format(username))
if not len(result) == 0:
return True
else:
return False
if len(result) > 0:
exists = True
return exists
def create_user(self, user, password, firstname, lastname, email):
dn = self.dn.format(user)
modlist = {
"objectClass": ["inetOrgPerson", "posixAccount", "ldapPublickey"],
"uid": [user],
"sn": [lastname],
"givenName": [firstname],
"cn": ["{} {}".format(firstname, lastname)],
"displayName": ["{} {}".format(firstname, lastname)],
"uidNumber": ["{}".format(self.get_new_uid_number(conn))],
"gidNumber": [self.gid],
"loginShell": ["/bin/bash"],
"homeDirectory": ["/home/{}".format(user)],
"mail": email,
"userPassword": password
attr = {
"objectClass": ["inetOrgPerson".encode("utf-8"),
"posixAccount".encode("utf-8"),
"ldapPublickey".encode("utf-8")],
"uid": [user.encode("utf-8")],
"sn": [lastname.encode("utf-8")],
"givenName": [firstname.encode("utf-8")],
"cn": ["{} {}".format(firstname, lastname).encode("utf-8")],
"displayName": ["{} {}".format(firstname, lastname).encode("utf-8")],
"uidNumber": ["{}".format(self.get_new_uid_number()).encode("utf-8")],
"gidNumber": [self.gid.encode("utf-8")],
"loginShell": ["/bin/bash".encode("utf-8")],
"homeDirectory": ["/home/{}".format(user).encode("utf-8")],
"mail": email.encode("utf-8"),
"userPassword": password.encode("utf-8")
}
result = self.conn.add_s(dn, ldap.modlist.addModlist(modlist))
ldif = modlist.addModlist(attr)
print("just before: {} {}".format(dn, ldif))
return self.conn.add_s(dn, ldif)
def get_new_uid_number(self):
uidlist = [0]
@ -83,8 +91,8 @@ class LDAP(object):
for result in self.conn.search_s(self.search_base,
self.search_scope,
self.search_filter):
uidlist.append(int(result[1]['uidNumber'][0]))
if 'uidNumber' in result[1]:
uidlist.append(int(result[1]['uidNumber'][0]))
return sorted(uidlist)[-1] + 1
@ -119,7 +127,6 @@ class Register(View):
if username == "" or not username:
return render(request, 'error.html', { 'urlname': urlname, 'service': service, 'error': 'Please supply a username.' } )
if l.check_user_exists(username):
return render(request, 'error.html', { 'urlname': urlname, 'service': service, 'error': 'User already exists.' } )
@ -148,8 +155,6 @@ class Register(View):
# so nothing strange happens if there are escapable chars
pwd = r'%s' % password1
l = LDAP()
try:
l.create_user(username, pwd, firstname, lastname, email)
except Exception as e: