<commit_before># coding: utf-8
"""
    flask_oauthlib.provider.oauth1
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Implemnts OAuth1 provider support for Flask.

    :copyright: (c) 2013 by <NAME>.
"""

from functools import wraps
from werkzeug import cached_property
from flask import request, redirect, url_for
from flask import make_response, abort
from oauthlib.oauth1 import RequestValidator
from oauthlib.oauth1 import WebApplicationServer as Server
from oauthlib.oauth1 import SIGNATURE_HMAC, SIGNATURE_RSA
from oauthlib.common import to_unicode, add_params_to_uri
from oauthlib.oauth1.rfc5849.errors import OAuth1Error
from .._utils import log, _extract_params

SIGNATURE_METHODS = (SIGNATURE_HMAC, SIGNATURE_RSA)

__all__ = ('OAuth1Provider', 'OAuth1RequestValidator')


class OAuth1Provider(object):
    """Provide secure services using OAuth1.

    Like many other Flask extensions, there are two usage modes. One is
    binding the Flask app instance::

        app = Flask(__name__)
        oauth = OAuth1Provider(app)

    The second possibility is to bind the Flask app later::

        oauth = OAuth1Provider()

        def create_app():
            app = Flask(__name__)
            oauth.init_app(app)
            return app

    And now you can protect the resource with realms::

        @app.route('/api/user')
        @oauth.require_oauth('email', 'username')
        def user():
            return jsonify(g.user)
    """

    def __init__(self, app=None):
        if app:
            self.init_app(app)

    def init_app(self, app):
        """
        This callback can be used to initialize an application for the
        oauth provider instance.
        """
        self.app = app
        app.extensions = getattr(app, 'extensions', {})
        app.extensions['oauthlib.provider.oauth1'] = self

    @cached_property
    def error_uri(self):
        """The error page URI.

        When something turns error, it will redirect to this error page.
        You can configure the error page URI with Flask config::

            OAUTH1_PROVIDER_ERROR_URI = '/error'

        You can also define the error page by a named endpoint::

            OAUTH1_PROVIDER_ERROR_ENDPOINT = 'oauth.error'
        """
        error_uri = self.app.config.get('OAUTH1_PROVIDER_ERROR_URI')
        if error_uri:
            return error_uri
        error_endpoint = self.app.config.get('OAUTH1_PROVIDER_ERROR_ENDPOINT')
        if error_endpoint:
            return url_for(error_endpoint)
        return '/oauth/errors'

    @cached_property
    def server(self):
        """
        All in one endpoints. This property is created automaticly
        if you have implemented all the getters and setters.
        """
        if hasattr(self, '_validator'):
            return Server(self._validator)

        if hasattr(self, '_clientgetter') and \
           hasattr(self, '_tokengetter') and \
           hasattr(self, '_tokensetter') and \
           hasattr(self, '_noncegetter') and \
           hasattr(self, '_noncesetter') and \
           hasattr(self, '_grantgetter') and \
           hasattr(self, '_grantsetter'):

            # you can have no verifier getter and setter
            verifiergetter = getattr(self, '_verifiergetter', None)
            verifiersetter = getattr(self, '_verifiersetter', None)

            validator = OAuth1RequestValidator(
                clientgetter=self._clientgetter,
                tokengetter=self._tokengetter,
                tokensetter=self._tokensetter,
                grantgetter=self._grantgetter,
                grantsetter=self._grantsetter,
                noncegetter=self._noncegetter,
                noncesetter=self._noncesetter,
                verifiergetter=verifiergetter,
                verifiersetter=verifiersetter,
                config=self.app.config,
            )

            self._validator = validator
            server = Server(validator)
            if self.app.testing:
                # It will always be false, since the redirect_uri
                # didn't match when doing the testing
                server._check_signature = lambda *args, **kwargs: True
            return server
        raise RuntimeError(
            'application not bound to required getters and setters'
        )

    def clientgetter(self, f):
        """Register a function as the client getter.

        The function accepts one parameter `client_key`, and it returns
        a client object with at least these information:

            - client_key: A random string
            - client_secret: A random string
            - redirect_uris: A list of redirect uris
            - realms: Default scopes of the client

        The client may contain more information, which is suggested:

            - default_redirect_uri: One of the redirect uris
            - default_realms: Certain default realms

        Implement the client getter::

            @oauth.clientgetter
            def get_client(client_key):
                client = get_client_model(client_key)
                # Client is an object
                return client
        """
        self._clientgetter = f

    def tokengetter(self, f):
        self._tokengetter = f

    def tokensetter(self, f):
        self._tokensetter = f

    def grantgetter(self, f):
        self._grantgetter = f

    def grantsetter(self, f):
        self._grantsetter = f
<commit_msg>doc string on tokengetter and tokensetter<commit_after># coding: utf-8
"""
    flask_oauthlib.provider.oauth1
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Implemnts OAuth1 provider support for Flask.

    :copyright: (c) 2013 by <NAME>.
"""

from functools import wraps
from werkzeug import cached_property
from flask import request, redirect, url_for
from flask import make_response, abort
from oauthlib.oauth1 import RequestValidator
from oauthlib.oauth1 import WebApplicationServer as Server
from oauthlib.oauth1 import SIGNATURE_HMAC, SIGNATURE_RSA
from oauthlib.common import to_unicode, add_params_to_uri
from oauthlib.oauth1.rfc5849.errors import OAuth1Error
from .._utils import log, _extract_params

SIGNATURE_METHODS = (SIGNATURE_HMAC, SIGNATURE_RSA)

