#!/usr/bin/env python3
"""uFTP authentication hook: users checked by a web API (an example to adapt: tried with a local test server, not with your API).

Settings in uftp-auth-api.conf next to the script (keep it 0600 if it holds a token):
  url      = https://accounts.example.com/uftp/login
  token    = secret                  sent as  Authorization: Bearer ...  (optional)
  timeout  = 3
The script POSTs {"name": "...", "password": "..."} as JSON and expects HTTP 200 with {"ok": true, "home": "/srv/ftp/x", "readonly": false, "permissions": "list,download",
"max_connections": 2, "max_download_speed": 1024, "max_upload_speed": 512, "owner_user": "x", "owner_group": "x", "allow_from": ["10.0.0.0/8"],
"deny_from": "10.9.0.0/16", "umask": "027"}  (everything but ok and home is optional), or {"ok": false}.
401 or 403 = refused; anything else (no answer, 5xx, not JSON) = not available. Certificates are checked.
"""
import json
import os
import re
import sys
import urllib.error
import urllib.request

NAME = re.compile(r"^[A-Za-z0-9._@-]{1,64}$")
KEYS = ("permissions", "max_connections", "max_download_speed", "max_upload_speed", "owner_user", "owner_group", "allow_from", "deny_from", "umask")


def conf():
    values = {"timeout": "3"}
    path = os.path.abspath(__file__) + ".conf"
    if os.path.exists(path):
        for line in open(path):
            line = line.strip()
            if line and not line.startswith("#") and "=" in line:
                key, value = line.split("=", 1)
                values[key.strip()] = value.strip()
    return values


def main():
    if len(sys.argv) < 2 or sys.argv[1] != "auth":
        sys.exit(__doc__)
    settings = conf()
    name = sys.stdin.readline().rstrip("\n")
    password = sys.stdin.readline().rstrip("\n")
    if not NAME.match(name):
        sys.exit(1)
    if "url" not in settings:
        sys.stderr.write("url is not set\n")
        sys.exit(3)
    headers = {"Content-Type": "application/json"}
    if "token" in settings:
        headers["Authorization"] = "Bearer " + settings["token"]
    request = urllib.request.Request(settings["url"], data=json.dumps({"name": name, "password": password}).encode(), headers=headers, method="POST")
    try:
        with urllib.request.urlopen(request, timeout=float(settings["timeout"])) as response:
            answer = json.loads(response.read(65536).decode())
    except urllib.error.HTTPError as error:
        sys.exit(1 if error.code in (401, 403) else 3)
    except (OSError, ValueError) as error:
        sys.stderr.write("api: %s\n" % error)
        sys.exit(3)
    if not isinstance(answer, dict) or answer.get("ok") is not True or not isinstance(answer.get("home"), str):
        sys.exit(1)
    print("home=" + answer["home"].replace("\n", ""))
    readonly = answer.get("readonly")
    if readonly is True:
        print("readonly=1")
    elif readonly is not None and readonly is not False:      # not a boolean: uFTP says whether it is valid, it must not become a full access
        print("readonly=" + str(readonly).replace("\n", ""))
    for key in KEYS:
        if key in answer and answer[key] is not None:
            value = ",".join(map(str, answer[key])) if isinstance(answer[key], list) else str(answer[key])
            print("%s=%s" % (key, value.replace("\n", "")))


if __name__ == "__main__":
    try:
        main()
    except SystemExit:
        raise
    except Exception as error:              # any other failure is "not available" (3), never "refused" (1) or "accepted"
        sys.stderr.write("error: %s\n" % error)
        sys.exit(3)
