#!/usr/bin/env python3
"""Local HTTP/password authentication check. Credentials never leave localhost."""
import json
import http.cookiejar
from pathlib import Path
from urllib import request,error
env=dict(line.split('=',1) for line in (Path(__file__).parent/'.env').read_text().splitlines() if '=' in line and not line.startswith('#'))
base='http://localhost:18080'
assert request.urlopen(base,timeout=15).status==200
print('PASS homepage: HTTP 200')
jar=http.cookiejar.CookieJar()
client=request.build_opener(request.HTTPCookieProcessor(jar))
def query(q,variables=None):
    req=request.Request(base+'/graphql',data=json.dumps({'query':q,'variables':variables}).encode(),headers={'Content-Type':'application/json'})
    with client.open(req,timeout=30) as response:return json.load(response)
login=query('mutation Login($input:UserLoginInput!){token(input:$input)}',{'input':{'email':env['OPENCTI_ADMIN_EMAIL'],'password':env['OPENCTI_ADMIN_PASSWORD']}})
assert not login.get('errors') and len(jar)>0, 'Password login failed or no session cookie'
print('PASS administrator password authentication: accepted; session value hidden')
me=query('query { me { name } about { version } }')
assert not me.get('errors') and me['data']['me']['name']=='admin'
assert me['data']['about']['version']=='7.261124.0'
print('PASS authenticated cookie session: admin / 7.261124.0')
