Beispiel #1
0
def auth_success_response(user, pgt, proxies):
    response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
    auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
    username = etree.SubElement(auth_success, CAS + 'user')
    username.text = getattr(user, settings.CAS_USERNAME_FIELD)

    if len(username.text) > 30:
        if '@' in username.text[:30]:
            username.text = username.text[:30]
        elif username.text.endswith('@touchstonenetwork.net'):
            username.text = username.text.rsplit(
                '@touchstonenetwork.net')[0][:27] + '@tn'
        else:
            username.text = username.text[:29] + '@'

    if settings.CAS_CUSTOM_ATTRIBUTES_CALLBACK:
        callback = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_CALLBACK)
        attrs = callback(user)
        if len(attrs) > 0:
            formater = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
            formater(auth_success, attrs)

    if pgt:
        pgtElement = etree.SubElement(auth_success,
                                      CAS + 'proxyGrantingTicket')
        pgtElement.text = pgt

    if proxies:
        proxiesElement = etree.SubElement(auth_success, CAS + "proxies")
        for proxy in proxies:
            proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
            proxyElement.text = proxy

    return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')
Beispiel #2
0
 def test_exceptions(self):
     # A missing view (identified by an AttributeError) should raise
     # ViewDoesNotExist, ...
     with six.assertRaisesRegex(self, ViewDoesNotExist, ".*View does not exist in.*"):
         get_callable('urlpatterns_reverse.views.i_should_not_exist')
     # ... but if the AttributeError is caused by something else don't
     # swallow it.
     with self.assertRaises(AttributeError):
         get_callable('urlpatterns_reverse.views_broken.i_am_broken')
Beispiel #3
0
 def _set_attr(self, prefix_name, value):
     name = prefix_name[len(self.prefix) + 1:]
     if name in ('ROUTER', ):
         try:
             obj = import_by_name(value)
         except (ImportError, ValueError, AttributeError):
             raise ImportError(
                 f"Cannot import '{value}'. Check your settings.{prefix_name}"
             )
         setattr(self, name, obj)
         return obj
     elif name in ('get_current_user', 'get_current_request',
                   'get_current_user'):
         try:
             if isinstance(value, str):
                 func = get_callable(value)
             elif callable(value):
                 func = value
             else:
                 raise ImproperlyConfigured(
                     f"{value} is not a valid value for `{name}`. "
                     "It must be a callable or a fullpath to callable. ")
         except Exception as e:
             raise ImproperlyConfigured(e)
         setattr(self, name, func)
         return func
     else:
         setattr(self, name, value)
         return value
Beispiel #4
0
    def render(self, context):
        """
        Render the view node
        """
        if 'request' not in context:
            return ""
        request = context['request']

        url_or_view = Variable(self.url_or_view).resolve(context)
        try:
            urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
            resolver = URLResolver(r'^/', urlconf)
            view, args, kwargs = resolver.resolve(url_or_view)
        # pylint: disable=bare-except
        except:
            view = get_callable(url_or_view)
            args = [Variable(arg).resolve(context) for arg in self.args]
            kwargs = {}
            for key, value in self.kwargs.items():
                kwargs[key] = Variable(value).resolve(context)

        try:
            if callable(view):
                render_fnc = view(context['request'], *args, **kwargs).content.\
                    decode('unicode_escape')
                return render_fnc
            raise "%r is not callable" % view
        # pylint: disable=bare-except
        except:
            if settings.DEBUG_PROPAGATE_EXCEPTIONS:
                raise
        return ""
Beispiel #5
0
def auth_success_response(user, pgt, proxies):
    response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
    auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
    username = etree.SubElement(auth_success, CAS + 'user')
    username.text = user.username

    attrs = {}
    for receiver, custom in signals.cas_collect_custom_attributes.send(sender=auth_success_response, user=user):
        if custom:
            attrs.update(custom)

    identifiers = [i for sr, rr in signals.on_cas_collect_histories.send(sender=validate, for_user=user)
                   for i in rr]

    if identifiers:
        # Singular `identifier`, as that is the name of the element tag(s).
        attrs['identifier'] = identifiers

    if attrs:
        formatter = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
        formatter(auth_success, attrs)

    if pgt:
        pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket')
        pgtElement.text = pgt

    if proxies:
        proxiesElement = etree.SubElement(auth_success, CAS + "proxies")
        for proxy in proxies:
            proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
            proxyElement.text = proxy

    return etree.tostring(response, encoding='unicode')
 def _load_emails(self):
     loader = getattr(
         settings,
         "DEC_LOADER",
         "disposable_email_checker.emails.email_domain_loader",
     )
     return get_callable(loader)()
