Skip to content

Instantly share code, notes, and snippets.

@cuuupid
Last active March 22, 2018 15:35
Show Gist options
  • Save cuuupid/2b8aaa5e74ce4e7d86cd39c20aa0e765 to your computer and use it in GitHub Desktop.
Save cuuupid/2b8aaa5e74ce4e7d86cd39c20aa0e765 to your computer and use it in GitHub Desktop.
IC LDap in Python 3
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()
@cuuupid
Copy link
Author

cuuupid commented Mar 22, 2018

Setup

sudo apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev
pip install python-ldap

Usage

import search

c = search.connect()
search.search(c, 'shortcode')

# if connection drops (will return err)
search.close(c)

@cuuupid
Copy link
Author

cuuupid commented Mar 22, 2018

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