<commit_before>#
# https://auth0.com/docs/quickstart/backend/python#add-api-authorization
# https://github.com/auth0-samples/auth0-python-api-samples/tree/master/00-Starter-Seed

import functools
import json
import os

from flask import Flask, request, jsonify, _app_ctx_stack
from flask_cors import cross_origin
import werkzeug

import doorman

DOORMAN_SERVER = os.getenv("DOORMAN_SERVER", "http://localhost:8080")
# This service is the Auth0 API id.
SERVICE = os.getenv("SERVICE", "SLocf7Sa1ibd5GNJMMqO539g7cKvWBOI")
HERE = os.path.abspath(os.path.dirname(__file__))
RECORDS_PATH = os.getenv("RECORDS_PATH", os.path.join(HERE, "records"))


app = Flask(__name__)

allowed = functools.partial(doorman.allowed, DOORMAN_SERVER, SERVICE)


@app.errorhandler(doorman.AuthZError)
def handle_auth_error(ex):
    response = jsonify(ex.error)
    response.status_code = ex.status_code
    return response


def authorized(**allowed_kw):
    def wrapped(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            jwt = request.headers.get("Authorization", None)
            authz = allowed(jwt=jwt, **allowed_kw)
            _app_ctx_stack.top.authz = authz
            return f(*args, **kwargs)
        return wrapper
    return wrapped


@app.route("/")
@cross_origin(headers=["Content-Type", "Authorization"])
@cross_origin(headers=["Access-Control-Allow-Origin", "*"])
@authorized(resource="hello")
def hello():
    """A valid access token is required to access this route
    """
    authz = _app_ctx_stack.top.authz
    return jsonify(authz)


@app.route("/records")
@cross_origin(headers=["Content-Type", "Authorization"])
@cross_origin(headers=["Access-Control-Allow-Origin", "*"])
@authorized(resource="record", action="list")
def records():
    authz = _app_ctx_stack.top.authz
    email_principal = authz["principals"][1]
    records = Records.list(author=email_principal)
    return jsonify(records)


@app.route("/records/<name>", methods=('GET', 'PUT'))
@cross_origin(headers=["Content-Type", "Authorization"])
@cross_origin(headers=["Access-Control-Allow-Origin", "*"])
def record(name):
    jwt = request.headers.get("Authorization", None)

    record, author = Records.read(name)

    if request.method == "GET":
        action = "read"
    else:
        action = "create" if record is None else "update"

    # Check if allowed to perform action (will raise AuthZError if not authorized)
    authz = allowed(resource="record", action=action, jwt=jwt, context={"author": author})

    # Return 404 if allowed to read but unknown record.
    if record is None and request.method == "GET":
        raise werkzeug.exceptions.NotFound()

    # Save content on PUT
    if request.method == "PUT":
        body = request.data.decode("utf-8")
        email_principal = authz["principals"][1]
        record = Records.save(name, body, email_principal)

    return jsonify(record)


class Records:
    @staticmethod
    def list(author):
        all_records = [f for f in os.listdir(RECORDS_PATH) if f.endswith(".json")]
        all_contents = [(f, json.load(open(os.path.join(RECORDS_PATH, f)))) for f in all_records]
        return [{'name': f.replace('.json', ''), 'body': content['body']}
                for f, content in all_contents if content["author"] == author]

    @staticmethod
    def read(name):
        path = os.path.join(RECORDS_PATH, "{}.json".format(os.path.basename(name)))
        if os.path.exists(path):
            with open(path, 'r') as f:<commit_msg>Fix demo with new OIDC conformant mode<commit_after>#
# https://auth0.com/docs/quickstart/backend/python#add-api-authorization
# https://github.com/auth0-samples/auth0-python-api-samples/tree/master/00-Starter-Seed

import functools
import json
import os

from flask import Flask, request, jsonify, _app_ctx_stack
from flask_cors import cross_origin
import werkzeug

import doorman

DOORMAN_SERVER = os.getenv("DOORMAN_SERVER", "http://localhost:8080")
# This service is the Auth0 API id.
SERVICE = os.getenv("SERVICE", "SLocf7Sa1ibd5GNJMMqO539g7cKvWBOI")
HERE = os.path.abspath(os.path.dirname(__file__))
RECORDS_PATH = os.getenv("RECORDS_PATH", os.path.join(HERE, "records"))


app = Flask(__name__)

allowed = functools.partial(doorman.allowed, DOORMAN_SERVER, SERVICE)


@app.errorhandler(doorman.AuthZError)
def handle_auth_error(ex):
    response = jsonify(ex.error)
    response.status_code = ex.status_code
    return response


def authorized(**allowed_kw):
    def wrapped(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            jwt = request.headers.get("Authorization", None)
            authz = allowed(jwt=jwt, **allowed_kw)
            _app_ctx_stack.top.authz = authz
            return f(*args, **kwargs)
        return wrapper
    return wrapped


@app.route("/")
@cross_origin(headers=["Content-Type", "Authorization"])
@cross_origin(headers=["Access-Control-Allow-Origin", "*"])
@authorized(resource="hello")
def hello():
    """A valid access token is required to access this route
    """
    authz = _app_ctx_stack.top.authz
    return jsonify(authz)


@app.route("/records")
@cross_origin(headers=["Content-Type", "Authorization"])
@cross_origin(headers=["Access-Control-Allow-Origin", "*"])
@authorized(resource="record", action="list")
def records():
    authz = _app_ctx_stack.top.authz
    main_principal = authz["principals"][0]
    records = Records.list(author=main_principal)
    return jsonify(records)


@app.route("/records/<name>", methods=('GET', 'PUT'))
@cross_origin(headers=["Content-Type", "Authorization"])
@cross_origin(headers=["Access-Control-Allow-Origin", "*"])
def record(name):
    jwt = request.headers.get("Authorization", None)

    record, author = Records.read(name)

    if request.method == "GET":
        action = "read"
    else:
        action = "create" if record is None else "update"

    # Check if allowed to perform action (will raise AuthZError if not authorized)
    authz = allowed(resource="record", action=action, jwt=jwt, context={"author": author})

    # Return 404 if allowed to read but unknown record.
    if record is None and request.method == "GET":
        raise werkzeug.exceptions.NotFound()

    # Save content on PUT
    if request.method == "PUT":
        body = request.data.decode("utf-8")
        main_principal = authz["principals"][0]
        record = Records.save(name, body, main_principal)

    return jsonify(record)


class Records:
    @staticmethod
    def list(author):
        all_records = [f for f in os.listdir(RECORDS_PATH) if f.endswith(".json")]
        all_contents = [(f, json.load(open(os.path.join(RECORDS_PATH, f)))) for f in all_records]
        return [{'name': f.replace('.json', ''), 'body': content['body']}
                for f, content in all_contents if content["author"] == author]

    @staticmethod
    def read(name):
        path = os.path.join(RECORDS_PATH, "{}.json".format(os.path.basename(name)))
        if os.path.exists(path):
            with open(path, 'r') as f:
{'fraction_non_alphanumeric': 0.14352840666381889, 'fraction_numerical': 0.006549907446959989, 'mean_word_length': 3.9084556254367575, 'pattern_counts': {'":': 8, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 4, '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': '6927265', 'n_tokens_mistral': 2308, 'n_tokens_neox': 2265, 'n_words': 497}