<commit_before>import datetime as dt
import logging

from flask import (Blueprint, flash, redirect, render_template,
                   request, session, url_for, jsonify)

from flask_login import login_required, current_user

from server.models import db, Client, Token, Grant
from server.extensions import csrf, oauth_provider

logger = logging.getLogger(__name__)

oauth = Blueprint('oauth', __name__)

@oauth.record
def record_params(setup_state):
    """ Load used app configs into local config on registration from
    server/__init__.py """
    app = setup_state.app
    oauth_provider.init_app(app)

@oauth_provider.clientgetter
def load_client(client_id):
    return Client.query.filter_by(client_id=client_id).first()

@oauth_provider.grantgetter
def load_grant(client_id, code):
    return Grant.query.filter_by(client_id=client_id, code=code).first()

@oauth_provider.grantsetter
def save_grant(client_id, code, request, *args, **kwargs):
    expires = dt.datetime.utcnow() + dt.timedelta(seconds=100)
    grant = Grant(
        client_id=client_id,
        code=code['code'],
        redirect_uri=request.redirect_uri,
        scopes=request.scopes,
        user=current_user,
        expires=expires
    )
    db.session.add(grant)
    db.session.commit()
    return grant

@oauth_provider.tokengetter
def load_token(access_token=None, refresh_token=None):
    if access_token:
        return Token.query.filter_by(access_token=access_token).first()
    elif refresh_token:
        return Token.query.filter_by(refresh_token=refresh_token).first()

@oauth_provider.tokensetter
def save_token(token, orequest, *args, **kwargs):
    toks = Token.query.filter_by(client_id=orequest.client.client_id,
                                 user_id=orequest.user.id).all()
    # make sure that every client has only one token connected to a user
    for t in toks:
        db.session.delete(t)

    expires_in = token.get('expires_in')
    expires = dt.datetime.utcnow() + dt.timedelta(seconds=expires_in)

    tok = Token(
        access_token=token['access_token'],
        refresh_token=token['refresh_token'],
        token_type=token['token_type'],
        scopes=token['scope'].split(),
        expires=expires,
        client_id=orequest.client.client_id,
        user_id=orequest.user.id,
    )
    db.session.add(tok)
    db.session.commit()
    return tok

@oauth.route('/oauth/authorize', methods=['GET', 'POST'])
@oauth_provider.authorize_handler
@login_required
def authorize(*args, **kwargs):
    # Only CSRF protect this route.
    csrf.protect()

    if request.method == 'GET':
        client_id = kwargs.get('client_id')
        client = Client.query.filter_by(client_id=client_id).first()
        kwargs['client'] = client
        return render_template('auth/oauthorize.html', **kwargs)

    confirm = request.form.get('confirm', 'no')
    return confirm == 'yes'

@oauth.route('/oauth/token', methods=['POST'])
@oauth_provider.token_handler
def access_token():<commit_msg>wild stab at fixing test because csrf on testing is disabled<commit_after>import datetime as dt
import logging

from flask import (Blueprint, flash, redirect, render_template,
                   request, session, url_for, jsonify)

from flask_login import login_required, current_user

from server.models import db, Client, Token, Grant
from server.extensions import csrf, oauth_provider
from server.controllers.auth import use_testing_login

logger = logging.getLogger(__name__)

oauth = Blueprint('oauth', __name__)

@oauth.record
def record_params(setup_state):
    """ Load used app configs into local config on registration from
    server/__init__.py """
    app = setup_state.app
    oauth_provider.init_app(app)

@oauth_provider.clientgetter
def load_client(client_id):
    return Client.query.filter_by(client_id=client_id).first()

@oauth_provider.grantgetter
def load_grant(client_id, code):
    return Grant.query.filter_by(client_id=client_id, code=code).first()

@oauth_provider.grantsetter
def save_grant(client_id, code, request, *args, **kwargs):
    expires = dt.datetime.utcnow() + dt.timedelta(seconds=100)
    grant = Grant(
        client_id=client_id,
        code=code['code'],
        redirect_uri=request.redirect_uri,
        scopes=request.scopes,
        user=current_user,
        expires=expires
    )
    db.session.add(grant)
    db.session.commit()
    return grant

@oauth_provider.tokengetter
def load_token(access_token=None, refresh_token=None):
    if access_token:
        return Token.query.filter_by(access_token=access_token).first()
    elif refresh_token:
        return Token.query.filter_by(refresh_token=refresh_token).first()

@oauth_provider.tokensetter
def save_token(token, orequest, *args, **kwargs):
    toks = Token.query.filter_by(client_id=orequest.client.client_id,
                                 user_id=orequest.user.id).all()
    # make sure that every client has only one token connected to a user
    for t in toks:
        db.session.delete(t)

    expires_in = token.get('expires_in')
    expires = dt.datetime.utcnow() + dt.timedelta(seconds=expires_in)

    tok = Token(
        access_token=token['access_token'],
        refresh_token=token['refresh_token'],
        token_type=token['token_type'],
        scopes=token['scope'].split(),
        expires=expires,
        client_id=orequest.client.client_id,
        user_id=orequest.user.id,
    )
    db.session.add(tok)
    db.session.commit()
    return tok

@oauth.route('/oauth/authorize', methods=['GET', 'POST'])
@oauth_provider.authorize_handler
@login_required
def authorize(*args, **kwargs):
    # Only CSRF protect this route.
    if not use_testing_login():
        csrf.protect()

    if request.method == 'GET':
        client_id = kwargs.get('client_id')
        client = Client.query.filter_by(client_id=client_id).first()
        kwargs['client'] = client
        return render_template('auth/oauthorize.html', **kwargs)

    confirm = request.form.get('confirm', 'no')
    return confirm == 'yes'

@oauth.route('/oauth/token', methods=['POST'])
@oauth_provider.token_handler
def access_token():
{'fraction_non_alphanumeric': 0.11437428618045359, 'fraction_numerical': 0.0009789525208027412, 'mean_word_length': 3.7890625, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2238633', 'n_tokens_mistral': 1957, 'n_tokens_neox': 1926, 'n_words': 384}