# This script demonstrates how to consume the Canopy REST API. It
# returns the details of the first 10 projects from the public demo
# instance of Canopy.

import pprint
import sys

import requests

SERVER_URL = "https://demo.canopy.checksec.com/"
LOGIN_URL = SERVER_URL + "accounts/login/"
PROJECTS_URL = SERVER_URL + "api/projects/project/"

USERNAME = "admin@checksec.com"
PASSWORD = "checksec99"


# Use a session object that supports cookies
s = requests.Session()

# First request is to obtain a CSRF Token. This can be any URL.
res = s.get(SERVER_URL + "accounts/login/")
if not res.ok:
    print(f"Failed to contact server: {res.status_code} {res.reason}")
    sys.exit(-1)

# Set CSRF Token header
csrftoken = s.headers["X-CSRFToken"] = s.cookies["csrftoken"]

# Login to obtain session id
# Note the referer is being set as the server verifies it and the csrftoken
res = s.post(
    LOGIN_URL,
    data=dict(
        username=USERNAME,
        password=PASSWORD,
        csrfmiddlewaretoken=csrftoken,
    ),
    headers={"referer": LOGIN_URL},
)

if not res.ok:
    print("Failed to login: %s" % res.content)
    sys.exit(-1)

# At this stage the session is populated with a the sessionid and csrftoken
# cookies. Additionally any request that makes modifications should include
# the X-CSRFToken header.

# Query Project endpoint
res = s.get(PROJECTS_URL + "?limit=10")
if res.ok:
    pprint.pprint(res.json())
else:
    print("Failed to query Project endpoint: %s" % res.reason)
