from server import *
import re

LDAP_USERRE = re.compile(r'[^a-z0-9]')
if 'LDAP_HOST' in config:
	import ldap3

	def ldapauth(user, password):
		user = LDAP_USERRE.sub(r'', user.lower())
		try:
			conn = ldap3.Connection(ldap3.Server(config['LDAP_HOST'], port=config['LDAP_PORT'], use_ssl=True), 'fsmpi\\%s'%user, password, auto_bind=True, check_names=False)
		except ldap3.core.exceptions.LDAPBindError:
			return {}, []
		conn.search("cn=users,dc=fsmpi,dc=rwth-aachen,dc=de", "(cn=%s)"%user, attributes=['memberOf', 'givenName', 'sn'])
		info = {'uid': user, 'givenName': conn.response[0]['attributes']['givenName'][0], 'sn': conn.response[0]['attributes']['sn'][0]}
		groups = [g.split(',')[0].split('=')[-1] for g in conn.response[0]['attributes']['memberOf']]
		conn.unbind()
		return info, groups

else:
	notldap = {
		'videoag':('videoag', ['fachschaft','videoag'], {'uid': 'videoag', 'givenName': 'Video', 'sn': 'Geier'}),
		'gustav':('passwort', ['fachschaft'], {'uid': 'gustav', 'givenName': 'Gustav', 'sn': 'Geier'})
	}

	def ldapauth(user, password):
		user = LDAP_USERRE.sub(r'', user.lower())
		if config.get('DEBUG') and user in notldap and password == notldap[user][0]:
			return notldap[user][2], notldap[user][1]
		return {}, []