-
Notifications
You must be signed in to change notification settings - Fork 13
Feature/whoami test page #212
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
AditiChikkali
wants to merge
6
commits into
NSLS2:main
Choose a base branch
from
AditiChikkali:feature/whoami-test-page
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
67cf338
added new endpoint for test login page
AditiChikkali 6e68bd0
changed ldap server configs
a6d6746
refactored api response
34e38d0
improve ldap connection handling && refactor api to use config settings
014283a
change print to logger
f041862
revive existing /person/me endpoitn to fetch ldap user info
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| from ldap3 import Server, Connection, ASYNC | ||
| from datetime import datetime, timedelta | ||
| import binascii | ||
| from nsls2api.infrastructure.logging import logger | ||
|
|
||
| def to_hex(val): | ||
|
|
||
| if isinstance(val, bytes): | ||
| return binascii.hexlify(val).decode() | ||
| return None | ||
|
|
||
| def get_user_info(upn, ldap_server, base_dn, bind_user, bind_password): | ||
| conn = None | ||
| try: | ||
| server = Server(ldap_server) | ||
| conn = Connection(server, user=bind_user, password=bind_password, auto_bind=True) | ||
| search_filter = f"(&(objectclass=person)(userPrincipalName={upn}))" | ||
| conn.search(base_dn, search_filter, attributes=['sAMAccountName']) | ||
|
|
||
| if not conn.entries: | ||
| logger.warning("No entries found for the given UPN.") | ||
| return None | ||
|
|
||
| entry = conn.entries[0] | ||
| username = entry.sAMAccountName.value if 'sAMAccountName' in entry else None | ||
| if username is None: | ||
| return None | ||
|
|
||
| search_filter = f"(&(objectclass=posixaccount)(sAMAccountName={username}))" | ||
| conn.search(base_dn, search_filter, attributes=['*']) | ||
|
|
||
| if not conn.entries: | ||
| logger.warning("no posix entries found for the given username.") | ||
| return None | ||
|
|
||
| entry = conn.entries[0] | ||
| user = dict() | ||
| for attribute in entry.entry_attributes: | ||
| value = entry[attribute].value | ||
| if attribute in ("objectGUID", "objectSid"): | ||
| user[attribute] = value # keep as bytes | ||
| else: | ||
| user[attribute] = str(value) | ||
| return user | ||
| except Exception as e: | ||
| logger.error(f"LDAP Error: {e}") | ||
| return None | ||
| finally: | ||
| if conn is not None: | ||
| conn.unbind() | ||
|
|
||
| def filetime_to_str(filetime): | ||
| try: | ||
| if filetime is None or int(filetime) == 0 or int(filetime) == 9223372036854775807: | ||
| return "Never" | ||
| dt = datetime(1601, 1, 1) + timedelta(microseconds=int(filetime) // 10) | ||
| return dt.strftime("%Y-%m-%d %H:%M:%S UTC") | ||
| except Exception: | ||
| return str(filetime) | ||
|
|
||
| def generalized_time_to_str(gt): | ||
| try: | ||
| if not gt: return "" | ||
| dt = datetime.strptime(gt.split(".")[0], "%Y%m%d%H%M%S") | ||
| return dt.strftime("%Y-%m-%d %H:%M:%S UTC") | ||
| except Exception: | ||
| return str(gt) | ||
|
|
||
| def decode_uac(uac): | ||
| flags = [] | ||
| try: | ||
| val = int(uac) | ||
| if val & 0x0001: flags.append("SCRIPT") | ||
| if val & 0x0002: flags.append("ACCOUNTDISABLE") | ||
| if val & 0x0008: flags.append("HOMEDIR_REQUIRED") | ||
| if val & 0x0200: flags.append("NORMAL_ACCOUNT") | ||
| if val & 0x1000: flags.append("PASSWORD_EXPIRED") | ||
| except Exception: | ||
| return [] | ||
| return flags or ["NORMAL_ACCOUNT"] | ||
|
|
||
| def shape_ldap_response(user_info, dn=None, status="Read", read_time=None): | ||
| def clean_groups(groups_val): | ||
| if not groups_val: | ||
| return [] | ||
| if isinstance(groups_val, list): | ||
| return groups_val | ||
| elif isinstance(groups_val, str): | ||
| return [g.strip() for g in groups_val.replace("\n", ",").split(",") if g.strip()] | ||
| return [] | ||
|
|
||
| return { | ||
| "dn": dn or user_info.get("distinguishedName"), | ||
| "status": status, | ||
| "readTime": read_time, | ||
| "identity": { | ||
| "displayName": user_info.get("displayName"), | ||
| "email": user_info.get("mail") or user_info.get("email"), | ||
| "department": user_info.get("department"), | ||
| "manager": user_info.get("manager"), | ||
| "unix": { | ||
| "uid": user_info.get("uid"), | ||
| "uidNumber": user_info.get("uidNumber"), | ||
| "gidNumber": user_info.get("gidNumber"), | ||
| "homeDirectory": user_info.get("homeDirectory"), | ||
| "loginShell": user_info.get("loginShell") | ||
| } | ||
| }, | ||
| "account": { | ||
| "accountExpires": filetime_to_str(user_info.get("accountExpires")), | ||
| "badPasswordTime": filetime_to_str(user_info.get("badPasswordTime")), | ||
| "badPwdCount": int(user_info.get("badPwdCount") or 0), | ||
| "pwdLastSet": filetime_to_str(user_info.get("pwdLastSet")), | ||
| "lastLogon": filetime_to_str(user_info.get("lastLogon")), | ||
| "userAccountControlFlags": decode_uac(user_info.get("userAccountControl")), | ||
| "userPrincipalName": user_info.get("userPrincipalName"), | ||
| }, | ||
| "directory": { | ||
| "objectGUID": to_hex(user_info.get("objectGUID")), | ||
| "objectSid": to_hex(user_info.get("objectSid")), | ||
| "primaryGroupID": user_info.get("primaryGroupID"), | ||
| "distinguishedName": user_info.get("distinguishedName"), | ||
| }, | ||
| "groups": clean_groups(user_info.get("memberOf")), | ||
| "attributes": { | ||
| "sn": user_info.get("sn"), | ||
| "givenName": user_info.get("givenName"), | ||
| "description": user_info.get("description"), | ||
| "gecos": user_info.get("gecos"), | ||
| "street": user_info.get("street"), | ||
| "codePage": user_info.get("codePage"), | ||
| "countryCode": user_info.get("countryCode"), | ||
| "instanceType": user_info.get("instanceType"), | ||
| "objectClass": [s.strip() for s in user_info.get("objectClass", "").split() if s.strip()] | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ldap3 appears to support ASYNC connections. This would be advantageous to avoid blocking.
https://ldap3.readthedocs.io/en/latest/connection.html
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Attempted client_strategy=ASYNC for non-blocking LDAP, but conn.result after conn.search did not reliably wait for completion or fetch results. Would need proper asyncio integration for true async; reverted to default strategy since it works reliably for now.