Beispiel #7
0
    def render(self, context):
        if 'request' not in context:
            return ""
        request = context['request']

        url_or_view = Variable(self.url_or_view).resolve(context)
        try:
            urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
            resolver = URLResolver(RegexPattern(r'^/'), urlconf)
            view, args, kwargs = resolver.resolve(url_or_view)
        except:
            view = get_callable(url_or_view)
            args = [Variable(arg).resolve(context) for arg in self.args]
            kwargs = {}
            for key, value in self.kwargs.items():
                kwargs[key] = Variable(value).resolve(context)

        try:
            if callable(view):
                return view(context['request'], *args,
                            **kwargs).content.decode(settings.DEFAULT_CHARSET)
            raise "%r is not callable" % view
        except:
            if getattr(settings, 'TEMPLATE_DEBUG', False):
                raise
        return ""
Beispiel #8
0
    def render(self, context):
        if 'request' not in context:
            return ""
        request = context['request']

        url_or_view = Variable(self.url_or_view).resolve(context)
        try:
            urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
            resolver = urls.RegexURLResolver(r'^/', urlconf)
            view, args, kwargs = resolver.resolve(url_or_view)
        except:
            #            view = urls.get_callable(url_or_view, True)
            view = urls.get_callable(url_or_view)
            args = [Variable(arg).resolve(context) for arg in self.args]
            kwargs = {}
            for key, value in self.kwargs.items():
                kwargs[key] = Variable(value).resolve(context)

        try:
            if callable(view):
                return view(context['request'], *args, **kwargs).content
            raise "%r is not callable" % view
        except:
            #            if settings.TEMPLATE_DEBUG:
            raise
        return ""
Beispiel #9
0
 def render(self, context):
     """ Effectuer le rendu du nœud """
     # Renvoyer chaîne vide si aucune variable request à passer
     if 'request' not in context:
         return ''
     request = context['request']
     url_or_view = Variable(self.url_or_view).resolve(context)
     try:
         urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
         resolver = urls.RegexURLResolver(r'^/', urlconf)
         kwargs = {
             key: Variable(value).resolve(context)
             for (key, value) in self.kwargs.items()
         }
         url_or_view = urls.reverse(url_or_view, kwargs=kwargs)
         view, args, kwargs = resolver.resolve(url_or_view)
     except:
         view = urls.get_callable(url_or_view)
         args = [Variable(arg).resolve(context) for arg in self.args]
         kwargs = {
             key: Variable(value).resolve(context)
             for key, value in self.kwargs.items()
         }
     if callable(view):
         output = view(request, *args, **kwargs)
         return getattr(output, 'content', output)
     if settings.TEMPLATE_DEBUG:
         output = (_(
             "%(viewname)r is not a method or function and cannot be called"
         ) % {
             'viewname': view
         })
         raise ViewDoesNotExist(output)
     return ''
Beispiel #10
0
def can_url(user, view):
    """
    Tests whether the given user would have access to the view. The view can
    be a callable, importable text path or a view name, possibly with the
    namespace prefix ('namespace:view_name'). The view function must be
    decorated with the can_url_func (that's what UrlPatterns class does).
    """
    if ':' not in view:
        view = get_callable(view)

    if not callable(view):
        callbacks = get_all_callbacks(get_urlconf())
        if view not in callbacks:
            raise NoReverseMatch("Reverse for '%s' not found." % view)

        view = callbacks[view]

    if not hasattr(view, 'can_url_func'):
        raise NoReverseMatch(
            "Reverse for '%s' is not decorated with permissions." % view)

    try:
        return view.can_url_func(user)
    except PermissionDenied:
        return False
