diff --git a/app/main.py b/app/main.py index 874c47a..7c4eb58 100644 --- a/app/main.py +++ b/app/main.py @@ -10,6 +10,8 @@ from app.auth import get_authorization_url, exchange_code_for_token, get_userinf from app.config import load_config from app.unifi import authorize_guest +from app.unifi import authorize_guest, set_guest_name + logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @@ -98,6 +100,7 @@ async def callback(request: Request, code: str, state: str): success = authorize_guest(site, mac, duration) user_agent = request.headers.get("user-agent", "").lower() logger.info("User agent: %s", user_agent) + set_guest_name(site, mac, userinfo.get("preferred_username", "Guest"), user_agent) if not success: return templates.TemplateResponse("error.html", { diff --git a/app/unifi.py b/app/unifi.py index eff1167..e8ec85e 100644 --- a/app/unifi.py +++ b/app/unifi.py @@ -1,5 +1,6 @@ from unifi_utils import UnifiUtils, UnifiAPI from app.config import SiteConfig +from unifi_utils import UnifiUtils, UnifiAPI, UnifiEndpointSymbolics import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) @@ -54,3 +55,49 @@ def unauthorize_guest(site: SiteConfig, mac: str) -> bool: except Exception as e: logger.error("Failed to unauthorize guest %s on site %s: %s", mac, site.id, str(e)) return False + +def set_guest_name(site: SiteConfig, mac: str, username: str, user_agent: str) -> None: + """Set a friendly name on the guest device in UniFi.""" + try: + unifi = UnifiUtils( + endpoint=site.unifi_host, + api_key=site.unifi_api_key, + site=site.unifi_site, + ) + unifi.session.verify = False + + # Determine device type from user agent + ua = user_agent.lower() + if "iphone" in ua: + device_type = "iPhone" + elif "ipad" in ua: + device_type = "iPad" + elif "android" in ua: + device_type = "Android" + elif "windows" in ua: + device_type = "Windows" + elif "mac" in ua: + device_type = "Mac" + else: + device_type = "Device" + + friendly_name = f"{username} {device_type}" + + # Look up client by MAC to get _id + clients = unifi.make_api_call(UnifiAPI.ActiveClientsGet) + client = next((c for c in clients.get("data", []) if c.get("mac") == mac.lower()), None) + + if client is None: + logger.warning("Could not find client %s to set name", mac) + return + + client_id = client.get("_id") + unifi.make_api_call( + UnifiAPI.ClientModifyPut, + json_body={"name": friendly_name}, + added_substitutions={UnifiEndpointSymbolics.ID: client_id}, + ) + logger.info("Set guest name '%s' for %s", friendly_name, mac) + + except Exception as e: + logger.error("Failed to set guest name for %s: %s", mac, str(e)) \ No newline at end of file