import os


class FrameAncestorsMiddleware:
    """Allow named sites to show this CRM inside a frame.

    X_FRAME_OPTIONS = 'DENY' is right by default: it stops any other site
    putting the CRM in a frame and tricking a signed-in user into clicking
    something. But the dashboard at csr.altriaph.com embeds the CRM on purpose,
    and DENY blocks that too.

    ALLOW-FROM is obsolete and ignored by every current browser, so the answer
    is to drop the header for those sites and state the permission in a
    Content-Security-Policy instead, which browsers do honour. Nothing changes
    unless FRAME_ANCESTORS is set: with it empty, DENY stands exactly as before.

        FRAME_ANCESTORS=https://csr.altriaph.com

    Several sites are comma-separated. Only put your own sites here — anything
    listed can frame a signed-in CRM session.
    """

    def __init__(self, get_response):
        self.get_response = get_response
        raw = os.getenv('FRAME_ANCESTORS', '')
        self.ancestors = [origin.strip() for origin in raw.split(',') if origin.strip()]

    def __call__(self, request):
        response = self.get_response(request)
        if not self.ancestors:
            return response

        # Responses travel back up the middleware list, so this runs BEFORE
        # XFrameOptionsMiddleware, and simply deleting the header would not
        # help - that middleware adds it again afterwards. It does honour this
        # flag, which is Django's own way of saying "this response may be
        # framed". The pop covers the case where the header is already set.
        response.xframe_options_exempt = True
        response.headers.pop('X-Frame-Options', None)
        response.headers['Content-Security-Policy'] = (
            "frame-ancestors 'self' " + ' '.join(self.ancestors)
        )
        return response