def oauth_user_auth(request):
    oauth_server, oauth_request = initialize_server_request(request)

    if oauth_request is None:
        return INVALID_PARAMS_RESPONSE

    try:
        token = oauth_server.fetch_request_token(oauth_request)
    except oauth.OAuthError as err:
        return send_oauth_error(err)

    try:
        callback = oauth_server.get_callback(oauth_request)
    except:
        callback = None

    if request.method == "GET":
        params = oauth_request.get_normalized_parameters()

        oauth_view = getattr(settings, 'OAUTH_AUTH_VIEW', None)
        if oauth_view is None:
            return oauth_auth_view(request, token, callback, params)
        else:
            return get_callable(oauth_view)(request, token, callback, params)
    elif request.method == "POST":
        try:
            form = forms.OAuthAuthenticationForm(request.POST)
            if form.is_valid():
                token = oauth_server.authorize_token(token, request.user)
                args = '?'+token.to_string(only_key=True)
            else:
                args = '?error=%s' % 'Access not granted by user.'

            if not callback:
                callback = getattr(settings, 'OAUTH_CALLBACK_VIEW')
                return get_callable(callback)(request, token)

            response = HttpResponseRedirect(callback+args)

        except oauth.OAuthError as err:
            response = send_oauth_error(err)
    else:
        response = HttpResponse('Action not allowed.')

    return response
Beispiel #12
0
def error_view(status_code):
    if status_code == 4031:
        return get_callable(settings.CSRF_FAILURE_VIEW)
    if status_code == 500:
        return handle_500
    exceptions = {
        400: SuspiciousOperation,
        403: PermissionDenied,
        404: Http404,
    }
    exception = exceptions[status_code]

    def error_view(request, *args, **kwargs):
        raise exception

    return error_view
Beispiel #13
0
    def get_payment_modules(self, request=None):
        """
        Import and return all payment modules defined in
        ``PLATA_PAYMENT_MODULES``

        If request is given only applicable modules are loaded.
        """
        all_modules = [
            get_callable(module)(self)
            for module in plata.settings.PLATA_PAYMENT_MODULES
        ]
        if not request:
            return all_modules
        return [
            module for module in all_modules
            if module.enabled_for_request(request)
        ]
    def fallback_view(self, request):
        """
        Runs the fallback view function in ``settings.MULTISITE_FALLBACK``.

        If ``MULTISITE_FALLBACK`` is None, raises an Http404 error.

        If ``MULTISITE_FALLBACK`` is callable, will treat that
        callable as a view that returns an HttpResponse.

        If ``MULTISITE_FALLBACK`` is a string, will resolve it to a
        view that returns an HttpResponse.

        In order to use a generic view that takes additional
        parameters, ``settings.MULTISITE_FALLBACK_KWARGS`` may be a
        dictionary of additional keyword arguments.
        """
        fallback = getattr(settings, 'MULTISITE_FALLBACK', None)
        if fallback is None:
            raise Http404
        if callable(fallback):
            view = fallback
        else:
            try:
                view = get_callable(fallback)
                if django.VERSION < (1,8):
                    # older django's get_callable falls through on error,
                    # returning the input as output
                    # which notably is definitely not a callable here
                    if not callable(view):
                        raise ImportError()
            except ImportError:
                # newer django forces this to be an error, which is tidier.
                # we rewrite the error to be a bit more helpful to our users.
                raise ImproperlyConfigured(
                    'settings.MULTISITE_FALLBACK is not callable: %s' %
                    fallback
                )

        kwargs = getattr(settings, 'MULTISITE_FALLBACK_KWARGS', {})
        if hasattr(view, 'as_view'):
            # Class-based view
            return view.as_view(**kwargs)(request)
        # View function
        return view(request, **kwargs)
Beispiel #15
0
 def _set_attr(self, prefix_name, value):
     name = prefix_name[len(self.prefix) + 1:]
     if name in ('GET_CACHE_KEY', 'GET_CACHE_VERSION'):
         try:
             if isinstance(value, str):
                 func = get_callable(value)
             elif callable(value):
                 func = value
             else:
                 raise ImproperlyConfigured(
                     f"{value} is not a valid value for `{name}`. "
                     "It must be a callable or a fullpath to callable. ")
         except Exception as e:
             raise ImproperlyConfigured(e)
         setattr(self, name, func)
         return func
     else:
         setattr(self, name, value)
         return value
