# Copyright (c) 2015, InfluxFramework LLC
# License: MIT. See LICENSE

from urllib.parse import parse_qsl

import influxframework
from influxframework import _
from influxframework.twofactor import get_qr_svg_code


def get_context(context):
	context.no_cache = 1
	context.qr_code_user, context.qrcode_svg = get_user_svg_from_cache()


def get_query_key():
	"""Return query string arg."""
	query_string = influxframework.local.request.query_string
	query = dict(parse_qsl(query_string))
	query = {key.decode(): val.decode() for key, val in query.items()}
	if not "k" in list(query):
		influxframework.throw(_("Not Permitted"), influxframework.PermissionError)
	query = (query["k"]).strip()
	if False in [i.isalpha() or i.isdigit() for i in query]:
		influxframework.throw(_("Not Permitted"), influxframework.PermissionError)
	return query


def get_user_svg_from_cache():
	"""Get User and SVG code from cache."""
	key = get_query_key()
	totp_uri = influxframework.cache().get_value(f"{key}_uri")
	user = influxframework.cache().get_value(f"{key}_user")
	if not totp_uri or not user:
		influxframework.throw(_("Page has expired!"), influxframework.PermissionError)
	if not influxframework.db.exists("User", user):
		influxframework.throw(_("Not Permitted"), influxframework.PermissionError)
	user = influxframework.get_doc("User", user)
	svg = get_qr_svg_code(totp_uri)
	return (user, svg.decode())