__all__ = ('OAuth1Provider', 'OAuth1RequestValidator')


class OAuth1Provider(object):
    """Provide secure services using OAuth1.

    Like many other Flask extensions, there are two usage modes. One is
    binding the Flask app instance::

        app = Flask(__name__)
        oauth = OAuth1Provider(app)

    The second possibility is to bind the Flask app later::

        oauth = OAuth1Provider()

        def create_app():
            app = Flask(__name__)
            oauth.init_app(app)
            return app

    And now you can protect the resource with realms::

        @app.route('/api/user')
        @oauth.require_oauth('email', 'username')
        def user():
            return jsonify(g.user)
    """

    def __init__(self, app=None):
        if app:
            self.init_app(app)

    def init_app(self, app):
        """
        This callback can be used to initialize an application for the
        oauth provider instance.
        """
        self.app = app
        app.extensions = getattr(app, 'extensions', {})
        app.extensions['oauthlib.provider.oauth1'] = self

    @cached_property
    def error_uri(self):
        """The error page URI.

        When something turns error, it will redirect to this error page.
        You can configure the error page URI with Flask config::

            OAUTH1_PROVIDER_ERROR_URI = '/error'

        You can also define the error page by a named endpoint::

            OAUTH1_PROVIDER_ERROR_ENDPOINT = 'oauth.error'
        """
        error_uri = self.app.config.get('OAUTH1_PROVIDER_ERROR_URI')
        if error_uri:
            return error_uri
        error_endpoint = self.app.config.get('OAUTH1_PROVIDER_ERROR_ENDPOINT')
        if error_endpoint:
            return url_for(error_endpoint)
        return '/oauth/errors'

    @cached_property
    def server(self):
        """
        All in one endpoints. This property is created automaticly
        if you have implemented all the getters and setters.
        """
        if hasattr(self, '_validator'):
            return Server(self._validator)

        if hasattr(self, '_clientgetter') and \
           hasattr(self, '_tokengetter') and \
           hasattr(self, '_tokensetter') and \
           hasattr(self, '_noncegetter') and \
           hasattr(self, '_noncesetter') and \
           hasattr(self, '_grantgetter') and \
           hasattr(self, '_grantsetter'):

            # you can have no verifier getter and setter
            verifiergetter = getattr(self, '_verifiergetter', None)
            verifiersetter = getattr(self, '_verifiersetter', None)

            validator = OAuth1RequestValidator(
                clientgetter=self._clientgetter,
                tokengetter=self._tokengetter,
                tokensetter=self._tokensetter,
                grantgetter=self._grantgetter,
                grantsetter=self._grantsetter,
                noncegetter=self._noncegetter,
                noncesetter=self._noncesetter,
                verifiergetter=verifiergetter,
                verifiersetter=verifiersetter,
                config=self.app.config,
            )

            self._validator = validator
            server = Server(validator)
            if self.app.testing:
                # It will always be false, since the redirect_uri
                # didn't match when doing the testing
                server._check_signature = lambda *args, **kwargs: True
            return server
        raise RuntimeError(
            'application not bound to required getters and setters'
        )

    def clientgetter(self, f):
        """Register a function as the client getter.

        The function accepts one parameter `client_key`, and it returns
        a client object with at least these information:

            - client_key: A random string
            - client_secret: A random string
            - redirect_uris: A list of redirect uris
            - default_realms: Default scopes of the client

        The client may contain more information, which is suggested:

            - default_redirect_uri: One of the redirect uris

        Implement the client getter::

            @oauth.clientgetter
            def get_client(client_key):
                client = get_client_model(client_key)
                # Client is an object
                return client
        """
        self._clientgetter = f

    def tokengetter(self, f):
        """Register a function as the access token getter.

        The function accepts `client_key` and `token` parameters, and it
        returns an access token object contains:

            - client: Client associated with this token
            - client_key: Key of the client
            - user: User associated with this token
            - token: Access token
            - secret: Access token secret
            - realms: Realms with this access token

        Implement the token getter::

            @oauth.tokengetter
            def get_access_token(client_key, token):
                return get_token_model(client_key=client_key, token=token)
        """
        self._tokengetter = f

    def tokensetter(self, f):
        """Register a function as the access token setter.

        The setter accepts two parameters at least, one is token,
        the other is request::

            @oauth.tokensetter
            def save_access_token(token, request):
                tok = AccessToken(
                    client_key=request.client.client_key,
                    user_id=request.request_token.user_id,
                    token=token['oauth_token'],
                    secret=token['oauth_token_secret'],
                    _realms=token['oauth_authorized_realms'],
                )
                db.session.add(tok)
                db.session.commit()

        The parameter token is a dict, that looks like::

            {
                u'oauth_token': u'arandomstringoftoken',
                u'oauth_token_secret': u'arandomstringofsecret',
                u'oauth_authorized_realms': u'email address'
            }

        The `request` object would provide these information (at least)::

            - client: Client object associated with this token
            - request_token: Requst token for exchanging this access token
        """
        self._tokensetter = f

    def grantgetter(self, f):
        """Register a function as the request token getter.
        """
        self._grantgetter = f

    def grantsetter(self, f):
        """Register a function as the request token setter.
        """
        self._grantsetter = f

{'fraction_non_alphanumeric': 0.07741733270647234, 'fraction_numerical': 0.004388026955022724, 'mean_word_length': 2.1152062484744936, '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': '5754965', 'n_tokens_mistral': 3540, 'n_tokens_neox': 3365, 'n_words': 1024}