Beispiel #16
0
    def fallback_view(self, request):
        """
        Runs the fallback view function in ``settings.MULTISITE_FALLBACK``.

        If ``MULTISITE_FALLBACK`` is None, raises an Http404 error.

        If ``MULTISITE_FALLBACK`` is callable, will treat that
        callable as a view that returns an HttpResponse.

        If ``MULTISITE_FALLBACK`` is a string, will resolve it to a
        view that returns an HttpResponse.

        In order to use a generic view that takes additional
        parameters, ``settings.MULTISITE_FALLBACK_KWARGS`` may be a
        dictionary of additional keyword arguments.
        """
        fallback = getattr(settings, 'MULTISITE_FALLBACK', None)
        if fallback is None:
            raise Http404
        if callable(fallback):
            view = fallback
        else:
            try:
                view = get_callable(fallback)
                if django.VERSION < (1, 8):
                    # older django's get_callable falls through on error,
                    # returning the input as output
                    # which notably is definitely not a callable here
                    if not callable(view):
                        raise ImportError()
            except ImportError:
                # newer django forces this to be an error, which is tidier.
                # we rewrite the error to be a bit more helpful to our users.
                raise ImproperlyConfigured(
                    'settings.MULTISITE_FALLBACK is not callable: %s' %
                    fallback)

        kwargs = getattr(settings, 'MULTISITE_FALLBACK_KWARGS', {})
        if hasattr(view, 'as_view'):
            # Class-based view
            return view.as_view(**kwargs)(request)
        # View function
        return view(request, **kwargs)
Beispiel #17
0
 def render(self, context):
     """ Effectuer le rendu du nœud """
     # Renvoyer chaîne vide si aucune variable request à passer
     if 'request' in context:
         request = context['request']
         view = urls.get_callable(Variable(self.view).resolve(context))
         args = [Variable(arg).resolve(context) for arg in self.args]
         kwargs = {
             key: Variable(value).resolve(context)
             for key, value in self.kwargs.items()
         }
         if callable(view):
             output = view(request, *args, **kwargs)
             return getattr(output, 'content', output)
         elif settings.TEMPLATE_DEBUG:
             output = _(
                 "{viewname} is not a method or function and cannot be called"
             ).format(viewname=view)
             raise ViewDoesNotExist(output)
     return ""
Beispiel #18
0
def get_resource_uri_template(self):
    """
    URI template processor.
    See http://bitworking.org/projects/URI-Templates/
    """

    def _convert(template, params=[]):
        """URI template converter"""
        paths = template % dict([p, "{%s}" % p] for p in params)
        return "%s%s" % (get_script_prefix(), paths)

    try:
        resource_uri = self.handler.resource_uri()
        components = [None, [], {}]

        for i, value in enumerate(resource_uri):
            components[i] = value
        lookup_view, args, kwargs = components
        try:
            lookup_view = get_callable(lookup_view)
        except (ImportError, ViewDoesNotExist):
            # Emulate can_fail=True from earlier django versions.
            pass

        possibilities = get_resolver(None).reverse_dict.getlist(lookup_view)
        # The monkey patch is right here: we need to cope with 'possibilities'
        # being a list of tuples with 2 or 3 elements.
        for possibility_data in possibilities:
            possibility = possibility_data[0]
            for result, params in possibility:
                if args:
                    if len(args) != len(params):
                        continue
                    return _convert(result, params)
                else:
                    if set(kwargs.keys()) != set(params):
                        continue
                    return _convert(result, params)
    except Exception:
        return None
Beispiel #19
0
def fix_references(fn, view_names):
    new_content = []
    with open(fn, 'r') as code:
        for line in code:
            m = dot_ref_re.search(line)
            if m:
                dotted = m.group('dotted')
                viewfunc = get_callable(dotted)
                newline = line.replace(dotted, view_names[viewfunc])
            else:
                newline = line
            new_content.append(newline)

            m = function_reverse_re.search(line)
            if m:
                print("function reference reverse() in ", fn)

            m = no_namespace_tag_re.search(line)
            if m:
                print("no namespace on {% url %} in ", fn)

    with open(fn, 'w') as py:
        py.write(''.join(new_content))
