<commit_before>#!/usr/bin/env python
from __future__ import unicode_literals, absolute_import, division, print_function

import base64
import logging
import re
from copy import deepcopy
from datetime import datetime

from flask import Flask, redirect, url_for, session, request, current_app
from flask_oauthlib.client import OAuth, OAuthException
from werkzeug.exceptions import Unauthorized, Forbidden, InternalServerError
from six import wraps, raise_from

log = logging.getLogger(__name__)


class ZalandoAuthException(Exception):
    pass


class MissingTokenException(ZalandoAuthException):
    pass


class MissingTokenInfoException(ZalandoAuthException):
    pass


class TokenIsExpiredException(ZalandoAuthException):
    pass


class UnsupportedAuthMethodException(ZalandoAuthException):
    pass


class TokenIsExpired(ZalandoAuthException):
    pass


def get_oauth_token():
    token = None
    if 'Authorization' in request.headers:
        if request.headers['Authorization'].startswith('Bearer'):
            token = request.headers['Authorization']
            token = token.split(' ', 1)[1]
        elif request.headers['Authorization'].startswith('Basic'):
            try:
                auth_header_part = request.headers['Authorization'].split(' ', 1)[1]
                auth_data = base64.b64decode(auth_header_part)
                _, token = auth_data.split(':', 1)
            except Exception as e:
                msg = (
                    "Exception during parsing auth headers: %s",
                    e
                )
                log.exception(msg[0], *msg[1:])
                raise_from(ZalandoAuthException(msg[0] % msg[1:]), e)
        else:
            msg = (
                'Unsupported auth method was specified: %s',
                request.headers['Authorization']
            )
            log.exception(msg[0], *msg[1:])
            raise UnsupportedAuthMethodException(msg[0] % msg[1:])

        if token:
            return token, ''

        # We do not want to fallback to session based auth if Auth header presents
        return None

    token = _get_session_data('token')
    if not token:
        return None
    return token, ''


def make_oauth_wsgi(oauth, next_app, config=None):
    app = Flask(__name__)
    if config:
        app.config.update(config)
    else:
        app.config.from_envvar('OAUTH_SETTINGS')

    app.next_app = next_app
    oauth.init_app(app)
    app.add_url_rule('/login', endpoint=None, view_func=login)
    app.add_url_rule('/logout', endpoint=None, view_func=logout)
    app.add_url_rule('/login/oauth_callback', endpoint=None, view_func=authorized)
    app.add_url_rule(
        '/',
        endpoint=None, view_func=default_handler,
    )
    app.add_url_rule(
        '/<path:any>',
        endpoint=None, view_func=default_handler,
    )

    auth = get_auth_provider(oauth)
    if not auth._tokengetter:
        auth.tokengetter(get_oauth_token)

    return app


def _set_session_data(key, val):
    session.setdefault('auth_info', {})
    session['auth_info'][key] = val


def _get_session_data(key, default=None):
    session.setdefault('auth_info', {})<commit_msg>Proxyfix middleware for work behind https<commit_after>#!/usr/bin/env python
from __future__ import unicode_literals, absolute_import, division, print_function

import base64
import logging
import re
from copy import deepcopy
from datetime import datetime

from flask import Flask, redirect, url_for, session, request, current_app
from flask_oauthlib.client import OAuth, OAuthException
from werkzeug.contrib.fixers import ProxyFix
from werkzeug.exceptions import Unauthorized, Forbidden, InternalServerError
from six import wraps, raise_from

log = logging.getLogger(__name__)


class ZalandoAuthException(Exception):
    pass


class MissingTokenException(ZalandoAuthException):
    pass


class MissingTokenInfoException(ZalandoAuthException):
    pass


class TokenIsExpiredException(ZalandoAuthException):
    pass


class UnsupportedAuthMethodException(ZalandoAuthException):
    pass


class TokenIsExpired(ZalandoAuthException):
    pass


def get_oauth_token():
    token = None
    if 'Authorization' in request.headers:
        if request.headers['Authorization'].startswith('Bearer'):
            token = request.headers['Authorization']
            token = token.split(' ', 1)[1]
        elif request.headers['Authorization'].startswith('Basic'):
            try:
                auth_header_part = request.headers['Authorization'].split(' ', 1)[1]
                auth_data = base64.b64decode(auth_header_part)
                _, token = auth_data.split(':', 1)
            except Exception as e:
                msg = (
                    "Exception during parsing auth headers: %s",
                    e
                )
                log.exception(msg[0], *msg[1:])
                raise_from(ZalandoAuthException(msg[0] % msg[1:]), e)
        else:
            msg = (
                'Unsupported auth method was specified: %s',
                request.headers['Authorization']
            )
            log.exception(msg[0], *msg[1:])
            raise UnsupportedAuthMethodException(msg[0] % msg[1:])

        if token:
            return token, ''

        # We do not want to fallback to session based auth if Auth header presents
        return None

    token = _get_session_data('token')
    if not token:
        return None
    return token, ''


def make_oauth_wsgi(oauth, next_app, config=None):
    app = Flask(__name__)
    if config:
        app.config.update(config)
    else:
        app.config.from_envvar('OAUTH_SETTINGS')

    app.next_app = next_app
    oauth.init_app(app)
    app.add_url_rule('/login', endpoint=None, view_func=login)
    app.add_url_rule('/logout', endpoint=None, view_func=logout)
    app.add_url_rule('/login/oauth_callback', endpoint=None, view_func=authorized)
    app.add_url_rule(
        '/',
        endpoint=None, view_func=default_handler,
    )
    app.add_url_rule(
        '/<path:any>',
        endpoint=None, view_func=default_handler,
    )

    auth = get_auth_provider(oauth)
    if not auth._tokengetter:
        auth.tokengetter(get_oauth_token)

    app.wsgi_app = ProxyFix(app.wsgi_app)

    return app


def _set_session_data(key, val):
    session.setdefault('auth_info', {})
    session['auth_info'][key] = val


def _get_session_data(key, default=None):
    session.setdefault('auth_info', {})
{'fraction_non_alphanumeric': 0.09875968992248062, 'fraction_numerical': 0.005891472868217054, 'mean_word_length': 2.8721488595438176, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4850468', 'n_tokens_mistral': 1947, 'n_tokens_neox': 1886, 'n_words': 415}