Ejemplo n.º 1
0
 def get_context_data(self, **kwargs):
     context = super(AuthMixin, self).get_context_data(**kwargs)
     # URLs for user
     if not is_authenticated(self.request):
         user_urls = {
             'login_github': reverse('social:begin', args=('github', )),
             'login_google': reverse('social:begin',
                                     args=('google-oauth2', )),
             'login_twitter': reverse('social:begin', args=('twitter', )),
         }
         if 'urls' in context:
             if 'user' in context['urls']:
                 context['urls']['user'].update(user_urls)
             else:
                 context['urls'].update({'user': user_urls})
         else:
             context.update({'urls': {'user': user_urls}})
     urls_default = {
         'pricing': reverse('saas_cart_plan_list'),
     }
     if 'urls' in context:
         context['urls'].update(urls_default)
     else:
         context.update({'urls': urls_default})
     return context
Ejemplo n.º 2
0
 def get_initial(self):
     kwargs = super(ContactView, self).get_initial()
     if is_authenticated(self.request):
         kwargs.update({
             'email': self.request.user.email,
             'full_name': self.request.user.get_full_name()})
     return kwargs
Ejemplo n.º 3
0
 def get_context_data(self, **kwargs):
     context = super(DjaoAppMixin, self).get_context_data(**kwargs)
     context.update({'edit_perm': self.edit_perm})  # XXX _appmenu.html
     if self.organization:
         if not Plan.objects.filter(
                 organization=self.organization).exists():
             context.update({'next_url': reverse('saas_cart_plan_list')})
     # URLs for user
     if is_authenticated(self.request):
         urls = {
             'user': {
                 'logout':
                 reverse('logout'),
                 'profile':
                 reverse('users_profile', args=(self.request.user, )),
             }
         }
     else:
         urls = {
             'user': {
                 'login':
                 reverse('login'),
                 'login_github':
                 reverse('social:begin', args=('github', )),
                 'login_google':
                 reverse('social:begin', args=('google-oauth2', )),
                 'login_twitter':
                 reverse('social:begin', args=('twitter', )),
                 'password_reset':
                 reverse('password_reset'),
                 'register':
                 reverse('registration_register'),
             }
         }
     # URLs for provider
     app = get_current_app()
     # ``app.account`` is guarenteed to be in the same database as ``app``.
     # ``site.account`` is always in the *default* database, which is not
     # the expected database ``Organization`` are typically queried from.
     provider = app.account
     if not fail_direct(self.request, organization=provider):
         urls.update({
             'provider': {
                 'dashboard': reverse('saas_dashboard', args=(provider, )),
             }
         })
     if 'urls' in context:
         for key, val in six.iteritems(urls):
             if key in context['urls']:
                 context['urls'][key].update(val)
             else:
                 context['urls'].update({key: val})
     else:
         context.update({'urls': urls})
     return context
Ejemplo n.º 4
0
    def post(self, request, *args, **kwargs):
        #pylint:disable=too-many-locals,unused-argument
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        if is_authenticated(self.request):
            user = self.request.user
        else:
            user_model = get_user_model()
            email = serializer.validated_data.get('email', None)
            try:
                user = user_model.objects.get(email=email)
            except user_model.DoesNotExist:
                #pylint:disable=unused-variable
                first_name, mid, last_name = full_name_natural_split(
                    serializer.validated_data.get('full_name', None))
                user = user_model(email=email,
                                  first_name=first_name,
                                  last_name=last_name)
        message = serializer.validated_data.get('message', '')
        provider = serializer.validated_data.get('provider', self.provider)
        items = []
        for key, value in six.iteritems(serializer.data):
            if value and not (key in serializer.validated_data or key in (
                    'captcha', 'g-recaptcha-response', 'csrfmiddlewaretoken')):
                items += [(key, value)]
        if message:
            items += [("Message", message)]
        if not user.email:
            return Response({'detail':
            _("Thank you for the feedback. Please feel free to leave your contact"\
" information next time so we can serve you better.")})
        if provider:
            provider = get_object_or_404(Organization, slug=provider)
        else:
            provider = self.provider
        try:
            contact_requested.send(sender=__name__,
                                   provider=provider,
                                   user=user,
                                   reason=items,
                                   request=self.request)
            return Response({
                'detail':
                _("Your request has been sent. We will reply within 24 hours. Thank you."
                  )
            })
        except (SMTPException, socket.error) as err:
            LOGGER.exception("%s on page %s", err, self.request.get_raw_uri())
            return Response({'detail':
                             _("Sorry, there was an issue sending your request for information"\
" to '%(full_name)s <%(email)s>'.") % {
            'full_name': provider.full_name, 'email': provider.email}})