Beispiel #20
0
    def get_resource_uri_template(self):
        """
        URI template processor.
        
        See http://bitworking.org/projects/URI-Templates/
        """
        def _convert(template, params=[]):
            """URI template converter"""
            paths = template % dict([p, "{%s}" % p] for p in params)
            return '%s%s' % (get_script_prefix(), paths)
        
        try:
            resource_uri = self.handler.resource_uri()
            
            components = [None, [], {}]

            for i, value in enumerate(resource_uri):
                components[i] = value
        
            lookup_view, args, kwargs = components
            lookup_view = get_callable(lookup_view, True)

            possibilities = get_resolver(None).reverse_dict.getlist(lookup_view)
            
            for possibility, pattern in possibilities:
                for result, params in possibility:
                    if args:
                        if len(args) != len(params):
                            continue
                        return _convert(result, params)
                    else:
                        if set(kwargs.keys()) != set(params):
                            continue
                        return _convert(result, params)
        except:
            return None
Beispiel #21
0
    RetrieveUpdateDestroyProfileValidationSerializer,
)
from simple_login.views.base import (
    BaseAPIView,
    ProfileBaseAPIView,
    AuthenticatedRequestBaseAPIView,
)
from simple_login import models
from simple_login.utils.otp import OTPHandler
from simple_login.utils.auth import AuthMethod
from simple_login.utils import social
from simple_login.utils.user import UserHelpers
from simple_login import serializers


SERIALIZER = get_callable(settings.AUTH_USER_SERIALIZER) if hasattr(settings, 'AUTH_USER_SERIALIZER') else \
    serializers.AuthUserSerializer


def get_unique_username(user_model, username_desired, append_id=0):
    username = username_desired
    if user_model.objects.filter(username=username).count() > 0:
        username = '******'.format(username, append_id)
        get_unique_username(user_model, username, append_id)
    return username


def download_and_set_photo(url, instance, field, is_facebook=False):
    if is_facebook:
        filename = url.split('?')[0].split('/')[-1]
    else:
Beispiel #22
0
        url(r'^api/auth-n/',
            include('rest_framework.urls', namespace='rest_framework')),
    ]

if settings.DEBUG:
    from django.views import defaults as dj_default_views
    from django.urls import get_callable

    urlpatterns += [
        url(r'^400/$',
            dj_default_views.bad_request,
            kwargs={'exception': Exception('Bad Request!')}),
        url(r'^403/$',
            dj_default_views.permission_denied,
            kwargs={'exception': Exception('Permission Denied!')}),
        url(r'^403_csrf/$', get_callable(settings.CSRF_FAILURE_VIEW)),
        url(r'^404/$',
            dj_default_views.page_not_found,
            kwargs={'exception': Exception('Not Found!')}),
        url(r'^500/$', handler500),
    ]

    # Django Debug Toolbar
    try:
        import debug_toolbar
        urlpatterns += [
            url(r'^__debug__/', include(debug_toolbar.urls)),
        ]
    except ImportError:
        pass
Beispiel #23
0
 def _render_throttling(self, request, exception):
     return get_callable(settings.THROTTLING_FAILURE_VIEW)(request,
                                                           exception)
Beispiel #24
0
def getEditorClass():
    global _EditorClass
    if not _EditorClass:
        _EditorClass = get_callable(settings.EDITOR)
    return _EditorClass
Beispiel #25
0
def get_disabled_view():
    module = settings.FEATUREFLAGS_DISABLED_VIEW
    return get_callable(module)
Beispiel #26
0
    def test_view_loading(self):
        self.assertEqual(get_callable('urlpatterns_reverse.views.empty_view'), empty_view)

        # passing a callable should return the callable
        self.assertEqual(get_callable(empty_view), empty_view)
Beispiel #27
0
def _get_failure_view():
    """
    Returns the view to be used for CSRF rejections
    """
    return get_callable(settings.CSRF_FAILURE_VIEW)
