import logging as log
import os

from api import app, BASE_ROUTE
from flask import request
from services import cognito_service
from utils.common import PlutoException

BASE_PATH = BASE_ROUTE + 'post-confirm'


def handler(event, context):  # pylint: disable=unused-argument
    receive_aws_post_confirmation_hook(event)
    return event


def receive_aws_post_confirmation_hook(event):
    try:
        username = event.get('userName', None)
        if not username:
            raise Exception("Invalid post confirmation. Username was not defined")

        user_attributes = event.get('request', {}).get('userAttributes', {})
        if not user_attributes.get('email_verified', False):
            raise Exception("Invalid post confirmation. Email was not verified.")

        cognito_service.create_user(username, user_attributes)
    except Exception as e:
        log.exception("Processing Cognito post confirmation failed")
        raise PlutoException("Post confirmation hook failed") from e


@app.route(BASE_PATH, methods=["POST"])
def test_endpoint():
    payload = request.get_json()
    log.info("PAYLOAD %s", payload)
    receive_aws_post_confirmation_hook(payload)

    return "OK", 200


if __name__ == "__main__":
    os.environ['DEBUG'] = "True"
    app.run("0.0.0.0", port=8083, debug=True)

import logging as log
import os

from api import app, BASE_ROUTE
from flask import request
from services import cognito_service
from utils.common import PlutoException

BASE_PATH = BASE_ROUTE + 'post-confirm'


def handler(event, context):  # pylint: disable=unused-argument
    receive_aws_post_confirmation_hook(event)
    return event


def receive_aws_post_confirmation_hook(event):
    try:
        username = event.get('userName', None)
        if not username:
            raise Exception("Invalid post confirmation. Username was not defined")

        user_attributes = event.get('request', {}).get('userAttributes', {})
        if not user_attributes.get('email_verified', False):
            raise Exception("Invalid post confirmation. Email was not verified.")

        cognito_service.create_user(username, user_attributes)
    except Exception as e:
        log.exception("Processing Cognito post confirmation failed")
        raise PlutoException("Post confirmation hook failed") from e


@app.route(BASE_PATH, methods=["POST"])
def test_endpoint():
    payload = request.get_json()
    log.info("PAYLOAD %s", payload)
    receive_aws_post_confirmation_hook(payload)

    return "OK", 200


if __name__ == "__main__":
    os.environ['DEBUG'] = "True"
    app.run("0.0.0.0", port=8083, debug=True)

# pylint: disable=unused-argument