from flask import abort, Flask, redirect, request
from flask.views import View
from hydra_client import HydraAdmin
import hydra_client
import logging
from os import environ

HYDRA_ADMIN_URL = environ['HYDRA_ADMIN_URL']
HYDRA = HydraAdmin(HYDRA_ADMIN_URL)

app = Flask(__name__)
app.logger.setLevel(logging.INFO)

@app.route('/logout', methods=['GET'])
def home():
    """Handles the OpenID Connect Logout flow

    Communicates with the hydra server to start the logout flow which uses backchannel and
    frontchannel logout methods to log out the user from all applications they have
    access to.

    Args:
        logout_challenge: Reference to a logout challenge object in form of an alphanumeric
         String. Can be used to retrieve the LogoutRequest object via the Hydra Admin API (GET)

    Returns:
        Redirect to the url that is provided by the LogoutRequest object.
    """
    challenge = request.args.get("logout_challenge")
    app.logger.info("Logout request: challenge={0}".format(challenge))
    if not challenge:
        abort(403)
    try:
        logout_request = HYDRA.logout_request(challenge)
    except hydra_client.exceptions.NotFound:
        app.logger.error("Not Found. Logout request not found. challenge={0}".format(challenge))
        abort(404)
    except hydra_client.exceptions.HTTPError:
        app.logger.error("Conflict. Logout request has been used already. challenge={0}".format(challenge))
        abort(503)
    return redirect(logout_request.accept(subject=logout_request.subject))

if __name__ == '__main__':
    app.run()