Beispiel #28
0
#     return datetime.datetime(d.year, 1, 1, 0, 0, 0, 0, pytz.timezone(settings.TIME_ZONE))
#
#
# def get_end_of_this_year():
#     d = datetime.datetime.today()
#     return datetime.datetime(d.year + 1, 1, 1, 0, 0, 0, 0, pytz.timezone(settings.TIME_ZONE))

import datetime
"""
Documented
"""
# a function to control be dbfield on all instances, Saves you time to subclass ifonly you need to add a help text or something
RA_FORMFIELD_FOR_DBFIELD_FUNC = getattr(
    settings, 'RA_FORMFIELD_FOR_DBFIELD_FUNC',
    'ra.base.helpers.default_formfield_for_dbfield')
RA_FORMFIELD_FOR_DBFIELD_FUNC = get_callable(RA_FORMFIELD_FOR_DBFIELD_FUNC)
# ------

# Navigation class
RA_NAVIGATION_CLASS = getattr(settings, 'RA_NAVIGATION_CLASS',
                              'ra.utils.navigation.RaSuitMenu')
"""
UnDocumented
"""

RA_ENABLE_ADMIN_DELETE_ALL = getattr(settings, 'RA_ENABLE_ADMIN_DELETE_ALL',
                                     False)

# RA_DEFAULT_FROM_DATETIME = lazy(get_first_of_this_year, datetime.datetime)()
# RA_DEFAULT_TO_DATETIME = lazy(get_end_of_this_year, datetime.datetime)()
# # models
Beispiel #29
0
 def build_views(self):
     for view_str in self.view_list:
         view = get_callable(view_str)
         view(_exporting_event=self._exporting_event).build_method()
Beispiel #30
0
    except ImportError as e:
        raise ImportError(
            'Failed to import class "%s" from module "%s". Reason: %s.' %
            (klass, module, e))
    try:
        klass = getattr(module, klass)
    except AttributeError:
        raise AttributeError('Module "%s" does not define a "%s" class.' %
                             (module.__name__, klass))

    return klass


# Make use of django-autoslug compatible slugify function.

slugify = getattr(settings, 'AUTOSLUG_SLUGIFY_FUNCTION', None)

if not slugify:
    try:
        from unidecode import unidecode
        slugify = lambda s: unidecode(s).replace(' ', '-')
    except ImportError:
        try:
            from pytils.translit import slugify
        except ImportError:
            slugify = 'django.template.defaultfilters.slugify'

if isinstance(slugify, six.string_types):
    from django.urls import get_callable
    slugify = get_callable(slugify)
Beispiel #31
0
if settings.API_DEBUG:
    urlpatterns += [
        # Browsable API
        url('^schema/$', api_schemas.schema_view, name='schema'),
        url(r'^api-playground/$', api_schemas.swagger_schema_view, name='api-playground'),
        url(r'^api/auth-n/', include('rest_framework.urls', namespace='rest_framework')),
    ]

if settings.DEBUG:
    from django.views import defaults as dj_default_views
    from django.urls import get_callable

    urlpatterns += [
        url(r'^400/$', dj_default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}),
        url(r'^403/$', dj_default_views.permission_denied, kwargs={'exception': Exception('Permission Denied!')}),
        url(r'^403_csrf/$', get_callable(settings.CSRF_FAILURE_VIEW)),
        url(r'^404/$', dj_default_views.page_not_found, kwargs={'exception': Exception('Not Found!')}),
        url(r'^500/$', handler500),
    ]

    # Django Debug Toolbar
    try:
        import debug_toolbar
        urlpatterns += [url(r'^__debug__/', include(debug_toolbar.urls)), ]
    except ImportError:
        pass

    # Livereloading
    try:
        from devrecargar.urls import urlpatterns as devrecargar_urls
        urlpatterns += [url(r'^devrecargar/', include((devrecargar_urls, 'devrecargar', ), namespace='devrecargar'))]