Ejemplo n.º 5
0
    def form_valid(self, form):
        if is_authenticated(self.request):
            user = self.request.user
        else:
            user_model = get_user_model()
            email = form.cleaned_data.get('email', None)
            try:
                user = user_model.objects.get(email=email)
            except user_model.DoesNotExist:
                #pylint:disable=unused-variable
                first_name, mid, last_name = full_name_natural_split(
                    form.cleaned_data.get('full_name', None))
                user = user_model(email=email,
                                  first_name=first_name,
                                  last_name=last_name)
        message = form.cleaned_data.get('message', '')
        provider = form.cleaned_data.get('provider', self.provider)
        items = []
        for key, value in six.iteritems(form.data):
            if value and not (key in form.cleaned_data or key in (
                    'captcha', 'g-recaptcha-response', 'csrfmiddlewaretoken')):
                items += [(key, value)]
        if message:
            items += [("Message", message)]
        if user.email:
            if provider:
                provider = get_object_or_404(Organization, slug=provider)
            else:
                provider = self.provider
            try:
                contact_requested.send(sender=__name__,
                                       provider=provider,
                                       user=user,
                                       reason=items,
                                       request=self.request)
                messages.info(
                    self.request,
                    _("Your request has been sent. We will reply within 24 hours. Thank you."
                      ))
            except (SMTPException, socket.error) as err:
                LOGGER.exception("%s on page %s", err,
                                 self.request.get_raw_uri())
                messages.error(self.request,
                _("Sorry, there was an issue sending your request for information"\
    " to '%(full_name)s <%(email)s>'.") % {
                'full_name': provider.full_name, 'email': provider.email})
        else:
            messages.warning(self.request,
            _("Thank you for the feedback. Please feel free to leave your contact"\
" information next time so we can serve you better."))
        return http.HttpResponseRedirect(self.get_success_url())
