Piotr Dobrowolski | a01905a | 2021-10-16 18:22:46 +0200 | [diff] [blame] | 1 | import ldap3 |
| 2 | import os |
| 3 | import sys |
| 4 | import ssl |
| 5 | from ldap3.utils.conv import escape_filter_chars |
| 6 | |
| 7 | class NotActiveMember(Exception): |
| 8 | "Person is not an active hackerspace member" |
| 9 | |
| 10 | def check_member(uid: str, password: str): |
| 11 | escaped_uid = escape_filter_chars(uid) |
| 12 | user_dn = f"uid={escaped_uid},ou=People,dc=hackerspace,dc=pl" |
| 13 | |
| 14 | tls_configuration = ldap3.Tls(validate=ssl.CERT_REQUIRED, version=ssl.PROTOCOL_TLSv1) |
| 15 | server = ldap3.Server("ldap.hackerspace.pl", use_ssl=True, tls=tls_configuration) |
| 16 | with ldap3.Connection(server, user=user_dn, password=password, raise_exceptions=True) as conn: |
| 17 | filterstr = ( |
| 18 | "(&" |
| 19 | f"(uid={escaped_uid})" |
| 20 | "(objectClass=hsMember)" |
| 21 | "(|" |
| 22 | "(memberOf=cn=starving,ou=Group,dc=hackerspace,dc=pl)" |
| 23 | "(memberOf=cn=fatty,ou=Group,dc=hackerspace,dc=pl)" |
| 24 | "(memberOf=cn=potato,ou=Group,dc=hackerspace,dc=pl)" |
| 25 | ")" |
| 26 | ")") |
| 27 | conn.search('ou=People,dc=hackerspace,dc=pl', |
| 28 | filterstr, |
| 29 | search_scope = ldap3.LEVEL, |
| 30 | attributes = ['uid']) |
| 31 | for e in conn.entries: |
| 32 | if e['uid'] == uid: |
| 33 | break |
| 34 | else: |
| 35 | NotActiveMember(f'Member {uid} not found in active members groups') |
| 36 | |
| 37 | def member_auth(): |
| 38 | import argparse |
| 39 | import getpass |
| 40 | |
| 41 | uid = os.environ.get('username', None) |
| 42 | password = os.environ.get('password', None) |
| 43 | |
| 44 | if uid is None and password is None: |
| 45 | print('"username" and "password" not found in environment') |
| 46 | parser = argparse.ArgumentParser() |
| 47 | parser.add_argument("uid", nargs='?', default=getpass.getuser(), help="user id") |
| 48 | args = parser.parse_args() |
| 49 | |
| 50 | uid = args.uid |
| 51 | password = getpass.getpass() |
| 52 | |
| 53 | try: |
| 54 | check_member(uid, password) |
| 55 | sys.exit(0) |
| 56 | except Exception: |
| 57 | sys.exit(1) |
| 58 | |
| 59 | if __name__ == "__main__": |
| 60 | member_auth() |
| 61 | |