Beispiel #32
0
def user_authorization(request, form_class=AuthorizeRequestTokenForm):
    oauth_token = request.POST.get('oauth_token',
                                   request.GET.get('oauth_token'))
    if not oauth_token:
        return HttpResponseBadRequest('No request token specified.')

    oauth_request = get_oauth_request(request)

    try:
        request_token = store.get_request_token(request, oauth_request,
                                                oauth_token)
    except InvalidTokenError:
        return HttpResponseBadRequest('Invalid request token.')

    consumer = store.get_consumer_for_request_token(request, oauth_request,
                                                    request_token)

    if request.method == 'POST':
        form = form_class(request.POST)
        if request.session.get('oauth',
                               '') == request_token.key and form.is_valid():
            request.session['oauth'] = ''
            if form.cleaned_data['authorize_access']:
                request_token = store.authorize_request_token(
                    request, oauth_request, request_token)
                args = {'oauth_token': request_token.key}
            else:
                args = {'error': _('Access not granted by user.')}
            if request_token.callback is not None and request_token.callback != OUT_OF_BAND:
                callback_url = request_token.get_callback_url(args)
                if UNSAFE_REDIRECTS:
                    response = UnsafeRedirect(callback_url)
                else:
                    response = HttpResponseRedirect(callback_url)
            else:
                # try to get custom callback view
                callback_view_str = getattr(
                    settings, OAUTH_CALLBACK_VIEW,
                    'oauth_provider.views.fake_callback_view')
                try:
                    view_callable = get_callable(callback_view_str)
                except AttributeError:
                    raise Exception("%s view doesn't exist." %
                                    callback_view_str)

                # try to treat it as Class Based View (CBV)
                try:
                    callback_view = view_callable.as_view()
                except AttributeError:
                    # if it appears not to be CBV treat it like FBV
                    callback_view = view_callable

                response = callback_view(request, **args)
        else:
            response = send_oauth_error(oauth.Error(_('Action not allowed.')))
    else:
        # try to get custom authorize view
        authorize_view_str = getattr(
            settings, OAUTH_AUTHORIZE_VIEW,
            'oauth_provider.views.fake_authorize_view')
        try:
            view_callable = get_callable(authorize_view_str)
        except AttributeError:
            raise Exception("%s view doesn't exist." % authorize_view_str)

        # try to treat it as Class Based View (CBV)
        try:
            authorize_view = view_callable.as_view()
        except AttributeError:
            # if it appears not to be CBV treat it like FBV
            authorize_view = view_callable

        params = oauth_request.get_normalized_parameters()
        # set the oauth flag
        request.session['oauth'] = request_token.key
        response = authorize_view(request, request_token,
                                  request_token.get_callback_url(), params)

    return response
Beispiel #33
0
 def _render_throttling(self, request, exception):
     return get_callable(settings.THROTTLING_FAILURE_VIEW)(request, exception)
Beispiel #34
0
def _get_failure_view():
    """
    Returns the view to be used for CSRF rejections
    """
    return get_callable(settings.CSRF_FAILURE_VIEW)
Beispiel #35
0
# Only translate the urls if `TRANSLATE_URLS` is `True`.
if getattr(settings, 'TRANSLATE_URLS', False):
    _ = ugettext_lazy
else:

    def _(s):
        return s


auth_login_form = getattr(
    settings,
    'INCUNA_AUTH_LOGIN_FORM',
    'django.contrib.auth.forms.AuthenticationForm',
)
auth_form = get_callable(auth_login_form)

password_reset_form = getattr(
    settings,
    'INCUNA_PASSWORD_RESET_FORM',
    'incuna_auth.forms.CrispyPasswordResetForm',
)
reset_form = get_callable(password_reset_form)

