<commit_before>from __future__ import absolute_import

import functools
import logging
from pprint import pformat
from urllib import urlencode

import werkzeug as wz
import flask
from flask import request
from flask.ext.login import current_user

from . import utils


log = logging.getLogger(__name__)


class _Redirect(Exception):
    pass

class AuthManager(object):

    login_view = 'login'

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

    def init_app(self, app):
        app.errorhandler(_Redirect)(lambda r: flask.redirect(r.args[0]))

    def context_processor(self, func):
        self._context_processors.append(func)

    def ACL(self, *acl, **options):
        def _ACL(func):

            func.__acl__ = acl

            @functools.wraps(func)
            def wrapped(*args, **kwargs):
                permission = 'http.' + request.method.lower()
                self.assert_can(permission, func, **options)
                return func(*args, **kwargs)

            return wrapped
        return _ACL

    def _before_request(self):
        print flask.request.endpoint
        print dir(flask.request.endpoint)

    def can(self, permission, obj, **kwargs):
        """Check if we can do something with an object.

        >>> auth.can('read', some_object)
        >>> auth.can('write', another_object, group=some_group)

        """

        context = {}
        for func in self._context_processors:
            context.update(func())
        context.update(utils.get_object_acl_context(obj))
        context.update(kwargs)

        log.info('can context: %s' % pformat(context))
        for state, predicate, permissions in utils.iter_object_acl(obj):
            pred_match = predicate(**context)
            perm_match = permission in permissions
            log.info('can %s %r(%s) %r -> %s %s' % (
                'ALLOW' if state else 'DENY',
                predicate, pred_match,
                permissions,
                'ALLOW' if (pred_match and perm_match) else 'DENY', permission
            ))
            if pred_match and perm_match:
                return state
        return None

    def assert_can(self, permission, obj, **kwargs):

        flash_message = kwargs.pop('flash', None)
        stealth = kwargs.pop('stealth', False)

        if not self.can(permission, obj, **kwargs):
            if flash_message and not stealth:
                flask.flash(flash_message, 'danger')
            if current_user.is_authenticated():
                if flash_message is not False:
                    flask.flash(flask_message or 'You are not permitted to "%s" this resource' % permission)
                flask.abort(403)
            elif not stealth and self.login_view:
                if flask_message is not False:
                    flask.flash(flask_message or 'Please login for access.')
                raise _Redirect(flask.url_for(self.login_view) + '?' + urlencode(dict(next=
                    flask.request.script_root + flask.request.path
                )))
            else:
                flask.abort(404)

<commit_msg>Fix a typo<commit_after>from __future__ import absolute_import

import functools
import logging
from pprint import pformat
from urllib import urlencode

import werkzeug as wz
import flask
from flask import request
from flask.ext.login import current_user

from . import utils


log = logging.getLogger(__name__)


class _Redirect(Exception):
    pass

class AuthManager(object):

    login_view = 'login'

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

    def init_app(self, app):
        app.errorhandler(_Redirect)(lambda r: flask.redirect(r.args[0]))

    def context_processor(self, func):
        self._context_processors.append(func)

    def ACL(self, *acl, **options):
        def _ACL(func):

            func.__acl__ = acl

            @functools.wraps(func)
            def wrapped(*args, **kwargs):
                permission = 'http.' + request.method.lower()
                self.assert_can(permission, func, **options)
                return func(*args, **kwargs)

            return wrapped
        return _ACL

    def _before_request(self):
        print flask.request.endpoint
        print dir(flask.request.endpoint)

    def can(self, permission, obj, **kwargs):
        """Check if we can do something with an object.

        >>> auth.can('read', some_object)
        >>> auth.can('write', another_object, group=some_group)

        """

        context = {}
        for func in self._context_processors:
            context.update(func())
        context.update(utils.get_object_acl_context(obj))
        context.update(kwargs)

        log.info('can context: %s' % pformat(context))
        for state, predicate, permissions in utils.iter_object_acl(obj):
            pred_match = predicate(**context)
            perm_match = permission in permissions
            log.info('can %s %r(%s) %r -> %s %s' % (
                'ALLOW' if state else 'DENY',
                predicate, pred_match,
                permissions,
                'ALLOW' if (pred_match and perm_match) else 'DENY', permission
            ))
            if pred_match and perm_match:
                return state
        return None

    def assert_can(self, permission, obj, **kwargs):

        flash_message = kwargs.pop('flash', None)
        stealth = kwargs.pop('stealth', False)

        if not self.can(permission, obj, **kwargs):
            if flash_message and not stealth:
                flask.flash(flash_message, 'danger')
            if current_user.is_authenticated():
                if flash_message is not False:
                    flask.flash(flash_message or 'You are not permitted to "%s" this resource' % permission)
                flask.abort(403)
            elif not stealth and self.login_view:
                if flash_message is not False:
                    flask.flash(flash_message or 'Please login for access.')
                raise _Redirect(flask.url_for(self.login_view) + '?' + urlencode(dict(next=
                    flask.request.script_root + flask.request.path
                )))
            else:
                flask.abort(404)


{'fraction_non_alphanumeric': 0.09801744647105472, 'fraction_numerical': 0.0022204599524187152, 'mean_word_length': 2.0745977571916137, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 17, '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': '902011', 'n_tokens_mistral': 1811, 'n_tokens_neox': 1714, 'n_words': 458}