사용자 관리 API 사용하기
Not translated
This page is currently being translated. We will complete the translation as soon as possible.
This page is currently being translated. We will complete the translation as soon as possible.
인증 토큰을 발급받은 후에는 API를 통해 사용자 라이프사이클을 관리할 수 있습니다. 사용자 조회, 생성, 수정, 중단 등의 엔드포인트를 사용하여 BioStar Air 사이트의 사용자를 자동화된 방식으로 관리하세요.
권장 API 통합 범위
API 통합은 가능한 한 아래의 범위로 제한하세요.
-
사용자 라이프사이클(lifecycle) 관리(생성/업데이트/삭제)
-
자격 증명 관리(모바일, RF 카드, 생체 인식)
관리자가 기존 BioStar Air 웹 및 모바일 관리 앱을 사용할 수 있도록 허용하세요.
-
출입 등급
-
일정
-
출입문 및 장치 설정
-
사이트 설정
사용자 관리 API 호출
로그인 후 다음 엔드포인트를 사용하여 사용자를 관리하세요.
-
getUsers -
createUser -
updateUser -
suspendUsers
항상 Authorization 헤더에 Bearer 토큰을 포함하세요.
사용자를 활성화하려면 최소한 하나의 크리덴셜 유형을 할당해야 합니다.
예, RF 카드, 모바일, LinkPass
애플리케이션 예제
다음은 API를 통해 CSV 파일을 업로드하고 사용자를 일괄 중단할 수 있는 Python 앱의 샘플 코드입니다.
Python
import requests
import csv
import getpass
from pathlib import Path
def select_server():
servers = {
"1": ("Demo", "https://demo-afs-api.airfob.com/v1"),
"2": ("Global", "https://a-afs-api.airfob.com/v1"),
"3": ("EU", "https://e-afs-api.airfob.com/v1")
}
print("Please select a server:")
for key, (name, _) in servers.items():
print(f"{key}: {name}")
choice = input("Enter server number: ").strip()
return servers.get(choice, (None, None))[1]
def login(base_url, username, password):
url = f"{base_url}/login"
payload = {"username": username, "password": password}
response = requests.post(url, json=payload)
response.raise_for_status()
data = response.json()
token = data.get("access_token")
if not token:
raise ValueError("Login succeeded but no access_token returned.")
print("✅ Login successful.")
return token
def login_to_account(base_url, token, account_id):
url = f"{base_url}/login/{account_id}"
headers = {"Authorization": f"Bearer {token}"}
response = requests.post(url, headers=headers)
response.raise_for_status()
new_token = response.json().get("access_token")
if new_token:
print(f"✅ Switched to account ID: {account_id}")
return new_token
return token
def get_accounts(base_url, token):
url = f"{base_url}/accounts/self"
headers = {"Authorization": f"Bearer {token}"}
response = requests.get(url, headers=headers)
response.raise_for_status()
accounts = response.json().get("accounts", [])
return [{"id": acc["id"], "name": acc["site"]["name"]} for acc in accounts]
def suspend_users_from_csv(base_url, csv_path, token):
if not Path(csv_path).exists():
print(f"❌ File not found: {csv_path}")
return
headers = {"Authorization": f"Bearer {token}"}
with open(csv_path, newline='', encoding='utf-8-sig') as f:
reader = csv.DictReader(f)
# Normalize headers
reader.fieldnames = [field.strip().lower() for field in reader.fieldnames]
if 'email' not in reader.fieldnames:
print("❌ Missing required 'email' column in CSV.")
return
for row in reader:
email = row.get("email")
if not email:
print("⚠️ Skipping row with missing email.")
continue
# Search user
search_url = f"{base_url}/users/search"
payload = {"filters": [{"field": "email", "equals": email}]}
search_resp = requests.post(search_url, headers=headers, json=payload)
if search_resp.status_code != 200:
print(f"❌ Failed to search user {email}: {search_resp.text}")
continue
users = search_resp.json().get("users", [])
if not users:
print(f"❌ No user found with email: {email}")
continue
user_id = users[0]["id"]
# Suspend user
suspend_url = f"{base_url}/users/suspend"
suspend_payload = {
"ids": [user_id],
"certify_by": "none",
"use_site_template": True
}
suspend_resp = requests.post(suspend_url, headers=headers, json=suspend_payload)
if suspend_resp.status_code == 200:
print(f"✅ Suspended user: {email}")
else:
print(f"❌ Failed to suspend user {email}: {suspend_resp.text}")
def main():
base_url = select_server()
if not base_url:
print("❌ Invalid selection. Exiting.")
return
print("\n🔑 BioStar Air Login")
username = input("Email: ")
password = getpass.getpass("Password: ")
token = login(base_url, username, password)
accounts = get_accounts(base_url, token)
print("\n🌐 Available Sites:")
for i, acc in enumerate(accounts):
print(f"{i}: {acc['name']} (ID: {acc['id']})")
selected = int(input("\nSelect site number to log into: "))
account_id = accounts[selected]["id"]
token = login_to_account(base_url, token, account_id)
csv_path = input("Enter path to CSV file with user emails: ").strip()
suspend_users_from_csv(base_url, csv_path, token)
if __name__ == "__main__":
main()