urlpatterns = [
    url(
        _(r'^login/$'),
        views.LoginView.as_view(authentication_form=auth_form),
        name='login',
    ),
    url(
Beispiel #36
0
from django.conf import settings
from django.contrib.staticfiles import finders
from django.core import mail
from django.core.exceptions import ValidationError
from django.core.files.storage import DefaultStorage, default_storage
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.template.loader import render_to_string
from django.urls import get_callable, reverse
from django.utils.html import format_html
from premailer import transform
from resizeimage.resizeimage import resize_contain

slugify_function_path = \
    getattr(settings, 'AUTOSLUG_SLUGIFY_FUNCTION', 'autoslug.utils.slugify')

slugify = get_callable(slugify_function_path)


def client_ip_from_request(request):
    """Returns the IP of the request, accounting for the possibility of being behind a proxy.
    """
    ip = request.META.get("HTTP_X_FORWARDED_FOR", None)
    if ip:
        # X_FORWARDED_FOR returns client1, proxy1, proxy2,...
        ip = ip.split(", ")[0]
    else:
        ip = request.META.get("REMOTE_ADDR", "")
    return ip


class OriginSettingsObject(object):
Beispiel #37
0
def render_inertia(request, component_name, props=None, template_name=None):
    """
    Renders either an HttpRespone or JsonResponse of a component for
    the use in an InertiaJS frontend integration.
    """
    inertia_template = None
    inertia_template = getattr(settings, "INERTIA_TEMPLATE", "base.html")

    if template_name is not None:
        inertia_template = template_name

    if inertia_template is None:
        raise ImproperlyConfigured(
            "No Inertia template found. Either set INERTIA_TEMPLATE"
            "in settings.py or pass template parameter."
        )

    # share custom data or default authenticated user
    share_method_path = getattr(settings, "INERTIA_SHARE", "inertia.share.share_auth")
    if share_method_path:
        share_method = get_callable(share_method_path)
        share_method(request)

    if props is None:
        props = {}
    shared = {}
    if hasattr(request, "session"):
        for k, v in request.session.get("share", {}).items():
            log.debug((k,v))
            shared[k]=v
        props.update(shared)

    for key in ("success", "error", "errors"):
        if hasattr(request, "session") and request.session.get(key):
            del request.session[key]

    # subsequent renders
    inertia_version = get_version()
    is_version_correct = 'X-Inertia-Version' in request.headers and \
                         request.headers["X-Inertia-Version"] == str(inertia_version)

    # check if partial reload is requested
    only_props = request.headers.get("X-Inertia-Partial-Data", [])
    if (
        only_props
        and request.headers.get("X-Inertia-Partial-Component", "") == component_name
    ):
        _props = {}
        for key in props:
            if key in only_props:
                _props.update({key: props[key]})
    else:
        _props = props

    # lazy load props and make request available to props being lazy loaded
    load_lazy_props(_props, request)

    if 'X-Inertia' in request.headers:
        response = JsonResponse({
            "component": component_name,
            "props": _props,
            "version": inertia_version,
            "url": request.get_full_path()
        })
        response['X-Inertia'] = True
        response['Vary'] = 'Accept'
        return response
    context = _build_context(component_name, _props,
                             inertia_version,
                             url=request.get_full_path())
    return render(request, inertia_template, context)
Beispiel #38
0
if settings.DEBUG:
    from django.urls import get_callable
    from django.views import defaults as dj_default_views

    urlpatterns += [
        path(
            "400/",
            dj_default_views.bad_request,
            kwargs={"exception": Exception("Bad Request!")},
        ),
        path(
            "403/",
            dj_default_views.permission_denied,
            kwargs={"exception": Exception("Permission Denied!")},
        ),
        path("403_csrf/", get_callable(settings.CSRF_FAILURE_VIEW)),
        path(
            "404/",
            dj_default_views.page_not_found,
            kwargs={"exception": Exception("Not Found!")},
        ),
        path("500/", handler500),
    ]

    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

    # Django Debug Toolbar
    if "debug_toolbar" in settings.INSTALLED_APPS:
        import debug_toolbar
Beispiel #39
0
if settings.DEBUG:
    from django.views import defaults as dj_default_views
    from django.urls import get_callable

    # ERROR URLs
    # --------------------------------------------------------------------------
    urlpatterns += [
        url(r'^400/$',
            dj_default_views.bad_request,
            kwargs={'exception': Exception('Bad Request.')}),
        url(r'^403/$',
            dj_default_views.permission_denied,
            kwargs={'exception': Exception('Permission Denied.')}),
        url(r'^403_csrf/$',
            get_callable(settings.CSRF_FAILURE_VIEW)),
        url(r'^404/$',
            dj_default_views.page_not_found,
            kwargs={'exception': Exception('Page Not Found.')}),
        url(r'^500/$',
            dj_default_views.server_error),
    ]

    # django-debug-toolbar URLs
    # --------------------------------------------------------------------------
    try:
        import debug_toolbar
        urlpatterns += [
            url(r'^__debug__/', include(debug_toolbar.urls)),
        ]
    except ImportError: