Last active
March 22, 2018 15:35
-
-
Save cuuupid/2b8aaa5e74ce4e7d86cd39c20aa0e765 to your computer and use it in GitHub Desktop.
IC LDap in Python 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import ldap, ldap.filter | |
def connect(): | |
conn = ldap.initialize('ldaps://unixldap.cc.ic.ac.uk') | |
conn.simple_bind_s() | |
return conn | |
def search(conn, user, return_list=True): | |
if not isinstance(user, list): | |
user = [user] | |
basedn = "ou=People,ou=shibboleth,dc=ic,dc=ac,dc=uk" | |
output = [] | |
for i in user: | |
filt_uname = "uid={0}".format(ldap.filter.escape_filter_chars(str(i), 1)) | |
query_result = conn.search_s(basedn, ldap.SCOPE_SUBTREE, filt_uname) | |
for dn, entry in query_result: | |
for key, item in entry.items(): | |
entry[key] = item[0] | |
if not query_result: | |
entry = None | |
if return_list: | |
output.append(entry) | |
else: | |
return entry | |
return output | |
def close(conn): conn.unbind() |
API Example:
import l
from console_logging.console import Console
console = Console()
from sanic import Sanic, response
from sanic_cors import CORS
app = Sanic()
CORS(app)
def find(shortcode):
c = l.connect()
try:
s = l.search(c, shortcode)
l.close(c)
except Exception as e:
try:
l.close(c)
except:
pass
console.error('[LDAP] %s' % e)
return False, None
try: return True, s[0]
except: return True, None
@app.route('/search', methods=['POST', 'GET'])
def search(q):
params = q.args
if 'code' not in params:
return response.json({'err': 'No shortcode provided!'}, status=400)
code = params['code'][0]
ret, u = find(code)
if not ret: return response.json({'err': 'LDAP Error!'}, status=500)
if not u: return response.json({'err': 'User does not exist'}, status=401)
return response.json({
'name': u['displayName'].decode(),
'campus': u['l'].decode(),
'student': u['eduPersonAffiliation'].decode() == 'student',
'course': u['ou'].decode().split(',')[0].split('=')[-1].capitalize()
}, status=200)
app.run()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Setup
Usage