PCv5/app/utils/ldap.py

98 lines
3.2 KiB
Python

import ldap
from ldap.modlist import addModlist, modifyModlist
from app.utils.unicode_names import normalize
from config import V5Config
def get_member(username):
""" Get informations about member"""
username = normalize(username) # Never safe enough
conn = ldap.initialize("ldap://localhost")
# Search for user
r = conn.search_s(f"{V5Config.LDAP_ENV},{V5Config.LDAP_ROOT}",
ldap.SCOPE_SUBTREE, f'(cn={username})')
if len(r) > 0:
return r[0]
else:
return None
def edit(old_username, new_member):
""" Edit a user. Fields is {'name': ['value'], …} """
old_username = normalize(old_username)
conn = ldap.initialize("ldap://localhost")
# Connect as root
conn.simple_bind_s(f'cn=ldap-root,{V5Config.LDAP_ROOT}',
V5Config.LDAP_PASSWORD)
# Create values fields
old_dn = f'cn={old_username},{V5Config.LDAP_ENV},{V5Config.LDAP_ROOT}'
new_dn = f'cn={new_member.norm}'
new_values = [
(ldap.MOD_REPLACE, 'sn', [new_member.norm.encode('utf-8')]),
(ldap.MOD_REPLACE, 'displayName', [new_member.name.encode('utf-8')]),
(ldap.MOD_REPLACE, 'mail', [new_member.email.encode('utf-8')]),
]
conn.modify_s(old_dn, new_values)
conn.rename_s(old_dn, new_dn)
def set_email(user, email):
pass
def set_password(user, password):
""" Set password for a user. """
conn = ldap.initialize("ldap://localhost")
# Connect as root
conn.simple_bind_s(f'cn=ldap-root,{V5Config.LDAP_ROOT}',
V5Config.LDAP_PASSWORD)
conn.passwd_s(f"cn={user.norm},{V5Config.LDAP_ENV},{V5Config.LDAP_ROOT}",
None, password)
def check_password(user, password):
""" Try to login a user through LDAP register. """
conn = ldap.initialize("ldap://localhost")
try:
conn.simple_bind_s(f"cn={user.norm},{V5Config.LDAP_ENV}," \
f"{V5Config.LDAP_ROOT}", password)
except ldap.INVALID_CREDENTIALS:
return False
return True
def add_member(member):
""" Add a member to LDAP register. Fields must have been sanitized! """
if get_member(member.norm) is not None:
print("User already exists")
return
conn = ldap.initialize("ldap://localhost")
# Connect as root
conn.simple_bind_s(f'cn=ldap-root,{V5Config.LDAP_ROOT}',
V5Config.LDAP_PASSWORD)
# Create fields
dn = f'cn={member.norm},{V5Config.LDAP_ENV},{V5Config.LDAP_ROOT}'
modlist = addModlist({
'objectClass': [bytes('inetOrgPerson', 'UTF8')],
'cn': [bytes(member.norm, 'UTF8')],
'sn': [bytes(member.norm, 'UTF8')],
'displayName': [bytes(member.name, 'UTF8')],
'mail': [bytes(member.email, 'UTF8')],
'uid': [bytes(str(member.id), 'UTF8')],
'userPassword': [bytes("", 'UTF8')]
})
# Add the member
conn.add_s(dn, modlist)
def delete_member(member):
""" Remove a member from LDAP register """
conn = ldap.initialize("ldap://localhost")
# Connect as root
conn.simple_bind_s(f'cn=ldap-root,{V5Config.LDAP_ROOT}',
V5Config.LDAP_PASSWORD)
# Create fields
dn = f'cn={member.norm},{V5Config.LDAP_ENV},{V5Config.LDAP_ROOT}'
# Delete the user
conn.delete_s(dn)