Ejemplo n.º 6
0
def inject_edition_tools(response,
                         request,
                         context=None,
                         body_top_template_name=None,
                         body_bottom_template_name=None):
    """
    If the ``request.user`` has editable permissions, this method
    injects the edition tools into the html *content* and return
    a BeautifulSoup object of the resulting content + tools.

    If the response is editable according to the proxy rules, this
    method returns a BeautifulSoup object of the content such that
    ``PageMixin`` inserts the edited page elements.
    """
    #pylint:disable=too-many-locals,too-many-nested-blocks,too-many-statements
    content_type = response.get('content-type', '')
    if not content_type.startswith('text/html'):
        return None

    if context is None:
        context = {}
    dj_urls = {}
    edit_urls = {}
    provider_urls = {}
    site = get_current_site()
    app = get_current_app()
    # ``app.account`` is guarenteed to be in the same database as ``app``.
    # ``site.account`` is always in the *default* database, which is not
    # the expected database ``Organization`` are typically queried from.
    provider = app.account
    enable_code_editor = False
    edit_urls = {
        'api_medias': reverse('uploaded_media_elements', kwargs={'path': ''}),
        'api_sitecss': reverse('edit_sitecss'),
        'api_less_overrides': reverse('pages_api_less_overrides'),
        'api_sources': reverse('pages_api_sources'),
        'api_page_elements': reverse('page_elements'),
        'api_plans': reverse('saas_api_plans', args=(provider, )),
        'plan_update_base': reverse('saas_plan_base', args=(provider, ))
    }
    if not fail_edit_perm(request, account=provider):
        # XXX `not fail_edit_perm` will pass even if site is testing, which
        # puts the tools to edit online. Error of duplicate remains.
        if is_testing(site):
            if has_bank_account(provider):
                body_top_template_name = "pages/_body_top_testing_manager.html"
            else:
                provider_urls = {
                    'bank': reverse('saas_update_bank', args=(provider, ))
                }
                body_top_template_name = \
                    "pages/_body_top_testing_no_processor_manager.html"
        elif not has_bank_account(provider) and (
                request and request.path.endswith('/cart/')):
            provider_urls = {
                'bank': reverse('saas_update_bank', args=(provider, ))
            }
            body_top_template_name = "pages/_body_top_no_processor_manager.html"
        try:
            # The following statement will raise an Exception
            # when we are dealing with a ``FileSystemStorage``.
            _ = get_storage_class().bucket_name
            edit_urls.update(
                {'media_upload': reverse('api_credentials_organization')})
        except AttributeError:
            LOGGER.debug("doesn't look like we have a S3Storage.")
        # XXX sites which are hosted on a same domain shouldn't disable
        # all edit functionality, just the edition of base templates.
        enable_code_editor = is_domain_site(site)
        if enable_code_editor:
            dj_urls = djaoapp_urls(request,
                                   account=provider,
                                   base=site.as_base())
            body_bottom_template_name = "pages/_body_bottom_edit_tools.html"
        else:
            dj_urls = djaoapp_urls(request, account=provider)
            body_bottom_template_name = "pages/_body_bottom.html"
    else:
        if is_testing(site):
            if has_bank_account(provider):
                body_top_template_name = "pages/_body_top_testing.html"
            else:
                body_top_template_name \
                    = "pages/_body_top_testing_no_processor.html"
        elif not has_bank_account(provider) and (
                request and request.path.endswith('/cart/')):
            body_top_template_name = "pages/_body_top_no_processor.html"
    context.update({
        'ENABLE_CODE_EDITOR': enable_code_editor,
        'FEATURE_DEBUG': settings.FEATURES_DEBUG,
        'urls': {
            'provider': provider_urls,
            'djaodjin': dj_urls,
            'edit': edit_urls
        }
    })
    context.update(csrf(request))
    soup = None
    if app.show_edit_tools:
        soup = pages_inject_edition_tools(
            response,
            request,
            context=context,
            body_top_template_name=body_top_template_name,
            body_bottom_template_name=body_bottom_template_name)

    # Insert the authenticated user information and roles on organization.
    if is_authenticated(request):
        if not soup:
            soup = BeautifulSoup(response.content, 'html5lib')
        if soup and soup.body:
            # Implementation Note: we have to use ``.body.next`` here
            # because html5lib "fixes" our HTML by adding missing
            # html/body tags. Furthermore if we use
            #``soup.body.insert(1, BeautifulSoup(body_top, 'html.parser'))``
            # instead, later on ``soup.find_all(class_=...)`` returns
            # an empty set though ``soup.prettify()`` outputs the full
            # expected HTML text.
            auth_user = soup.body.find(class_='header-menubar')
            user_menu_template = '_menubar.html'
            if (request.user.is_authenticated and auth_user
                    and user_menu_template):
                serializer_class = import_string(
                    rules_settings.SESSION_SERIALIZER)
                serializer = serializer_class(request)
                path_parts = reversed(request.path.split('/'))
                top_accessibles = []
                has_broker_role = False
                active_organization = None
                for role, organizations in six.iteritems(
                        serializer.data['roles']):
                    for organization in organizations:
                        if organization['slug'] == request.user.username:
                            # Personal Organization
                            continue
                        db_obj = Organization.objects.get(
                            slug=organization['slug'])  # XXX Remove query.
                        if db_obj.is_provider:
                            settings_location = reverse(
                                'saas_dashboard',
                                args=(organization['slug'], ))
                        else:
                            settings_location = reverse(
                                'saas_organization_profile',
                                args=(organization['slug'], ))
                        app_location = reverse('organization_app',
                                               args=(organization['slug'], ))
                        if organization['slug'] in path_parts:
                            active_organization = TopAccessibleOrganization(
                                organization['slug'],
                                organization['printable_name'],
                                settings_location, role, app_location)
                        if is_broker(organization['slug']):
                            has_broker_role = True
                        top_accessibles += [
                            TopAccessibleOrganization(
                                organization['slug'],
                                organization['printable_name'],
                                settings_location, role, app_location)
                        ]
                if not active_organization and has_broker_role:
                    active_organization = get_broker()
                context.update({'active_organization': active_organization})
                context.update({'top_accessibles': top_accessibles})
                template = loader.get_template(user_menu_template)
                user_menu = render_template(template, context, request).strip()
                auth_user.clear()
                els = BeautifulSoup(user_menu, 'html5lib').body.ul.children
                for elem in els:
                    auth_user.append(BeautifulSoup(str(elem), 'html5lib'))
    return soup
Ejemplo n.º 7
0
 def wrapped(request, *args, **kwargs):
     if is_authenticated(request):
         return HttpResponseRedirect(next_url)
     return func(request, *args, **kwargs)
Ejemplo n.º 8
0
 def get(self, request, *args, **kwargs):
     if is_authenticated(self.request):
         self.request.session['mydata'] = 'dummy'
     return super(IndexView, self).get(request, *args, **kwargs)