django.http.HttpResponseRedirect

Here are the examples of the python api django.http.HttpResponseRedirect taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

177 Examples 7

Example 101

Project: indextank-service Source File: views.py
@login_required
def dashboard(request):
    # Possible statuses:
    #    - No index
    #    - Index but no docs
    #    - Index with docs

    account_status = None
    
    if request.user.get_profile().change_password:
        messages.info(request, 'Your password was reset and you need to change it.')
        return HttpResponseRedirect(reverse('change_password'))
    
    account = request.user.get_profile().account
    
    #if not account.package:
    #    return HttpResponseRedirect(reverse('select_package'))
    if not account.status == Account.Statuses.operational and not account.payment_informations.count():
        if account.package.base_price > 0:
            messages.info(request, 'Before accessing your dashboard you need to enter your payment information')
            return HttpResponseRedirect(reverse('enter_payment'))
        elif account.status == Account.Statuses.creating:
            account.status = Account.Statuses.operational
            
            mail.report_new_account(account)
            account.save()
        else:
            return HttpResponseRedirect(reverse('logout'))
    
    indexes = account.indexes.filter(deleted=False)
    
    has_indexes_left = (len(indexes) < account.package.max_indexes)
  
    totals = dict(size=0, docs=0, qpd=0)  
    for index in indexes:
        totals['docs'] += index.current_docs_number
        totals['size'] += index.current_size
        totals['qpd'] += index.queries_per_day
  
    if len(indexes) == 0:
        account_status = 'NOINDEX'
    elif totals['docs'] == 0:
        account_status = 'INDEXNODOCS'
    else:
        account_status = 'INDEXWITHDOCS'
    
    percentages = {}
    def add_percentage(k, max, t, p):
        p[k] = 100.0 * t[k] / max
    
    KB = 1024
    MB = KB * KB
    max_docs = account.package.index_max_size
    max_size = account.package.max_size_mb()
    max_qpd = account.package.searches_per_day
    
    add_percentage('docs', max_docs, totals, percentages)
    add_percentage('size', max_size, totals, percentages)
    add_percentage('qpd', max_qpd, totals, percentages)
    
    for index in indexes:
        insights = {}
        insights_update = {}
        #for i in index.insights.all():
        #    try:
        #        insights[i.code] = json.loads(i.data)
        #        insights_update[i.code] = i.last_update
        #    except:
        #        print 'Failed to load insight %s for %s' % (i.code, index.code)
        #index.insights_map = insights
        #index.insights_update = insights_update
  
    context = {
        'account': account,
        'indexes': indexes,
        'has_indexes_left': has_indexes_left,
        'account_status': account_status,
        'totals': totals,
        'percentages': percentages,
        'navigation_pos': 'dashboard',
    }

    return render('dashboard.html', request, context_dict=context)

Example 102

Project: wikicoding Source File: decorators.py
def get_article(func=None, can_read=True, can_write=False, 
                 deleted_contents=False, not_locked=False,
                 can_delete=False, can_moderate=False,
                 can_create=False):
    """View decorator for processing standard url keyword args: Intercepts the 
    keyword args path or article_id and looks up an article, calling the decorated 
    func with this ID.
    
    Will accept a func(request, article, *args, **kwargs)
    
    NB! This function will redirect if an article does not exist, permissions
    are missing or the article is deleted.
    
    Arguments:
    
    can_read=True and/or can_write=True: Check that the current request.user
    has correct permissions.
    
    can_delete and can_moderate: Verifies with wiki.core.permissions
    
    can_create: Same as can_write but adds an extra global setting for anonymous access (ANONYMOUS_CREATE)

    deleted_contents=True: Do not redirect if the article has been deleted.
    
    not_locked=True: Return permission denied if the article is locked
    
    Also see: wiki.views.mixins.ArticleMixin 
    """
    
    def wrapper(request, *args, **kwargs):
        from . import models

        path = kwargs.pop('path', None)
        article_id = kwargs.pop('article_id', None)
        language = kwargs.pop('language', '_')
                
        urlpath = None
        
        # fetch by urlpath.path
        if not path is None:
            try:
                urlpath = models.URLPath.get_by_path(path=path, language=language, select_related=True)
            except NoRootURL:
                return redirect('wiki:root_create')
            except models.URLPath.DoesNotExist:
                try:
                    pathlist = list(filter(lambda x: x!="", path.split("/"),))
                    path = "/".join(pathlist[:-1])
                    parent = models.URLPath.get_by_path(path=path, language=language)
                    return HttpResponseRedirect(reverse("wiki:create", kwargs={'language': language, 'path': parent.path}) + "?slug=%s" % pathlist[-1])
                except models.URLPath.DoesNotExist:
                    c = RequestContext(request, {'error_type' : 'ancestors_missing'})
                    return HttpResponseNotFound(render_to_string("wiki/error.html", context_instance=c))
            if urlpath.article:
                # urlpath is already smart about prefetching items on article (like current_revision), so we don't have to
                article = urlpath.article
            else:
                # Be robust: Somehow article is gone but urlpath exists... clean up
                return_url = reverse('wiki:get', kwargs={'path': urlpath.parent.path})
                urlpath.delete()
                return HttpResponseRedirect(return_url)
        
        
        # fetch by article.id
        elif article_id:
            #TODO We should try to grab the article form URLPath so the caching is good, and fall back to grabbing it from Article.objects if not
            articles = models.Article.objects
            
            article = get_object_or_404(articles, id=article_id)
            try:
                urlpath = models.URLPath.objects.get(articles__article=article)
            except models.URLPath.DoesNotExist as noarticle:
                models.URLPath.MultipleObjectsReturned = noarticle
                urlpath = None
        
        
        else:
            raise TypeError('You should specify either article_id or path')
        
        if not deleted_contents:    
            # If the article has been deleted, show a special page.        
            if urlpath:
                if urlpath.is_deleted(): # This also checks all ancestors
                    return redirect('wiki:deleted', path=urlpath.path)
            else:
                if article.current_revision and article.current_revision.deleted:
                    return redirect('wiki:deleted', article_id=article.id)
        
        
        if article.current_revision.locked and not_locked:
            return response_forbidden(request, article, urlpath)

        if can_read and not article.can_read(request.user):
            return response_forbidden(request, article, urlpath)
        
        if (can_write or can_create) and not article.can_write(request.user):
            return response_forbidden(request, article, urlpath)

        if can_create and not (request.user.is_authenticated() or settings.ANONYMOUS_CREATE):
            return response_forbidden(request, article, urlpath)
        
        if can_delete and not article.can_delete(request.user):
            return response_forbidden(request, article, urlpath)
            
        if can_moderate and not article.can_moderate(request.user):
            return response_forbidden(request, article, urlpath)
        
        kwargs['urlpath'] = urlpath
        
        return func(request, article, *args, **kwargs)
    
    if func:
        return wrapper
    else:
        return lambda func: get_article(func, can_read=can_read, can_write=can_write, 
                                        deleted_contents=deleted_contents,
                                        not_locked=not_locked,can_delete=can_delete,
                                        can_moderate=can_moderate, can_create=can_create)

Example 103

Project: synnefo Source File: __init__.py
@transaction.commit_on_success
def handle_third_party_login(request, provider_module, identifier,
                             provider_info=None, affiliation=None,
                             third_party_key=None, user_info=None):

    if not provider_info:
        provider_info = {}

    if not affiliation:
        affiliation = provider_module.title()

    next_redirect = request.GET.get(
        'next', request.session.get('next_url', None))

    if 'next_url' in request.session:
        del request.session['next_url']

    third_party_request_params = get_third_party_session_params(request)
    # from_login = third_party_request_params.get('from_login', False)
    switch_from = third_party_request_params.get('switch_from', False)
    provider_data = {
        'affiliation': affiliation,
        'info': provider_info
    }

    provider = auth_providers.get_provider(provider_module, request.user,
                                           identifier, **provider_data)

    # an existing user accessed the view
    if request.user.is_authenticated():
        if request.user.has_auth_provider(provider.module,
                                          identifier=identifier):
            return HttpResponseRedirect(reverse('edit_profile'))

        if provider.verified_exists():
            provider.log("add failed (identifier exists to another user)")
            messages.error(request, provider.get_add_exists_msg)
            return HttpResponseRedirect(reverse('edit_profile'))

        # automatically add identifier provider to user
        if not switch_from and not provider.get_add_policy:
            # TODO: handle existing uuid message separately
            provider.log("user cannot add provider")
            messages.error(request, provider.get_add_failed_msg)
            return HttpResponseRedirect(reverse('edit_profile'))

        user = request.user
        if switch_from:
            existing_provider = \
                request.user.auth_providers.active().get(
                    pk=int(switch_from), module=provider_module).settings

            # this is not a provider removal so we don't not use
            # provider.remove_from_user. Use low level access to the provider
            # db instance.
            if not provider.verified_exists():
                if provider.get_add_policy:
                    existing_provider._instance.delete()
                    existing_provider.log("removed")
                    provider.add_to_user()
                    provider.log("added")
            else:
                messages.error(request, provider.get_add_exists_msg)
                return HttpResponseRedirect(reverse('edit_profile'))

            messages.success(request, provider.get_switch_success_msg)
            return HttpResponseRedirect(reverse('edit_profile'))

        provider.add_to_user()
        provider.log("added")
        provider = user.get_auth_provider(provider_module, identifier)
        messages.success(request, provider.get_added_msg)
        return HttpResponseRedirect(reverse('edit_profile'))

    # astakos user exists ?
    try:
        user = AstakosUser.objects.get_auth_provider_user(
            provider_module,
            identifier=identifier,
            user__email_verified=True,
        )
    except AstakosUser.DoesNotExist:
        if signup_form_required(provider):
            if astakos_messages.AUTH_PROVIDER_SIGNUP_FROM_LOGIN:
                # TODO: add a message ? redirec to login ?
                messages.warning(
                    request,
                    astakos_messages.AUTH_PROVIDER_SIGNUP_FROM_LOGIN)
            raise

        # If all attributes are set by the provider, the signup form is not
        # required. Continue by creating the AstakosUser object.
        user = handle_third_party_auto_signup(request, provider_module,
                                              provider_info,
                                              identifier, user_info)

    if not third_party_key:
        third_party_key = get_pending_key(request)

    provider = user.get_auth_provider(provider_module, identifier)

    if user.is_active:
        if not provider.get_login_policy:
            messages.error(request, provider.get_login_disabled_msg)
            return HttpResponseRedirect(reverse('login'))

        # Update attributes that are forced by the provider
        for attr in provider.get_provider_forced_attributes():
            if attr in user_info:
                setattr(user, attr, user_info[attr])

        # Update the groups that the user belongs to
        user_groups = user_info.get('groups', None)
        if isinstance(user_groups, list):
            user.groups = user_groups

        # Save user to get groups
        user.fix_username()
        user.save()

        # authenticate user
        response = prepare_response(request, user, next_redirect,
                                    'renew' in request.GET)

        messages.success(request, provider.get_login_success_msg)
        add_pending_auth_provider(request, third_party_key, provider)
        response.set_cookie('astakos_last_login_method', provider_module)
        provider.update_last_login_at()
        return response
    else:
        message = user.get_inactive_message(provider_module, identifier)
        messages.error(request, message)
        return HttpResponseRedirect(login_url(request))

Example 104

Project: djangosaml2 Source File: views.py
Function: log_in
def login(request,
          config_loader_path=None,
          wayf_template='djangosaml2/wayf.html',
          authorization_error_template='djangosaml2/auth_error.html',
          post_binding_form_template='djangosaml2/post_binding_form.html'):
    """SAML Authorization Request initiator

    This view initiates the SAML2 Authorization handshake
    using the pysaml2 library to create the AuthnRequest.
    It uses the SAML 2.0 Http Redirect protocol binding.

    * post_binding_form_template - path to a template containing HTML form with
    hidden input elements, used to send the SAML message data when HTTP POST
    binding is being used. You can customize this template to include custom
    branding and/or text explaining the automatic redirection process. Please
    see the example template in
    templates/djangosaml2/example_post_binding_form.html
    If set to None or nonexistent template, default form from the saml2 library
    will be rendered.
    """
    logger.debug('Login process started')

    came_from = request.GET.get('next', settings.LOGIN_REDIRECT_URL)
    if not came_from:
        logger.warning('The next parameter exists but is empty')
        came_from = settings.LOGIN_REDIRECT_URL

    # Ensure the user-originating redirection url is safe.
    if not is_safe_url(url=came_from, host=request.get_host()):
        came_from = settings.LOGIN_REDIRECT_URL

    # if the user is already authenticated that maybe because of two reasons:
    # A) He has this URL in two browser windows and in the other one he
    #    has already initiated the authenticated session.
    # B) He comes from a view that (incorrectly) send him here because
    #    he does not have enough permissions. That view should have shown
    #    an authorization error in the first place.
    # We can only make one thing here and that is configurable with the
    # SAML_IGNORE_AUTHENTICATED_USERS_ON_LOGIN setting. If that setting
    # is True (default value) we will redirect him to the came_from view.
    # Otherwise, we will show an (configurable) authorization error.
    if not request.user.is_anonymous():
        try:
            redirect_authenticated_user = settings.SAML_IGNORE_AUTHENTICATED_USERS_ON_LOGIN
        except AttributeError:
            redirect_authenticated_user = True

        if redirect_authenticated_user:
            return HttpResponseRedirect(came_from)
        else:
            logger.debug('User is already logged in')
            return render(request, authorization_error_template, {
                    'came_from': came_from,
                    })

    selected_idp = request.GET.get('idp', None)
    conf = get_config(config_loader_path, request)

    # is a embedded wayf needed?
    idps = available_idps(conf)
    if selected_idp is None and len(idps) > 1:
        logger.debug('A discovery process is needed')
        return render(request, wayf_template, {
                'available_idps': idps.items(),
                'came_from': came_from,
                })

    # Choose binding (REDIRECT vs. POST).
    # When authn_requests_signed is turned on, HTTP Redirect binding cannot be
    # used the same way as without signatures; proper usage in this case involves
    # stripping out the signature from SAML XML message and creating a new
    # signature, following precise steps defined in the SAML2.0 standard.
    #
    # It is not feasible to implement this since we wouldn't be able to use an
    # external (xmlsec1) library to handle the signatures - more (higher level)
    # context is needed in order to create such signature (like the value of
    # RelayState parameter).
    #
    # Therefore it is much easier to use the HTTP POST binding in this case, as
    # it can relay the whole signed SAML message as is, without the need to
    # manipulate the signature or the XML message itself.
    #
    # Read more in the official SAML2 specs (3.4.4.1):
    # http://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf
    binding = BINDING_HTTP_POST if getattr(conf, '_sp_authn_requests_signed', False) else BINDING_HTTP_REDIRECT

    client = Saml2Client(conf)
    try:
        (session_id, result) = client.prepare_for_authenticate(
            entityid=selected_idp, relay_state=came_from,
            binding=binding,
            )
    except TypeError as e:
        logger.error('Unable to know which IdP to use')
        return HttpResponse(unicode(e))

    logger.debug('Saving the session_id in the OutstandingQueries cache')
    oq_cache = OutstandingQueriesCache(request.session)
    oq_cache.set(session_id, came_from)

    logger.debug('Redirecting user to the IdP via %s binding.', binding.split(':')[-1])
    if binding == BINDING_HTTP_REDIRECT:
        return HttpResponseRedirect(get_location(result))
    elif binding == BINDING_HTTP_POST:
        if not post_binding_form_template:
            return HttpResponse(result['data'])
        try:
            params = get_hidden_form_inputs(result['data'][3])
            return render(request, post_binding_form_template, {
                    'target_url': result['url'],
                    'params': params,
                    })
        except (DTDForbidden, EntitiesForbidden, ExternalReferenceForbidden):
            raise PermissionDenied
        except TemplateDoesNotExist:
            return HttpResponse(result['data'])
    else:
        raise NotImplementedError('Unsupported binding: %s', binding)

Example 105

Project: healthsites Source File: views.py
@csrf_exempt
def map(request):
    """View for request."""
    if request.user.is_authenticated():
        user = get_object_or_404(User, username=request.user)
        request.user = get_profile(user)

    if request.method == 'POST':
        search_query = request.POST.get('q')
        option = request.POST.get('option')
        if option == 'place':
            map_url = reverse('map')
            return HttpResponseRedirect(
                map_url + "?place=%s" % search_query)
        elif option == 'what3words':
            locality_values = Value.objects.filter(
                specification__attribute__key='what3words').filter(
                data=search_query)
            if locality_values:
                locality_value = locality_values[0]
            else:
                return render_to_response(
                    'map.html',
                    context_instance=RequestContext(request)
                )
            locality_uuid = locality_value.locality.uuid
            map_url = reverse('map')
            return HttpResponseRedirect(
                map_url + "#!/locality/%s" % locality_uuid)
        elif option == 'healthsite':
            localities = Locality.objects.filter(
                name=search_query)
            if len(localities) > 0:
                locality = localities[0]
                locality_uuid = locality.uuid
                map_url = reverse('map')
                return HttpResponseRedirect(
                    map_url + "#!/locality/%s" % locality_uuid)
            else:
                return render_to_response(
                    'map.html',
                    context_instance=RequestContext(request)
                )
    else:
        tag = request.GET.get('tag')
        country = request.GET.get('country')
        place = request.GET.get('place')
        attribute = request.GET.get('attribute')
        result = {}
        if tag:
            result = search_locality_by_tag(tag)
            result['tag'] = tag
        elif country:
            result = get_country_statistic(country)
            result['country'] = country
            result['polygon'] = Country.objects.get(name__iexact=country).polygon_geometry.geojson
        elif place:
            result = search_place(request, place)
        elif attribute:
            uuid = request.GET.get('uuid')
            result = search_locality_by_spec_data("attribute", attribute, uuid)
            result['attribute'] = {'attribute': attribute, 'uuid': uuid, 'name': result['locality_name'],
                                   'location': result['location']}
        elif len(request.GET) == 0:
            result = search_place(request, place)
        else:
            uuid = request.GET.get('uuid')
            for item in request.GET:
                if item != "uuid":
                    spec = item
                    data = request.GET.get(item)
                    result = search_locality_by_spec_data(spec, data, uuid)
                    result['spec'] = {'spec': spec, 'data': data, 'uuid': uuid, 'name': result['locality_name'],
                                      'location': result['location']}

        if 'new_geom' in request.session:
            result["new_geom"] = request.session['new_geom']
            del request.session['new_geom']
        return render_to_response(
            'map.html',
            result,
            context_instance=RequestContext(request)
        )

Example 106

Project: ganetimgr Source File: __init__.py
@permission_required("apply.change_instanceapplication")
def review_application(request, application_id=None):
    applications = InstanceApplication.objects.filter(status__in=PENDING_CODES)
    fast_clusters = Cluster.objects.filter(fast_create=True).exclude(
        disable_instance_creation=True
    ).order_by('description')
    # There is a chance that the administrator has just filled a form
    # by himself, so the application does not actually exist (yet)
    # import ipdb; ipdb.set_trace()
    if application_id:
        app = get_object_or_404(InstanceApplication, pk=application_id)
    else:
        # We set app to None because there is application instance yet
        app = None
    if request.method == "GET" and app:
        form = InstanceApplicationReviewForm(
            instance=app,
            initial={
                'operating_system': app.operating_system
            }
        )
        if app.instance_params and 'cluster' in app.instance_params.keys():
            form = InstanceApplicationReviewForm(
                instance=app,
                initial={
                    "cluster": Cluster.objects.get(
                        slug=app.instance_params['cluster']
                    ).pk,
                    'operating_system': app.operating_system
                })
        return render(
            request,
            'apply/review.html',
            {
                'application': app,
                'applications': applications,
                'appform': form,
                'fast_clusters': fast_clusters
            }
        )
    elif request.method == "POST":
        data = request.POST.dict()
        if data.get('reject', ''):
            if data.get('node_group'):
                del data['node_group']
            if data.get('netw'):
                del data['netw']
            if data.get('vgs'):
                del data['vgs']
            if data.get('disk_template'):
                del data['disk_template']

        nodegroup = data.get('node_group', '')
        form_ngs = (('', ''),)
        if nodegroup:
            form_ngs = ((nodegroup, nodegroup),)

        netw = data.get('netw', '')
        form_netw = (('', ''),)
        if netw:
            form_netw = ((netw, netw),)

        vgs = data.get('vgs', '')
        form_vgs = (('', ''),)
        if vgs:
            form_vgs = ((vgs, vgs),)

        dt = data.get('disk_template', '')
        form_dt = (('', ''),)
        if dt:
            form_dt = ((dt, dt),)

        form = InstanceApplicationReviewForm(data, instance=app)
        # check if code is run in test mode
        import sys
        if sys.argv[1:2] == ['test']:
            form.fields['cluster'].choices.append((100, 100))
            form.fields['netw'].choices.append(('test::test', 'test::test'))
            form.fields['disk_template'].choices.append(('test', 'test'))
            form.fields['node_group'].choices.append(('test', 'test'))
            form.fields['vgs'].choices.append(('test', 'test'))
        else:
            if not form.data.get('reject'):
                form.fields['node_group'] = forms.ChoiceField(choices=form_ngs, label="Node Group")
                form.fields['netw'] = forms.ChoiceField(choices=form_netw, label="Network")
                form.fields['vgs'] = forms.ChoiceField(choices=form_vgs, label="Volume Groups",)
                form.fields['disk_template'] = forms.ChoiceField(choices=form_dt, label="Disk Template",)
        if form.is_valid():
            application = form.save(commit=False)
            # if the instance does not exist yet
            if not app:
                # we have to connect the user with this form
                application.applicant = request.user
            application.operating_system = form.cleaned_data['operating_system']
            if "reject" in request.POST:
                application.status = STATUS_REFUSED
                application.save()
                mail_body = render_to_string(
                    "apply/emails/application_rejected_mail.txt",
                    {"application": application, },
                    context_instance=RequestContext(request)
                )
                send_mail(
                    settings.EMAIL_SUBJECT_PREFIX + "Application for %s rejected" % (
                        application.hostname
                    ),
                    mail_body,
                    settings.SERVER_EMAIL,
                    [application.applicant.email]
                )
                messages.add_message(
                    request,
                    messages.INFO,
                    "Application #%d rejected, user %s has"
                    " been notified" % (app.pk, application.applicant)
                )
            else:
                application.status = STATUS_APPROVED
                application.instance_params = {
                    'cluster': Cluster.objects.get(
                        pk=form.cleaned_data['cluster']
                    ).slug,
                    'network': form.cleaned_data['netw'].split("::")[0],
                    'mode': form.cleaned_data['netw'].split("::")[1],
                    'node_group': form.cleaned_data['node_group'],
                    'vgs': form.cleaned_data['vgs'],
                    'disk_template': form.cleaned_data['disk_template'],
                }
                application.reviewer = request.user
                application.save()
                application.submit()
                messages.add_message(request, messages.INFO,
                                     "Application #%d accepted and submitted"
                                     " to %s" % (application.pk, application.cluster))
            cache.delete('pendingapplications')
            return HttpResponseRedirect(reverse("application-list"))
        else:
            if app:
                return render(
                    request,
                    'apply/review.html',
                    {
                        'application': app,
                        'applications': applications,
                        'appform': form,
                        'fast_clusters': fast_clusters
                    }
                )
            else:
                return render(
                    request,
                    'apply/admin_apply.html',
                    {
                        'form': form
                    }
                )
    else:
        # If the request method is GET, but there is no application given,
        # then someone is trying to do stuff.
        raise Http404

Example 107

Project: fjord Source File: views.py
@ratelimit(rulename='doublesubmit_1p10m',
           keyfun=actual_ip_plus_context(
               lambda req: req.POST.get('description', u'no description')),
           rate='1/10m')
@ratelimit(rulename='50ph', rate='50/h')
def _handle_feedback_post(request, locale=None, product=None,
                          version=None, channel=None):
    """Saves feedback post to db accounting for throttling

    :arg request: request we're handling the post for
    :arg locale: locale specified in the url
    :arg product: None or the Product
    :arg version: validated and sanitized version specified in the url
    :arg channel: validated and sanitized channel specified in the url

    """
    if getattr(request, 'limited', False):
        # If we're throttled, then return the thanks page, but don't
        # add the response to the db.
        return HttpResponseRedirect(reverse('thanks'))

    # Get the form and run is_valid() so it goes through the
    # validation and cleaning machinery. We don't really care if it's
    # valid, though, since we will take what we got and do the best we
    # can with it. Error validation is now in JS.
    form = ResponseForm(request.POST)
    form.is_valid()

    get_data = request.GET.copy()

    data = form.cleaned_data

    description = data.get('description', u'').strip()
    if not description:
        # If there's no description, then there's nothing to do here,
        # so thank the user and move on.
        return HttpResponseRedirect(reverse('thanks'))

    opinion = models.Response(
        # Data coming from the user
        happy=data['happy'],
        url=clean_url(data.get('url', u'').strip()),
        description=description,

        # Pulled from the form data or the url
        locale=data.get('locale', locale),

        # Data from mobile devices which is probably only
        # applicable to mobile devices
        manufacturer=data.get('manufacturer', ''),
        device=data.get('device', ''),
    )

    # Add user_agent and inferred data.
    user_agent = request.META.get('HTTP_USER_AGENT', '')
    if user_agent:
        browser = request.BROWSER

        opinion.browser = browser.browser[:30]
        opinion.browser_version = browser.browser_version[:30]
        bp = browser.platform
        if bp == 'Windows':
            bp += (' ' + browser.platform_version)
        opinion.browser_platform = bp[:30]
        opinion.user_agent = user_agent[:config.USER_AGENT_LENGTH]

    # source is src or utm_source
    source = (
        get_data.pop('src', [u''])[0] or
        get_data.pop('utm_source', [u''])[0]
    )
    if source:
        opinion.source = source[:100]

    campaign = get_data.pop('utm_campaign', [u''])[0]
    if campaign:
        opinion.campaign = campaign[:100]

    # If they sent "happy=1"/"happy=0" in the querystring, it will get
    # picked up by the javascript in the form and we can just drop it
    # here.
    get_data.pop('happy', None)

    platform = u''

    if product:
        # If we have a product at this point, then it came from the
        # url and it's a Product instance and we need to turn it into
        # the product.db_name which is a string.
        product_db_name = product.db_name
    else:
        # Check the POST data for the product.
        product_db_name = data.get('product', '')

    # For the version, we try the url data, then the POST data.
    version = version or data.get('version', '')

    # At this point, we have a bunch of values, but we might be
    # missing some values, too. We're going to cautiously infer data
    # from the user agent where we're very confident it's appropriate
    # to do so.
    if request.BROWSER != UNKNOWN:
        # If we don't have a product, try to infer that from the user
        # agent information.
        if not product_db_name:
            product_db_name = models.Response.infer_product(request.BROWSER)

        # If we have a product and it matches the user agent browser,
        # then we can infer the version and platform from the user
        # agent if they're missing.
        if product_db_name:
            product = models.Product.objects.get(db_name=product_db_name)
            if product.browser and product.browser == request.BROWSER.browser:
                if not version:
                    version = request.BROWSER.browser_version
                if not platform:
                    platform = models.Response.infer_platform(
                        product_db_name, request.BROWSER)

    # Make sure values are at least empty strings--no Nones.
    opinion.product = (product_db_name or u'')[:30]
    opinion.version = (version or u'')[:30]
    opinion.channel = (channel or u'')[:30]
    opinion.platform = (platform or u'')[:30]

    opinion.save()

    # If there was an email address, save that separately.
    if data.get('email_ok') and data.get('email'):
        e = models.ResponseEmail(email=data['email'], opinion=opinion)
        e.save()
        statsd.incr('feedback.emaildata.optin')

    # If there's browser data, save that separately.
    if data.get('browser_ok'):
        # This comes in as a JSON string. Because we're using
        # JSONObjectField, we need to convert it back to Python and
        # then save it. This is kind of silly, but it does guarantee
        # we have valid JSON.
        try:
            browser_data = data['browser_data']
            browser_data = json.loads(browser_data)

        except ValueError:
            # Handles empty string and any non-JSON value.
            statsd.incr('feedback.browserdata.badvalue')

        except KeyError:
            # Handles the case where it's missing from the data
            # dict. If it's missing, we don't want to do anything
            # including metrics.
            pass

        else:
            # If browser_data isn't an empty dict, then save it.
            if browser_data:
                rti = models.ResponsePI(
                    data=browser_data, opinion=opinion)
                rti.save()
                statsd.incr('feedback.browserdata.optin')

    if get_data:
        # There was extra context in the query string, so we grab that
        # with some restrictions and save it separately.
        slop = {}

        # We capture at most the first 20 key/val pairs
        get_data_items = sorted(get_data.items())[:20]

        for key, val in get_data_items:
            # Keys can be at most 20 characters long.
            key = key[:20]
            if len(val) == 1:
                val = val[0]

            # Values can be at most 20 characters long.
            val = val[:100]
            slop[key.encode('utf-8')] = val.encode('utf-8')

        context = models.ResponseContext(data=slop, opinion=opinion)
        context.save()
        statsd.incr('feedback.contextdata.optin')

    if data['happy']:
        statsd.incr('feedback.happy')
    else:
        statsd.incr('feedback.sad')

    request.session['response_id'] = opinion.id

    return HttpResponseRedirect(reverse('thanks'))

Example 108

Project: geonode Source File: views.py
@login_required
def docuement_metadata(
        request,
        docid,
        template='docuements/docuement_metadata.html'):

    docuement = None
    try:
        docuement = _resolve_docuement(
            request,
            docid,
            'base.change_resourcebase_metadata',
            _PERMISSION_MSG_METADATA)

    except Http404:
        return HttpResponse(
            loader.render_to_string(
                '404.html', RequestContext(
                    request, {
                        })), status=404)

    except PermissionDenied:
        return HttpResponse(
            loader.render_to_string(
                '401.html', RequestContext(
                    request, {
                        'error_message': _("You are not allowed to edit this docuement.")})), status=403)

    if docuement is None:
        return HttpResponse(
            'An unknown error has occured.',
            content_type="text/plain",
            status=401
        )

    else:
        poc = docuement.poc
        metadata_author = docuement.metadata_author
        topic_category = docuement.category

        if request.method == "POST":
            docuement_form = DocuementForm(
                request.POST,
                instance=docuement,
                prefix="resource")
            category_form = CategoryForm(
                request.POST,
                prefix="category_choice_field",
                initial=int(
                    request.POST["category_choice_field"]) if "category_choice_field" in request.POST else None)
        else:
            docuement_form = DocuementForm(instance=docuement, prefix="resource")
            category_form = CategoryForm(
                prefix="category_choice_field",
                initial=topic_category.id if topic_category else None)

        if request.method == "POST" and docuement_form.is_valid(
        ) and category_form.is_valid():
            new_poc = docuement_form.cleaned_data['poc']
            new_author = docuement_form.cleaned_data['metadata_author']
            new_keywords = docuement_form.cleaned_data['keywords']
            new_category = TopicCategory.objects.get(
                id=category_form.cleaned_data['category_choice_field'])

            if new_poc is None:
                if poc is None:
                    poc_form = ProfileForm(
                        request.POST,
                        prefix="poc",
                        instance=poc)
                else:
                    poc_form = ProfileForm(request.POST, prefix="poc")
                if poc_form.is_valid():
                    if len(poc_form.cleaned_data['profile']) == 0:
                        # FIXME use form.add_error in django > 1.7
                        errors = poc_form._errors.setdefault('profile', ErrorList())
                        errors.append(_('You must set a point of contact for this resource'))
                        poc = None
                if poc_form.has_changed and poc_form.is_valid():
                    new_poc = poc_form.save()

            if new_author is None:
                if metadata_author is None:
                    author_form = ProfileForm(request.POST, prefix="author",
                                              instance=metadata_author)
                else:
                    author_form = ProfileForm(request.POST, prefix="author")
                if author_form.is_valid():
                    if len(author_form.cleaned_data['profile']) == 0:
                        # FIXME use form.add_error in django > 1.7
                        errors = author_form._errors.setdefault('profile', ErrorList())
                        errors.append(_('You must set an author for this resource'))
                        metadata_author = None
                if author_form.has_changed and author_form.is_valid():
                    new_author = author_form.save()

            if new_poc is not None and new_author is not None:
                the_docuement = docuement_form.save()
                the_docuement.poc = new_poc
                the_docuement.metadata_author = new_author
                the_docuement.keywords.add(*new_keywords)
                Docuement.objects.filter(id=the_docuement.id).update(category=new_category)

                if getattr(settings, 'SLACK_ENABLED', False):
                    try:
                        from geonode.contrib.slack.utils import build_slack_message_docuement, send_slack_messages
                        send_slack_messages(build_slack_message_docuement("docuement_edit", the_docuement))
                    except:
                        print "Could not send slack message for modified docuement."

                return HttpResponseRedirect(
                    reverse(
                        'docuement_detail',
                        args=(
                            docuement.id,
                        )))

        if poc is not None:
            docuement_form.fields['poc'].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

        if metadata_author is not None:
            docuement_form.fields['metadata_author'].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

        return render_to_response(template, RequestContext(request, {
            "docuement": docuement,
            "docuement_form": docuement_form,
            "poc_form": poc_form,
            "author_form": author_form,
            "category_form": category_form,
        }))

Example 109

Project: theyworkforyou Source File: comments.py
def post_comment(request):
    """
    Post a comment

    Redirects to the `comments.comments.comment_was_posted` view upon success.

    Templates: `comment_preview`
    Context:
        comment
            the comment being posted
        comment_form
            the comment form
        options
            comment options
        target
            comment target
        hash
            security hash (must be included in a posted form to succesfully
            post a comment).
        rating_options
            comment ratings options
        ratings_optional
            are ratings optional?
        ratings_required
            are ratings required?
        rating_range
            range of ratings
        rating_choices
            choice of ratings
    """
    if not request.POST:
        raise Http404, _("Only POSTs are allowed")
    try:
        options, target, security_hash = request.POST['options'], request.POST['target'], request.POST['gonzo']
    except KeyError:
        raise Http404, _("One or more of the required fields wasn't submitted")
    photo_options = request.POST.get('photo_options', '')
    rating_options = normalize_newlines(request.POST.get('rating_options', ''))
    if Comment.objects.get_security_hash(options, photo_options, rating_options, target) != security_hash:
        raise Http404, _("Somebody tampered with the comment form (security violation)")
    # Now we can be assured the data is valid.
    if rating_options:
        rating_range, rating_choices = Comment.objects.get_rating_options(base64.decodestring(rating_options))
    else:
        rating_range, rating_choices = [], []
    content_type_id, object_id = target.split(':') # target is something like '52:5157'
    try:
        obj = ContentType.objects.get(pk=content_type_id).get_object_for_this_type(pk=object_id)
    except ObjectDoesNotExist:
        raise Http404, _("The comment form had an invalid 'target' parameter -- the object ID was invalid")
    option_list = options.split(',') # options is something like 'pa,ra'
    new_data = request.POST.copy()
    new_data['content_type_id'] = content_type_id
    new_data['object_id'] = object_id
    new_data['ip_address'] = request.META.get('REMOTE_ADDR')
    new_data['is_public'] = IS_PUBLIC in option_list
    manipulator = PublicCommentManipulator(request.user,
        ratings_required=RATINGS_REQUIRED in option_list,
        ratings_range=rating_range,
        num_rating_choices=len(rating_choices))
    errors = manipulator.get_validation_errors(new_data)
    # If user gave correct username/password and wasn't already logged in, log them in
    # so they don't have to enter a username/password again.
    if manipulator.get_user() and not manipulator.get_user().is_authenticated() and new_data.has_key('password') and manipulator.get_user().check_password(new_data['password']):
        from django.contrib.auth import login
        login(request, manipulator.get_user())
    if errors or request.POST.has_key('preview'):
        class CommentFormWrapper(oldforms.FormWrapper):
            def __init__(self, manipulator, new_data, errors, rating_choices):
                oldforms.FormWrapper.__init__(self, manipulator, new_data, errors)
                self.rating_choices = rating_choices
            def ratings(self):
                field_list = [self['rating%d' % (i+1)] for i in range(len(rating_choices))]
                for i, f in enumerate(field_list):
                    f.choice = rating_choices[i]
                return field_list
        comment = errors and '' or manipulator.get_comment(new_data)
        comment_form = CommentFormWrapper(manipulator, new_data, errors, rating_choices)
        return render_to_response('comments/preview.html', {
            'comment': comment,
            'comment_form': comment_form,
            'options': options,
            'target': target,
            'hash': security_hash,
            'rating_options': rating_options,
            'ratings_optional': RATINGS_OPTIONAL in option_list,
            'ratings_required': RATINGS_REQUIRED in option_list,
            'rating_range': rating_range,
            'rating_choices': rating_choices,
        }, context_instance=RequestContext(request))
    elif request.POST.has_key('post'):
        # If the IP is banned, mail the admins, do NOT save the comment, and
        # serve up the "Thanks for posting" page as if the comment WAS posted.
        if request.META['REMOTE_ADDR'] in settings.BANNED_IPS:
            mail_admins("Banned IP attempted to post comment", str(request.POST) + "\n\n" + str(request.META))
        else:
            manipulator.do_html2python(new_data)
            comment = manipulator.save(new_data)
        return HttpResponseRedirect("../posted/?c=%s:%s" % (content_type_id, object_id))
    else:
        raise Http404, _("The comment form didn't provide either 'preview' or 'post'")

Example 110

Project: geonode Source File: views.py
@login_required
def map_metadata(request, mapid, template='maps/map_metadata.html'):

    map_obj = _resolve_map(request, mapid, 'base.change_resourcebase_metadata', _PERMISSION_MSG_VIEW)

    poc = map_obj.poc

    metadata_author = map_obj.metadata_author

    topic_category = map_obj.category

    if request.method == "POST":
        map_form = MapForm(request.POST, instance=map_obj, prefix="resource")
        category_form = CategoryForm(
            request.POST,
            prefix="category_choice_field",
            initial=int(
                request.POST["category_choice_field"]) if "category_choice_field" in request.POST else None)
    else:
        map_form = MapForm(instance=map_obj, prefix="resource")
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)

    if request.method == "POST" and map_form.is_valid(
    ) and category_form.is_valid():
        new_poc = map_form.cleaned_data['poc']
        new_author = map_form.cleaned_data['metadata_author']
        new_keywords = map_form.cleaned_data['keywords']
        new_title = strip_tags(map_form.cleaned_data['title'])
        new_abstract = strip_tags(map_form.cleaned_data['abstract'])
        new_category = TopicCategory.objects.get(
            id=category_form.cleaned_data['category_choice_field'])

        if new_poc is None:
            if poc is None:
                poc_form = ProfileForm(
                    request.POST,
                    prefix="poc",
                    instance=poc)
            else:
                poc_form = ProfileForm(request.POST, prefix="poc")
            if poc_form.has_changed and poc_form.is_valid():
                new_poc = poc_form.save()

        if new_author is None:
            if metadata_author is None:
                author_form = ProfileForm(request.POST, prefix="author",
                                          instance=metadata_author)
            else:
                author_form = ProfileForm(request.POST, prefix="author")
            if author_form.has_changed and author_form.is_valid():
                new_author = author_form.save()

        if new_poc is not None and new_author is not None:
            the_map = map_form.save()
            the_map.poc = new_poc
            the_map.metadata_author = new_author
            the_map.title = new_title
            the_map.abstract = new_abstract
            the_map.save()
            the_map.keywords.clear()
            the_map.keywords.add(*new_keywords)
            the_map.category = new_category
            the_map.save()

            if getattr(settings, 'SLACK_ENABLED', False):
                try:
                    from geonode.contrib.slack.utils import build_slack_message_map, send_slack_messages
                    send_slack_messages(build_slack_message_map("map_edit", the_map))
                except:
                    print "Could not send slack message for modified map."

            return HttpResponseRedirect(
                reverse(
                    'map_detail',
                    args=(
                        map_obj.id,
                    )))

    if poc is None:
        poc_form = ProfileForm(request.POST, prefix="poc")
    else:
        if poc is None:
            poc_form = ProfileForm(instance=poc, prefix="poc")
        else:
            map_form.fields['poc'].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

    if metadata_author is None:
        author_form = ProfileForm(request.POST, prefix="author")
    else:
        if metadata_author is None:
            author_form = ProfileForm(
                instance=metadata_author,
                prefix="author")
        else:
            map_form.fields['metadata_author'].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

    return render_to_response(template, RequestContext(request, {
        "map": map_obj,
        "map_form": map_form,
        "poc_form": poc_form,
        "author_form": author_form,
        "category_form": category_form,
    }))

Example 111

Project: karaage Source File: project.py
Function: view
    def view(self, request, application, label, roles, actions):
        """ Django view method. """
        status = None
        applicant = application.applicant
        attrs = []

        saml_session = saml.is_saml_session(request)

        # certain actions are supported regardless of what else happens
        if 'cancel' in request.POST:
            return "cancel"
        if 'prev' in request.POST:
            return 'prev'

        # test for conditions where shibboleth registration not required
        if applicant.saml_id is not None:
            status = "You have already registered a shibboleth id."
            form = None
            done = True

        elif application.content_type.model != 'applicant':
            status = "You are already registered in the system."
            form = None
            done = True

        elif (applicant.institute is not None and
                applicant.institute.saml_entityid is None):
            status = "Your institute does not have shibboleth registered."
            form = None
            done = True

        elif Institute.objects.filter(
                saml_entityid__isnull=False).count() == 0:
            status = "No institutes support shibboleth here."
            form = None
            done = True

        else:
            # shibboleth registration is required

            # Do construct the form
            form = saml.SAMLInstituteForm(
                request.POST or None,
                initial={'institute': applicant.institute})
            done = False
            status = None

            # Was it a POST request?
            if request.method == 'POST':

                # Did the login form get posted?
                if 'login' in request.POST and form.is_valid():
                    institute = form.cleaned_data['institute']
                    applicant.institute = institute
                    applicant.save()
                    # We do not set application.insitute here, that happens
                    # when application, if it is a ProjectApplication, is
                    # submitted

                    # if institute supports shibboleth, redirect back here via
                    # shibboleth, otherwise redirect directly back he.
                    url = base.get_url(request, application, roles, label)
                    if institute.saml_entityid is not None:
                        url = saml.build_shib_url(
                            request, url, institute.saml_entityid)
                    return HttpResponseRedirect(url)

                # Did we get a logout request?
                elif 'logout' in request.POST:
                    if saml_session:
                        url = saml.logout_url(request)
                        return HttpResponseRedirect(url)
                    else:
                        return HttpResponseBadRequest("<h1>Bad Request</h1>")

            # did we get a shib session yet?
            if saml_session:
                attrs, _ = saml.parse_attributes(request)
                saml_session = True

        # if we are done, we can proceed to next state
        if request.method == 'POST':
            if 'cancel' in request.POST:
                return "cancel"
            if 'prev' in request.POST:
                return 'prev'

            if not done:
                if saml_session:
                    applicant = _get_applicant_from_saml(request)
                    if applicant is not None:
                        application.applicant = applicant
                        application.save()
                    else:
                        applicant = application.applicant

                    applicant = saml.add_saml_data(
                        applicant, request)
                    applicant.save()

                    done = True
                else:
                    status = "Please login to SAML before proceeding."

        if request.method == 'POST' and done:
            for action in actions:
                if action in request.POST:
                    return action
            return HttpResponseBadRequest("<h1>Bad Request</h1>")

        # render the page
        return render(
            template_name='kgapplications/project_aed_shibboleth.html',
            context={
                'form': form,
                'done': done,
                'status': status,
                'actions': actions,
                'roles': roles,
                'application': application,
                'attrs': attrs,
                'saml_session': saml_session,
            },
            request=request)

Example 112

Project: fhurl Source File: fhurl.py
def _form_handler(
    request, form_cls, require_login=False, block_get=False, ajax=False,
    next=None, template=None, login_url=None, pass_request=True,
    validate_only=False, **kwargs
):
    """
    Some ajax heavy apps require a lot of views that are merely a wrapper
    around the form. This generic view can be used for them.
    """
    if "next" in request.REQUEST: next = request.REQUEST["next"]
    from django.shortcuts import render_to_response
    is_ajax = request.is_ajax() or ajax or request.REQUEST.get("json")=="true"
    if isinstance(form_cls, basestring):
        # can take form_cls of the form: "project.app.forms.FormName"
        mod_name, form_name = get_mod_func(form_cls)
        form_cls = getattr(__import__(mod_name, {}, {}, ['']), form_name)
    validate_only = (
        validate_only or request.REQUEST.get("validate_only") == "true"
    )
    if login_url is None:
        login_url = getattr(settings, "LOGIN_URL", "/login/")
    if callable(require_login): 
        require_login = require_login(request)
    elif require_login:
        require_login = not request.user.is_authenticated()
    if require_login:
        redirect_url = "%s?next=%s" % (
            login_url, urlquote(request.get_full_path())
        ) # FIXME
        if is_ajax:
            return JSONResponse({ 'success': False, 'redirect': redirect_url })
        return HttpResponseRedirect(redirect_url)
    if block_get and request.method != "POST":
        raise Http404("only post allowed")
    if next: assert template, "template required when next provided"
    def get_form(with_data=False):
        form = form_cls(request) if pass_request else form_cls()
        form.next = next
        if with_data:
            form.data = request.REQUEST
            form.files = request.FILES
            form.is_bound = True
        if hasattr(form, "init"):
            res = form.init(**kwargs)
            if res: raise ResponseReady(res)
        return form
    if is_ajax and request.method == "GET":
        return JSONResponse(get_form_representation(get_form()))
    if template and request.method == "GET":
        return render_to_response(
            template, {"form": get_form()},
            context_instance=RequestContext(request)
        )
    form = get_form(with_data=True)
    if form.is_valid():
        if validate_only:
            return JSONResponse({"valid": True, "errors": {}})
        r = form.save()
        if is_ajax: return JSONResponse(
            {
                'success': True,
                'response': (
                    form.get_json(r) if hasattr(form, "get_json") else r
                )
            }
        )
        if isinstance(r, HttpResponse): return r
        if next: return HttpResponseRedirect(next)
        if template: return HttpResponseRedirect(r)
        return JSONResponse(
            {
                'success': True,
                'response': (
                    form.get_json(r) if hasattr(form, "get_json") else r
                )
            }
        )
    if validate_only:
        if "field" in request.REQUEST:
            errors = form.errors.get(request.REQUEST["field"], "")
            if errors: errors = "".join(errors)
        else:
            errors = form.errors
        return JSONResponse({ "errors": errors, "valid": not errors})
    if is_ajax:
        return JSONResponse({ 'success': False, 'errors': form.errors })
    if template:
        return render_to_response(
            template, {"form": form}, context_instance=RequestContext(request)
        )
    return JSONResponse({ 'success': False, 'errors': form.errors })

Example 113

Project: django-mr_reports Source File: views.py
def render_report(request, report_id, format=''):
    """Render a given report, or ask for parameters if needed

    A utils.execute_subscription also runs this function using a mock request object
    so don't always expect request to contain things like user, etc.
    """
    report = get_object_or_404(Report, pk=report_id)

    subscriptions, subscription_formset, subscribe_parameters, show_subscription_form = [], None, '', False

    today = datetime.datetime.today()

    curr_url = request.get_full_path()
    base_path = ''
    datasets = []

    #If form exists, and is not bound, or is not valid, prompt for parameters
    #otherwise render report
    ParameterForm = build_parameter_form(report)
    prompt_for_parameters = False
    if ParameterForm:
        if request.GET:
            parameter_form = ParameterForm(request.GET)
            if parameter_form.is_valid():
                #render report
                datasets = report.get_all_data(parameter_form)
                #Include links to PDF and CSV versions of report
                if '?' in curr_url:
                    csv_url = ''.join([curr_url.split('?')[0],'csv/?',curr_url.split('?')[1]])
                    pdf_url = ''.join([curr_url.split('?')[0],'pdf/?',curr_url.split('?')[1]])
                    subscribe_parameters = curr_url.split('?')[1]
                else:
                    csv_url, pdf_url = '','' #when running as a scheduled email we won't have curr_url
            else:
                prompt_for_parameters = True
        else:
            prompt_for_parameters = True
            parameter_form = ParameterForm()
    else:
        #render report
        parameter_form = None
        datasets = report.get_all_data(parameter_form)
        #Include links to PDF and CSV versions of report
        csv_url = curr_url + 'csv/'
        pdf_url = curr_url + 'pdf/'

    #pull subscriptions if any, handle saving
    if getattr(request,'user',False):
        if request.POST:
            subscription_formset = SubscriptionFormSet(request.POST)
            if subscription_formset.is_valid():
                #add in non displayed fields: send_to and report
                instances = subscription_formset.save(commit=False)
                for instance in instances:
                    instance.send_to = request.user
                    instance.report = report
                    instance.save()
                return HttpResponseRedirect(curr_url)
            else:
                #print subscription_formset.forms[-1].changed_data
                #Show subscription form when loading page to highlight errors
                show_subscription_form = True
        else:
            #Note, Django 1.6 won't allow an initial/default value for time :-( lest it thinks an 
            #unchanged extra form has been changed.
            subscriptions = Subscription.objects.filter(send_to=request.user, report=report)
            subscription_formset = SubscriptionFormSet(queryset=subscriptions,
                initial=[{'frequency':'Monthly'}])
    #Footer:
    footer_html = getattr(settings,'MR_REPORTS_FOOTER_HTML',
        "<p><em>Generated by <a href=''>Mr. Reports</a>.</em></p>")

    #Handle alternative outputs
    if format=='csv':
        assert datasets and not prompt_for_parameters
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="%s.csv"' % report.filename()
        response = data_to_csv(response,datasets)
        return response
    elif format=='pdf':
        assert datasets and not prompt_for_parameters
        base_path = settings.BASE_PATH.rstrip('/')
        context = RequestContext(request, locals())
        return output_pdf(request, context, report)
    else:
        #normal page render
        return render(request, 'mr_reports/report.html', locals())

Example 114

Project: django-registration-me Source File: views.py
def register(request, success_url=None,
             form_class=RegistrationForm,
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register an account.
    
    Following successful registration, issue a redirect; by default,
    this will be whatever URL corresponds to the named URL pattern
    ``registration_complete``, which will be
    ``/accounts/register/complete/`` if using the included URLConf. To
    change this, point that named pattern at another URL, or pass your
    preferred URL as the keyword argument ``success_url``.
    
    By default, ``registration.forms.RegistrationForm`` will be used
    as the registration form; to change this, pass a different form
    class as the ``form_class`` keyword argument. The form class you
    specify must have a method ``save`` which will create and return
    the new ``User``, and that method must accept the keyword argument
    ``profile_callback`` (see below).
    
    To enable creation of a site-specific user profile object for the
    new user, pass a function which will create the profile object as
    the keyword argument ``profile_callback``. See
    ``RegistrationManager.create_inactive_user`` in the file
    ``models.py`` for details on how to write this function.
    
    By default, use the template
    ``registration/registration_form.html``; to change this, pass the
    name of a template as the keyword argument ``template_name``.
    
    **Required arguments**
    
    None.
    
    **Optional arguments**
    
    ``form_class``
        The form class to use for registration.
    
    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.
    
    ``profile_callback``
        A function which will be used to create a site-specific
        profile instance for the new ``User``.
    
    ``success_url``
        The URL to redirect to on successful registration.
    
    ``template_name``
        A custom template to use.
    
    **Context:**
    
    ``form``
        The registration form.
    
    Any extra variables supplied in the ``extra_context`` argument
    (see above).
    
    **Template:**
    
    registration/registration_form.html or ``template_name`` keyword
    argument.
    
    """
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = form.save()
            # success_url needs to be dynamically generated here; setting a
            # a default value using reverse() will cause circular-import
            # problems with the default URLConf for this application, which
            # imports this file.
            return HttpResponseRedirect(success_url or reverse('registration_complete'))
    else:
        form = form_class()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
    return render_to_response(template_name,
                              { 'form': form },
                              context_instance=context)

Example 115

Project: courtlistener Source File: views.py
def donate(request):
    """Load the donate page or process a submitted donation.

    This page has several branches. The logic is as follows:
        if GET:
            --> Load the page
        elif POST:
            if user is anonymous:
                if email address on record as a stub account:
                    --> Use it.
                elif new email address or a non-stub account:
                    --> We cannot allow anonymous people to update real
                        accounts, or this is a new email address, so create a
                        new stub account.
            elif user is logged in:
                --> associate with account.

            We now have an account. Process the payment and associate it.
    """

    message = None
    if request.method == 'POST':
        donation_form = DonationForm(request.POST)

        if request.user.is_anonymous():
            # Either this is a new account, a stubbed one, or a user that's
            # simply not logged into their account
            try:
                stub_account = User.objects.filter(
                    profile__stub_account=True
                ).get(
                    email__iexact=request.POST.get('email')
                )
            except User.DoesNotExist:
                stub_account = False

            if stub_account:
                # We use the stub account and anonymous users even are allowed
                # to update it. This is OK, because we don't care too much
                # about the accuracy of this data. Later if/when this becomes
                # a real account, anonymous users won't be able to update this
                # information -- that's what matters.
                user_form = UserForm(
                    request.POST,
                    instance=stub_account
                )
                profile_form = ProfileForm(
                    request.POST,
                    instance=stub_account.profile
                )
            else:
                # Either a regular account or an email address we've never
                # seen before. Create a new user from the POST data.
                user_form = UserForm(request.POST)
                profile_form = ProfileForm(request.POST)
        else:
            user_form = UserForm(
                request.POST,
                instance=request.user
            )
            profile_form = ProfileForm(
                request.POST,
                instance=request.user.profile
            )

        if all([donation_form.is_valid(),
                user_form.is_valid(),
                profile_form.is_valid()]):
            # Process the data in form.cleaned_data
            cd_donation_form = donation_form.cleaned_data
            cd_user_form = user_form.cleaned_data
            cd_profile_form = profile_form.cleaned_data
            stripe_token = request.POST.get('stripeToken')

            # Route the payment to a payment provider
            response = route_and_process_donation(
                cd_donation_form,
                cd_user_form,
                stripe_token
            )
            logger.info("Payment routed with response: %s" % response)

            if response['status'] == 0:
                if request.user.is_anonymous() and not stub_account:
                    # Create a stub account with an unusable password
                    user, profile = create_stub_account(
                        cd_user_form,
                        cd_profile_form,
                    )
                    user.save()
                    profile.save()
                else:
                    # Logged in user or an existing stub account.
                    user = user_form.save()
                    profile = profile_form.save()

                d = donation_form.save(commit=False)
                d.status = response['status']
                d.payment_id = response['payment_id']
                d.transaction_id = response.get('transaction_id')  # Will only work for Paypal.
                d.donor = user
                d.save()

                return HttpResponseRedirect(response['redirect'])

            else:
                logger.critical("Got back status of %s when making initial "
                                "request of API. Message was:\n%s" %
                                (response['status'], response['message']))
                message = response['message']
    else:
        # Loading the page...
        try:
            donation_form = DonationForm(
                initial={
                    'referrer': request.GET.get('referrer')
                }
            )
            user_form = UserForm(
                initial={
                    'first_name': request.user.first_name,
                    'last_name': request.user.last_name,
                    'email': request.user.email,
                }
            )
            up = request.user.profile
            profile_form = ProfileForm(
                initial={
                    'address1': up.address1,
                    'address2': up.address2,
                    'city': up.city,
                    'state': up.state,
                    'zip_code': up.zip_code,
                    'wants_newsletter': up.wants_newsletter
                }
            )
        except AttributeError:
            # for anonymous users, who lack profile info
            user_form = UserForm()
            profile_form = ProfileForm()

    return render_to_response(
        'donate.html',
        {
            'donation_form': donation_form,
            'user_form': user_form,
            'profile_form': profile_form,
            'private': False,
            'message': message,
            'stripe_public_key': settings.STRIPE_PUBLIC_KEY
        },
        RequestContext(request)
    )

Example 116

Project: django-rosetta Source File: views.py
Function: home
@never_cache
@user_passes_test(lambda user: can_translate(user), settings.LOGIN_URL)
def home(request):
    """
    Displays a list of messages to be translated
    """

    def fix_nls(in_, out_):
        """Fixes submitted translations by filtering carriage returns and pairing
        newlines at the begging and end of the translated string with the original
        """
        if 0 == len(in_) or 0 == len(out_):
            return out_

        if "\r" in out_ and "\r" not in in_:
            out_ = out_.replace("\r", '')

        if "\n" == in_[0] and "\n" != out_[0]:
            out_ = "\n" + out_
        elif "\n" != in_[0] and "\n" == out_[0]:
            out_ = out_.lstrip()
        if 0 == len(out_):
            pass
        elif "\n" == in_[-1] and "\n" != out_[-1]:
            out_ = out_ + "\n"
        elif "\n" != in_[-1] and "\n" == out_[-1]:
            out_ = out_.rstrip()
        return out_

    def _request_request(key, default=None):
        if key in request.GET:
            return request.GET.get(key)
        elif key in request.POST:
            return request.POST.get(key)
        return default

    storage = get_storage(request)
    query = ''
    if storage.has('rosetta_i18n_fn'):
        rosetta_i18n_fn = storage.get('rosetta_i18n_fn')

        rosetta_i18n_app = get_app_name(rosetta_i18n_fn)
        rosetta_i18n_lang_code = storage.get('rosetta_i18n_lang_code')
        rosetta_i18n_lang_bidi = rosetta_i18n_lang_code.split('-')[0] in settings.LANGUAGES_BIDI
        rosetta_i18n_write = storage.get('rosetta_i18n_write', True)
        if rosetta_i18n_write:
            rosetta_i18n_pofile = pofile(rosetta_i18n_fn, wrapwidth=rosetta_settings.POFILE_WRAP_WIDTH)
            for entry in rosetta_i18n_pofile:
                entry.md5hash = hashlib.md5(
                    (six.text_type(entry.msgid) +
                        six.text_type(entry.msgstr) +
                        six.text_type(entry.msgctxt or "")).encode('utf8')
                ).hexdigest()

        else:
            rosetta_i18n_pofile = storage.get('rosetta_i18n_pofile')

        if 'filter' in request.GET:
            if request.GET.get('filter') in ('untranslated', 'translated', 'fuzzy', 'all'):
                filter_ = request.GET.get('filter')
                storage.set('rosetta_i18n_filter', filter_)
                return HttpResponseRedirect(reverse('rosetta-home'))

        rosetta_i18n_filter = storage.get('rosetta_i18n_filter', 'all')

        if '_next' in request.POST:
            rx = re.compile(r'^m_([0-9a-f]+)')
            rx_plural = re.compile(r'^m_([0-9a-f]+)_([0-9]+)')
            file_change = False
            for key, value in request.POST.items():
                md5hash = None
                plural_id = None

                if rx_plural.match(key):
                    md5hash = str(rx_plural.match(key).groups()[0])
                    # polib parses .po files into unicode strings, but
                    # doesn't bother to convert plural indexes to int,
                    # so we need unicode here.
                    plural_id = six.text_type(rx_plural.match(key).groups()[1])

                    # Above no longer true as of Polib 1.0.4
                    if plural_id and plural_id.isdigit():
                        plural_id = int(plural_id)

                elif rx.match(key):
                    md5hash = str(rx.match(key).groups()[0])

                if md5hash is not None:
                    entry = rosetta_i18n_pofile.find(md5hash, 'md5hash')
                    # If someone did a makemessage, some entries might
                    # have been removed, so we need to check.
                    if entry:
                        old_msgstr = entry.msgstr
                        if plural_id is not None:
                            plural_string = fix_nls(entry.msgid_plural, value)
                            entry.msgstr_plural[plural_id] = plural_string
                        else:
                            entry.msgstr = fix_nls(entry.msgid, value)

                        is_fuzzy = bool(request.POST.get('f_%s' % md5hash, False))
                        old_fuzzy = 'fuzzy' in entry.flags

                        if old_fuzzy and not is_fuzzy:
                            entry.flags.remove('fuzzy')
                        elif not old_fuzzy and is_fuzzy:
                            entry.flags.append('fuzzy')

                        file_change = True

                        if old_msgstr != value or old_fuzzy != is_fuzzy:
                            entry_changed.send(sender=entry,
                                               user=request.user,
                                               old_msgstr=old_msgstr,
                                               old_fuzzy=old_fuzzy,
                                               pofile=rosetta_i18n_fn,
                                               language_code=rosetta_i18n_lang_code,
                                               )

                    else:
                        storage.set('rosetta_last_save_error', True)

            if file_change and rosetta_i18n_write:
                try:
                    rosetta_i18n_pofile.metadata['Last-Translator'] = unicodedata.normalize('NFKD', u"%s %s <%s>" % (
                        getattr(request.user, 'first_name', 'Anonymous'),
                        getattr(request.user, 'last_name', 'User'),
                        getattr(request.user, 'email', '[email protected]')
                    )).encode('ascii', 'ignore')
                    rosetta_i18n_pofile.metadata['X-Translated-Using'] = u"django-rosetta %s" % rosetta.get_version(False)
                    rosetta_i18n_pofile.metadata['PO-Revision-Date'] = timestamp_with_timezone()
                except UnicodeDecodeError:
                    pass

                try:
                    rosetta_i18n_pofile.save()
                    po_filepath, ext = os.path.splitext(rosetta_i18n_fn)

                    if rosetta_settings.AUTO_COMPILE:
                        save_as_mo_filepath = po_filepath + '.mo'
                        rosetta_i18n_pofile.save_as_mofile(save_as_mo_filepath)

                    post_save.send(sender=None, language_code=rosetta_i18n_lang_code, request=request)
                    # Try auto-reloading via the WSGI daemon mode reload mechanism
                    if rosetta_settings.WSGI_AUTO_RELOAD and \
                        'mod_wsgi.process_group' in request.environ and \
                        request.environ.get('mod_wsgi.process_group', None) and \
                        'SCRIPT_FILENAME' in request.environ and \
                            int(request.environ.get('mod_wsgi.script_reloading', '0')):
                            try:
                                os.utime(request.environ.get('SCRIPT_FILENAME'), None)
                            except OSError:
                                pass
                    # Try auto-reloading via uwsgi daemon reload mechanism
                    if rosetta_settings.UWSGI_AUTO_RELOAD:
                        try:
                            import uwsgi
                            # pretty easy right?
                            uwsgi.reload()
                        except:
                            # we may not be running under uwsgi :P
                            pass

                except Exception as e:
                    messages.error(request, e)
                    storage.set('rosetta_i18n_write', False)
                storage.set('rosetta_i18n_pofile', rosetta_i18n_pofile)

                # Retain query arguments
                query_arg = '?_next=1'
                if _request_request('query', False):
                    query_arg += '&query=%s' % _request_request('query')
                if 'page' in request.GET:
                    query_arg += '&page=%d&_next=1' % int(request.GET.get('page'))
                return HttpResponseRedirect(reverse('rosetta-home') + iri_to_uri(query_arg))
        rosetta_i18n_lang_code = storage.get('rosetta_i18n_lang_code')

        if _request_request('query', False) and _request_request('query', '').strip():
            query = _request_request('query', '').strip()
            rx = re.compile(re.escape(query), re.IGNORECASE)
            paginator = Paginator([e_ for e_ in rosetta_i18n_pofile if not e_.obsolete and rx.search(six.text_type(e_.msgstr) + six.text_type(e_.msgid) + u''.join([o[0] for o in e_.occurrences]))], rosetta_settings.MESSAGES_PER_PAGE)
        else:
            if rosetta_i18n_filter == 'untranslated':
                paginator = Paginator(rosetta_i18n_pofile.untranslated_entries(), rosetta_settings.MESSAGES_PER_PAGE)
            elif rosetta_i18n_filter == 'translated':
                paginator = Paginator(rosetta_i18n_pofile.translated_entries(), rosetta_settings.MESSAGES_PER_PAGE)
            elif rosetta_i18n_filter == 'fuzzy':
                paginator = Paginator([e_ for e_ in rosetta_i18n_pofile.fuzzy_entries() if not e_.obsolete], rosetta_settings.MESSAGES_PER_PAGE)
            else:
                paginator = Paginator([e_ for e_ in rosetta_i18n_pofile if not e_.obsolete], rosetta_settings.MESSAGES_PER_PAGE)

        if rosetta_settings.ENABLE_REFLANG:
            ref_lang = storage.get('rosetta_i18n_ref_lang_code', 'msgid')
            ref_pofile = None
            if ref_lang != 'msgid':
                ref_fn = re.sub('/locale/[a-z]{2}/', '/locale/%s/' % ref_lang, rosetta_i18n_fn)
                try:
                    ref_pofile = pofile(ref_fn)
                except IOError:
                    # there's a syntax error in the PO file and polib can't open it. Let's just
                    # do nothing and thus display msgids.
                    pass

            for o in paginator.object_list:
                # default
                o.ref_txt = o.msgid
                if ref_pofile is not None:
                    ref_entry = ref_pofile.find(o.msgid)
                    if ref_entry is not None and ref_entry.msgstr:
                        o.ref_txt = ref_entry.msgstr
            LANGUAGES = list(settings.LANGUAGES) + [('msgid', 'MSGID')]
        else:
            ref_lang = None
            LANGUAGES = settings.LANGUAGES

        page = 1
        if 'page' in request.GET:
            try:
                get_page = int(request.GET.get('page'))
            except ValueError:
                page = 1  # fall back to page 1
            else:
                if 0 < get_page <= paginator.num_pages:
                    page = get_page

        if '_next' in request.GET or '_next' in request.POST:
            page += 1
            if page > paginator.num_pages:
                page = 1
            query_arg = '?page=%d' % page
            return HttpResponseRedirect(reverse('rosetta-home') + iri_to_uri(query_arg))

        rosetta_messages = paginator.page(page).object_list
        main_language = None
        if rosetta_settings.MAIN_LANGUAGE and rosetta_settings.MAIN_LANGUAGE != rosetta_i18n_lang_code:
            for language in settings.LANGUAGES:
                if language[0] == rosetta_settings.MAIN_LANGUAGE:
                    main_language = _(language[1])
                    break

            fl = ("/%s/" % rosetta_settings.MAIN_LANGUAGE).join(rosetta_i18n_fn.split("/%s/" % rosetta_i18n_lang_code))
            po = pofile(fl)

            for message in rosetta_messages:
                message.main_lang = po.find(message.msgid).msgstr

        needs_pagination = paginator.num_pages > 1
        if needs_pagination:
            if paginator.num_pages >= 10:
                page_range = pagination_range(1, paginator.num_pages, page)
            else:
                page_range = range(1, 1 + paginator.num_pages)
        try:
            ADMIN_MEDIA_PREFIX = settings.ADMIN_MEDIA_PREFIX
            ADMIN_IMAGE_DIR = ADMIN_MEDIA_PREFIX + 'img/admin/'
        except AttributeError:
            ADMIN_MEDIA_PREFIX = settings.STATIC_URL + 'admin/'
            ADMIN_IMAGE_DIR = ADMIN_MEDIA_PREFIX + 'img/'

        if storage.has('rosetta_last_save_error'):
            storage.delete('rosetta_last_save_error')
            rosetta_last_save_error = True
        else:
            rosetta_last_save_error = False

        try:
            rosetta_i18n_lang_name = force_text(_(storage.get('rosetta_i18n_lang_name')))
        except:
            rosetta_i18n_lang_name = force_text(storage.get('rosetta_i18n_lang_name'))

        return render(request, 'rosetta/pofile.html', dict(
            version=rosetta.get_version(True),
            ADMIN_MEDIA_PREFIX=ADMIN_MEDIA_PREFIX,
            ADMIN_IMAGE_DIR=ADMIN_IMAGE_DIR,
            ENABLE_REFLANG=rosetta_settings.ENABLE_REFLANG,
            LANGUAGES=LANGUAGES,
            rosetta_settings=rosetta_settings,
            rosetta_i18n_lang_name=rosetta_i18n_lang_name,
            rosetta_i18n_lang_code=rosetta_i18n_lang_code,
            rosetta_i18n_lang_bidi=rosetta_i18n_lang_bidi,
            rosetta_last_save_error=rosetta_last_save_error,
            rosetta_i18n_filter=rosetta_i18n_filter,
            rosetta_i18n_write=rosetta_i18n_write,
            rosetta_messages=rosetta_messages,
            page_range=needs_pagination and page_range,
            needs_pagination=needs_pagination,
            main_language=main_language,
            rosetta_i18n_app=rosetta_i18n_app,
            page=page,
            query=query,
            paginator=paginator,
            rosetta_i18n_pofile=rosetta_i18n_pofile,
            ref_lang=ref_lang,
        ))
    else:
        return list_languages(request, do_session_warn=True)

Example 117

Project: ganetimgr Source File: instances.py
Function: instance
@login_required
@check_instance_readonly
def instance(request, cluster_slug, instance):
    cluster = get_object_or_404(Cluster, slug=cluster_slug)
    instance = cluster.get_instance_or_404(instance)
    if request.method == 'POST':
        configform = InstanceConfigForm(request.POST)
        if configform.is_valid():
            needs_reboot = False
            # The instance needs reboot if any of the hvparams have changed.
            if configform.cleaned_data['cdrom_type'] == 'none':
                configform.cleaned_data['cdrom_image_path'] = ""
            for key, val in configform.cleaned_data.items():
                if key == "cdrom_type":
                    continue
                if key == "whitelist_ip":
                    continue
                if configform.cleaned_data[key] != instance.hvparams[key]:
                    if instance.admin_state:
                        needs_reboot = True
            if configform.cleaned_data['cdrom_type'] == 'none':
                configform.cleaned_data['cdrom_image_path'] = ""
            elif (configform.cleaned_data['cdrom_image_path'] !=
                  instance.hvparams['cdrom_image_path']):
                # This should be an http URL
                if (
                    not (
                        configform.cleaned_data['cdrom_image_path'].startswith(
                            'http://'
                        ) or
                        configform.cleaned_data['cdrom_image_path'].startswith(
                            'https://'
                        ) or
                        configform.cleaned_data['cdrom_image_path'] == ""
                    )
                ):
                    # Remove this, we don't want them to
                    # be able to read local files
                    del configform.cleaned_data['cdrom_image_path']
            data = {}
            whitelistip = None
            for key, val in configform.cleaned_data.items():
                if key == "cdrom_type":
                    continue
                if key == "whitelist_ip":
                    whitelistip = val
                    if len(val) == 0:
                        whitelistip = None
                    continue
                data[key] = val
            auditlog = auditlog_entry(
                request,
                "Setting %s" % (
                    ", ".join(
                        [
                            "%s:%s" % (key, value) for key, value in data.iteritems()
                        ]
                    )
                ),
                instance,
                cluster_slug
            )
            jobid = instance.set_params(hvparams=data)
            auditlog.update(job_id=jobid)
            if needs_reboot:
                instance.cluster.tag_instance(
                    instance.name,
                    ["%s:needsreboot" % (settings.GANETI_TAG_PREFIX)]
                )
            if instance.whitelistip and whitelistip is None:
                auditlog = auditlog_entry(
                    request,
                    "Remove whitelist %s" % instance.whitelistip,
                    instance,
                    cluster_slug
                )
                jobid = instance.cluster.untag_instance(
                    instance.name,
                    ["%s:whitelist_ip:%s" % (
                        settings.GANETI_TAG_PREFIX,
                        instance.whitelistip
                    )]
                )
                auditlog.update(job_id=jobid)
                instance.cluster.migrate_instance(instance.name)
            if whitelistip:
                if instance.whitelistip:
                    auditlog = auditlog_entry(
                        request,
                        "Remove whitelist %s" % instance.whitelistip,
                        instance,
                        cluster_slug
                    )
                    jobid = instance.cluster.untag_instance(
                        instance.name,
                        ["%s:whitelist_ip:%s" % (
                            settings.GANETI_TAG_PREFIX,
                            instance.whitelistip
                        )])
                    auditlog.update(job_id=jobid)
                auditlog = auditlog_entry(
                    request,
                    "Add whitelist %s" % whitelistip, instance, cluster_slug
                )
                jobid = instance.cluster.tag_instance(
                    instance.name,
                    ["%s:whitelist_ip:%s" % (settings.GANETI_TAG_PREFIX, whitelistip)]
                )
                auditlog.update(job_id=jobid)
                instance.cluster.migrate_instance(instance.name)
            # Prevent form re-submission via browser refresh
            return HttpResponseRedirect(
                reverse(
                    'instance-detail',
                    kwargs={'cluster_slug': cluster_slug, 'instance': instance}
                )
            )
    else:
        if 'cdrom_image_path' in instance.hvparams.keys():
            if instance.hvparams['cdrom_image_path']:
                instance.hvparams['cdrom_type'] = 'iso'
            else:
                instance.hvparams['cdrom_type'] = 'none'
        else:
            instance.hvparams['cdrom_type'] = 'none'
        if instance.whitelistip:
            instance.hvparams['whitelist_ip'] = instance.whitelistip
        else:
            instance.hvparams['whitelist_ip'] = ''
        configform = InstanceConfigForm(instance.hvparams)
    instance.cpu_url = reverse(
        'graph',
        args=(cluster.slug, instance.name, 'cpu-ts')
    )
    instance.net_url = []
    for (nic_i, link) in enumerate(instance.nic_links):
        instance.net_url.append(
            reverse(
                'graph',
                args=(cluster.slug, instance.name, 'net-ts', '/eth%s' % nic_i)
            )
        )

    instance.netw = []
    try:
        instance.osname = get_os_details(
            instance.osparams['img_id']).get(
            'description', instance.osparams['img_id']
        )
    except Exception:
        try:
            instance.osname = instance.osparams['img_id']
        except Exception:
            instance.osname = instance.os
    instance.node_group_locked = instance.pnode in instance.cluster.locked_nodes_from_nodegroup()
    for (nic_i, link) in enumerate(instance.nic_links):
        if instance.nic_ips[nic_i] is None:
            instance.netw.append("%s" % (instance.nic_links[nic_i]))
        else:
            instance.netw.append("%s@%s" % (
                instance.nic_ips[nic_i], instance.nic_links[nic_i])
            )
    if instance.isolate and instance.whitelistip is None:

        djmessages.add_message(
            request,
            msgs.ERROR,
            "Your instance is isolated from the network and" +
            " you have not set an \"Allowed From\" address." +
            " To access your instance from a specific network range," +
            " you can set it via the instance configuration form"
        )
    if instance.needsreboot:
        djmessages.add_message(
            request,
            msgs.ERROR,
            "You have modified one or more of your instance's core " +
            "configuration components  (any of network adapter, hard" +
            " disk type, boot device, cdrom). In order for these changes " +
            "to take effect, you need to <strong>Reboot</strong>" +
            " your instance.",
            extra_tags='safe'
        )
    ret_dict = {'cluster': cluster,
                'instance': instance
                }
    if not request.user.has_perm('ganeti.view_instances') or (
        request.user.is_superuser or
        request.user in instance.users or
        set.intersection(set(request.user.groups.all()), set(instance.groups))
    ):
            ret_dict['configform'] = configform
    return render(
        request,
        'instances/instance.html',
        ret_dict
    )

Example 118

Project: mozillians Source File: views.py
@allow_unvouched
@never_cache
def edit_profile(request):
    """Edit user profile view."""
    # Don't use request.user
    user = User.objects.get(pk=request.user.id)
    profile = user.userprofile
    user_groups = profile.groups.all().order_by('name')
    emails = ExternalAccount.objects.filter(type=ExternalAccount.TYPE_EMAIL)
    accounts_qs = ExternalAccount.objects.exclude(type=ExternalAccount.TYPE_EMAIL)

    sections = {
        'registration_section': ['user_form', 'registration_form'],
        'basic_section': ['user_form', 'basic_information_form'],
        'groups_section': ['groups_privacy_form'],
        'skills_section': ['skills_form'],
        'email_section': ['email_privacy_form', 'alternate_email_formset'],
        'languages_section': ['language_privacy_form', 'language_formset'],
        'accounts_section': ['accounts_formset'],
        'irc_section': ['irc_form'],
        'location_section': ['location_form'],
        'contribution_section': ['contribution_form'],
        'tshirt_section': ['tshirt_form'],
        'developer_section': ['developer_form']
    }

    curr_sect = next((s for s in sections.keys() if s in request.POST), None)

    def get_request_data(form):
        if curr_sect and form in sections[curr_sect]:
            return request.POST
        return None

    ctx = {}
    ctx['user_form'] = forms.UserForm(get_request_data('user_form'), instance=user)
    ctx['registration_form'] = forms.RegisterForm(get_request_data('registration_form'),
                                                  request.FILES or None,
                                                  instance=profile)
    basic_information_data = get_request_data('basic_information_form')
    ctx['basic_information_form'] = forms.BasicInformationForm(basic_information_data,
                                                               request.FILES or None,
                                                               instance=profile)
    ctx['accounts_formset'] = forms.AccountsFormset(get_request_data('accounts_formset'),
                                                    instance=profile,
                                                    queryset=accounts_qs)
    ctx['language_formset'] = forms.LanguagesFormset(get_request_data('language_formset'),
                                                     instance=profile,
                                                     locale=request.locale)
    language_privacy_data = get_request_data('language_privacy_form')
    ctx['language_privacy_form'] = forms.LanguagesPrivacyForm(language_privacy_data,
                                                              instance=profile)
    ctx['skills_form'] = forms.SkillsForm(get_request_data('skills_form'), instance=profile)
    location_initial = {
        'saveregion': True if profile.geo_region else False,
        'savecity': True if profile.geo_city else False,
        'lat': profile.lat,
        'lng': profile.lng
    }
    ctx['location_form'] = forms.LocationForm(get_request_data('location_form'), instance=profile,
                                              initial=location_initial)
    ctx['contribution_form'] = forms.ContributionForm(get_request_data('contribution_form'),
                                                      instance=profile)
    ctx['tshirt_form'] = forms.TshirtForm(get_request_data('tshirt_form'), instance=profile)
    ctx['groups_privacy_form'] = forms.GroupsPrivacyForm(get_request_data('groups_privacy_form'),
                                                         instance=profile)
    ctx['irc_form'] = forms.IRCForm(get_request_data('irc_form'), instance=profile)
    ctx['developer_form'] = forms.DeveloperForm(get_request_data('developer_form'),
                                                instance=profile)
    ctx['email_privacy_form'] = forms.EmailPrivacyForm(get_request_data('email_privacy_form'),
                                                       instance=profile)
    alternate_email_formset_data = get_request_data('alternate_email_formset')
    ctx['alternate_email_formset'] = forms.AlternateEmailFormset(alternate_email_formset_data,
                                                                 instance=profile,
                                                                 queryset=emails)
    forms_valid = True
    if request.POST:
        if not curr_sect:
            raise Http404
        curr_forms = map(lambda x: ctx[x], sections[curr_sect])
        forms_valid = all(map(lambda x: x.is_valid(), curr_forms))
        if forms_valid:
            old_username = request.user.username
            for f in curr_forms:
                f.save()

            # Spawn task to check for spam
            if not profile.can_vouch:
                params = {
                    'instance_id': profile.id,
                    'user_ip': request.META.get('REMOTE_ADDR'),
                    'user_agent': request.META.get('HTTP_USER_AGENT'),
                    'referrer': request.META.get('HTTP_REFERER'),
                    'comment_author': profile.full_name,
                    'comment_author_email': profile.email,
                    'comment_content': profile.bio
                }

                check_spam_account.delay(**params)

            next_section = request.GET.get('next')
            next_url = urlparams(reverse('phonebook:profile_edit'), next_section)
            if curr_sect == 'registration_section':
                settings_url = reverse('phonebook:profile_edit')
                settings_link = '<a href="{0}">settings</a>'.format(settings_url)
                msg = _(u'Your registration is complete. '
                        u'Feel free to visit the {0} page to add '
                        u'additional information to your profile.'.format(settings_link))
                messages.info(request, mark_safe(msg))
                redeem_invite(profile, request.session.get('invite-code'))
                next_url = reverse('phonebook:profile_view', args=[user.username])
            elif user.username != old_username:
                msg = _(u'You changed your username; '
                        u'please note your profile URL has also changed.')
                messages.info(request, _(msg))
            return HttpResponseRedirect(next_url)

    ctx.update({
        'user_groups': user_groups,
        'profile': request.user.userprofile,
        'vouch_threshold': settings.CAN_VOUCH_THRESHOLD,
        'mapbox_id': settings.MAPBOX_PROFILE_ID,
        'apps': user.apiapp_set.filter(is_active=True),
        'appsv2': profile.apps.filter(enabled=True),
        'forms_valid': forms_valid
    })

    return render(request, 'phonebook/edit_profile.html', ctx)

Example 119

Project: ocf Source File: views.py
def flowspace(request, slice_id, fsmode = 'advanced', free_vlan = None, alertMessage=""):
    """
    Add flowspace.
    """
    slice = get_object_or_404(Slice, id=slice_id)

    class SliverMultipleChoiceField(forms.ModelMultipleChoiceField):
        def label_from_instance(self, obj):
            return "%s" % obj.resource.as_leaf_class()

        def widget_attrs(self, widget):
            return {"class": "wide"}

    def formfield_callback(f):
        if f.name == "slivers":
            return SliverMultipleChoiceField(
                queryset=OpenFlowInterfaceSliver.objects.filter(slice=slice),
                initial=OpenFlowInterfaceSliver.objects.filter(slice=slice))
        else:
            return f.formfield()

    if request.method == "POST":
        continue_to_start_slice = False
        
        # No extra forms apart from the one being shown
        flowspace_form_number = 0
        
        if fsmode == 'failed':
            # If an exception was risen from the previous step, the flowspace needs to be requested here
            flowspace_form_number = 1
        
        # create a formset to handle all flowspaces
        FSFormSet = forms.models.modelformset_factory(
            model=FlowSpaceRule,
            formfield_callback=formfield_callback,
            can_delete=True,
            extra=flowspace_form_number,
        )
        
        # Default formset
        formset = FSFormSet(
            queryset=FlowSpaceRule.objects.filter(
                slivers__slice=slice).distinct(),
        )
        if formset.is_valid():
            formset.save()

        if fsmode == 'advanced':
            formset = FSFormSet(
                request.POST,
                queryset=FlowSpaceRule.objects.filter(
                    slivers__slice=slice).distinct(),
            )
            if formset.is_valid():
                formset.save()
                continue_to_start_slice = True
        elif fsmode == 'simple':
            #create a simple flowspacerule containing only the vlans tags and the OF ports
            try:
                #create_simple_slice_vlan_based(free_vlan[0], slice)
                create_slice_with_vlan_range(slice, free_vlan)
                continue_to_start_slice = True
            except:
                #continue_to_start_slice flag will deal with this
                pass

        if continue_to_start_slice:
            slice_save_start(request, slice_id)
            if fsmode == 'simple':
                return HttpResponseRedirect(reverse("slice_detail", args=[slice_id]))
            else:
                return HttpResponseRedirect(request.path)

    elif request.method == "GET":
        flowspace_form_contents = FlowSpaceRule.objects.filter(slivers__slice=slice).distinct()
        flowspace_form_number = 1

        # When coming from the OpenFlow switches topology selection page...
        if "HTTP_REFERER" in request.META:
            # Checks if the referer page is the topology selcetion
            if reverse("book_openflow", args=[slice_id]) in request.META['HTTP_REFERER']:
                # If no flowspace has been selected yet, show an extra form to allow user to choose at least one
                if not flowspace_form_contents:
                    flowspace_form_number = 1 # Show an extra (1) form besides the already selected one
                # Otherwise, when there is some already requested flowspace, show only the requested ones (no extra forms)
                else:
                    flowspace_form_number = 0 # No extra forms apart from the one(s) being shown
        
        # Redefine formset to handle all flowspaces
        # Extra: field that determines how many extra flowspaces there are
        FSFormSet = forms.models.modelformset_factory(
            model=FlowSpaceRule,
            formfield_callback=formfield_callback,
            can_delete=True,
            extra=flowspace_form_number, # Show number of forms according to origin path request and so on
        )
        formset = FSFormSet(
            queryset=flowspace_form_contents,
        )

    else:
        return HttpResponseNotAllowed("GET", "POST")

    done = PlanetLabSliver.objects.filter(slice=slice).count() == 0

    return simple.direct_to_template(
        request,
        template="openflow_select_flowspace.html",
        extra_context={
            "slice": slice,
            "fsformset": formset,
            "alertMessage":alertMessage,
            "done": done,
            "breadcrumbs": (
                ("Home", reverse("home")),
                ("Project %s" % slice.project.name, reverse("project_detail", args=[slice.project.id])),
                ("Slice %s" % slice.name, reverse("slice_detail", args=[slice_id])),
                ("Choose Flowspace", reverse("flowspace", args=[slice_id])),
            ),
        },
    )

Example 120

Project: pyfreebilling Source File: views.py
@user_passes_test(lambda u: u.is_superuser)
@staff_member_required
def live_report_view(request):
    """ selecting cdr and live stats calculated from selection """

    form = CDRSearchForm(request.user, request.POST or None)

    if request.method == 'POST':

        if form.is_valid():
            query_string = ''
            query_answer = ''

            tzname = settings.TIME_ZONE
            offset = datetime.datetime.now(
                pytz.timezone(tzname)).strftime('%z')

            from_date = getvar(request, 'from_date_0')
            if from_date:
                formated_date = from_date[0:4] + '-' + from_date[8:10] + '-' + from_date[
                    5:7] + '+' + from_date[11:13] + '%3A' + from_date[14:16] + '%3A00'
                if offset[0] == '+':
                    formated_date = formated_date + '%2B'
                else:
                    formated_date = formated_date + '%2D'
                formated_date = formated_date + \
                    offset[1:3] + '%3A' + offset[3:5]
                date_string = 'start_stamp__gte=' + str(formated_date)
                query_string = return_query_string(query_string, date_string)
                #import pdb; pdb.set_trace()

            to_date = getvar(request, 'to_date_0')
            if to_date:
                formated_date = to_date[0:4] + '-' + to_date[8:10] + '-' + to_date[
                    5:7] + '+' + to_date[11:13] + '%3A' + to_date[14:16] + '%3A00'
                if offset[0] == '+':
                    formated_date = formated_date + '%2B'
                else:
                    formated_date = formated_date + '%2D'
                formated_date = formated_date + \
                    offset[1:3] + '%3A' + offset[3:5]
                date_string = 'start_stamp__lt=' + str(formated_date)
                query_string = return_query_string(query_string, date_string)

            customer_id = getvar(request, 'customer_id')
            if customer_id and customer_id != '0':
                customer_string = 'customer__id__exact=' + str(customer_id)
                query_string = return_query_string(
                    query_string, customer_string)

            provider_id = getvar(request, 'provider_id')
            if provider_id and provider_id != '0':
                provider_string = 'lcr_carrier_id__id__exact=' + \
                    str(provider_id)
                query_string = return_query_string(
                    query_string, provider_string)

            ratecard_id = getvar(request, 'ratecard_id')
            if ratecard_id and ratecard_id != '0':
                ratecard_string = 'ratecard_id__id__exact=' + str(ratecard_id)
                query_string = return_query_string(
                    query_string, ratecard_string)

            lcr_id = getvar(request, 'lcr_id')
            if lcr_id and lcr_id != '0':
                lcr_string = 'lcr_group_id__id__exact=' + str(lcr_id)
                query_string = return_query_string(query_string, lcr_string)

            dest_num = getvar(request, 'dest_num')
            if dest_num:
                dstnum_string = 'destination_number__startswith=' + \
                    str(dest_num)
                query_string = return_query_string(query_string, dstnum_string)

            if query_string:
                query_answer = '/extranet/pyfreebill/cdr/?' + str(query_string)
            else:
                query_answer = '/extranet/pyfreebill/cdr/'

            return HttpResponseRedirect(query_answer)
    else:
        form = CDRSearchForm(request.user)

    request.session['msg'] = ''
    request.session['error_msg'] = ''

    return render_to_response('admin/live_report.html', locals(),
                              context_instance=RequestContext(request))

Example 121

Project: django-uocLTI Source File: views.py
@csrf_exempt
def launch_lti(request):
    """ Receives a request from the lti consumer and creates/authenticates user in django """

    """ See post items in log by setting LTI_DEBUG=True in settings """    
    if settings.LTI_DEBUG:
        for item in request.POST:
            print ('%s: %s \r' % (item, request.POST[item]))

    if 'oauth_consumer_key' not in request.POST:
        raise PermissionDenied()  
    
    """ key/secret from settings """
    consumer_key = settings.CONSUMER_KEY 
    secret = settings.LTI_SECRET
    
    tool_provider = DjangoToolProvider(consumer_key, secret, request.POST)
    print "ROLES:  %s " % tool_provider.roles
    
    try: # attempt to validate request, if fails raises 403 Forbidden
        if tool_provider.valid_request(request) == False:
            raise PermissionDenied()
    except:
        raise PermissionDenied() 
    
    """ RETRIEVE username, names, email and roles.  These may be specific to the consumer, 
    in order to change them from the default values:  see README.txt """
    first_name = get_lti_value(settings.LTI_FIRST_NAME, tool_provider)
    last_name = get_lti_value(settings.LTI_LAST_NAME, tool_provider)
    email = get_lti_value(settings.LTI_EMAIL, tool_provider)
#    avatar = tool_provider.custom_params['custom_photo'] 
    roles = get_lti_value(settings.LTI_ROLES, tool_provider)
    user_id = get_lti_value('user_id', tool_provider)
    
    if not email or not user_id:
        print "Email and/or user_id wasn't found in post, return Permission Denied"
        raise PermissionDenied()    
    
    """ CHECK IF USER'S ROLES ALLOW ENTRY, IF RESTRICTION SET BY VELVET_ROLES SETTING """
    if settings.VELVET_ROLES:
        """ Roles allowed for entry into the application.  If these are not set in settings then we allow all roles to enter """
        if not roles:
            """ if roles is None, then setting for LTI_ROLES may be wrong, return 403 for user and print error to log """
            print "VELVET_ROLES is set but the roles for the user were not found.  Check that the setting for LTI_ROLES is correct."
            raise PermissionDenied()
        if not isinstance(roles, list): roles = (roles,) # In the case we are using a custom field for roles, may be a string and needs to be converted to a list
        is_role_allowed = [m for velvet_role in settings.VELVET_ROLES for m in roles if velvet_role.lower()==m.lower()]
        if not is_role_allowed:
            print "User does not have accepted role for entry, roles: %s" % roles
            raise PermissionDenied() 
    
    """ GET OR CREATE NEW USER AND LTI_PROFILE """
    lti_username = '%s:user_%s' % (request.POST['oauth_consumer_key'], user_id) #create username with consumer_key and user_id
    try:
        """ Check if user already exists using email, if not create new """    
        user = User.objects.get(email=email)
        if user.username != lti_username:
            """ If the username is not in the format user_id, change it and save.  This could happen
            if there was a previously populated User table. """
            user.username = lti_username
            user.save()
    except User.DoesNotExist:
        """ first time entry, create new user """
        user = User.objects.create_user(lti_username, email)
        user.set_unusable_password()
        if first_name: user.first_name = first_name
        if last_name: user.last_name = last_name
        user.save()
    except User.MultipleObjectsReturned:
        """ If the application is not requiring unique emails, multiple users may be returned if there was an existing
        User table before implementing this app with multiple users for the same email address.  Could add code to merge them, but for now we return 404 if 
        the user with the lti_username does not exist """    
        user = get_object_or_404(User, username=lti_username)
            
    """ CHECK IF ANY OF USER'S ROLES ARE IN THE VELVET_ADMIN_ROLES SETTING, IF SO MAKE SUPERUSER IF IS NOT ALREADY """
    if not user.is_superuser and settings.VELVET_ADMIN_ROLES:
        if [m for l in settings.VELVET_ADMIN_ROLES for m in roles if l.lower() in m.lower()]:
            user.is_superuser = True
            user.is_staff = True
            user.save()
    
    """ Save extra info to custom profile model (add/remove fields in models.py)""" 
    lti_userprofile = user.get_profile()
    lti_userprofile.roles = roles
#    lti_userprofile.avatar = avatar  #TO BE ADDED:  function to grab user profile image if exists
    lti_userprofile.save()
    
    """ Log in user and redirect to LOGIN_REDIRECT_URL defined in settings (default: accounts/profile) """
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    login(request, user)

    return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) 
    

Example 122

Project: django-uocLTI Source File: views.py
@csrf_exempt
def launch_lti(request):
    """ Receives a request from the lti consumer and creates/authenticates user in django """

    """ See post items in log by setting LTI_DEBUG=True in settings """    
    if settings.LTI_DEBUG:
        for item in request.POST:
            print ('%s: %s \r' % (item, request.POST[item]))

    if 'oauth_consumer_key' not in request.POST:
        raise PermissionDenied()  
    
    """ key/secret from settings """
    consumer_key = settings.CONSUMER_KEY 
    secret = settings.LTI_SECRET    
    tool_provider = DjangoToolProvider(consumer_key, secret, request.POST)

    """ Decode parameters - UOC LTI uses a custom param to indicate the encoding: utf-8, iso-latin, base64 """
    encoding = None
    utf8 = get_lti_value('custom_lti_message_encoded_utf8', tool_provider)         
    iso = get_lti_value('custom_lti_message_encoded_iso', tool_provider)       
    b64 = get_lti_value('custom_lti_message_encoded_base64', tool_provider)  

    if iso and int(iso) == 1: encoding = 'iso'
    if utf8 and int(utf8) == 1: encoding = 'utf8'
    if b64 and int(b64) == 1: encoding = 'base64'
    
    try: # attempt to validate request, if fails raises 403 Forbidden
        if tool_provider.valid_request(request) == False:
            raise PermissionDenied()
    except:
        print "LTI Exception:  Not a valid request."
        raise PermissionDenied() 
    
    """ RETRIEVE username, names, email and roles.  These may be specific to the consumer, 
    in order to change them from the default values:  see README.txt """
    first_name = get_lti_value(settings.LTI_FIRST_NAME, tool_provider, encoding=encoding)
    last_name = get_lti_value(settings.LTI_LAST_NAME, tool_provider, encoding=encoding)
    email = get_lti_value(settings.LTI_EMAIL, tool_provider, encoding=encoding)
#    avatar = tool_provider.custom_params['custom_photo'] 
    roles = get_lti_value(settings.LTI_ROLES, tool_provider, encoding=encoding)
    uoc_roles = get_lti_value(settings.LTI_CUSTOM_UOC_ROLES, tool_provider, encoding=encoding)
    user_id = get_lti_value('user_id', tool_provider, encoding=encoding)
    test = get_lti_value('context_title', tool_provider, encoding=encoding)

    if not email or not user_id:
        if settings.LTI_DEBUG: print "Email and/or user_id wasn't found in post, return Permission Denied"
        raise PermissionDenied()    
    
    """ CHECK IF USER'S ROLES ALLOW ENTRY, IF RESTRICTION SET BY VELVET_ROLES SETTING """
    if settings.VELVET_ROLES:
        """ Roles allowed for entry into the application.  If these are not set in settings then we allow all roles to enter """
        if not roles and not uoc_roles:
            """ if roles is None, then setting for LTI_ROLES may be wrong, return 403 for user and print error to log """
            if settings.LTI_DEBUG: print "VELVET_ROLES is set but the roles for the user were not found.  Check that the setting for LTI_ROLES is correct."
            raise PermissionDenied()

        all_user_roles = []
        if roles:
            if not isinstance(roles, list): roles = (roles,)
            all_user_roles += roles
        if uoc_roles:
            if not isinstance(uoc_roles, list): uoc_roles = (uoc_roles,)
            all_user_roles += uoc_roles

        is_role_allowed = [m for velvet_role in settings.VELVET_ROLES for m in all_user_roles if velvet_role.lower()==m.lower()]

        if not is_role_allowed:
            if settings.LTI_DEBUG: print "User does not have accepted role for entry, roles: %s" % roles
            ctx = {'roles':roles, 'first_name':first_name, 'last_name':last_name, 'email':email, 'user_id':user_id}
            return render_to_response('lti_role_denied.html', ctx, context_instance=RequestContext(request))
        else:
            if settings.LTI_DEBUG: print "User has accepted role for entry, roles: %s" % roles
    
    """ GET OR CREATE NEW USER AND LTI_PROFILE """
    lti_username = '%s:user_%s' % (request.POST['oauth_consumer_key'], user_id) #create username with consumer_key and user_id
    try:
        """ Check if user already exists using email, if not create new """    
        user = User.objects.get(email=email)
        if user.username != lti_username:
            """ If the username is not in the format user_id, change it and save.  This could happen
            if there was a previously populated User table. """
            user.username = lti_username
            user.save()
    except User.DoesNotExist:
        """ first time entry, create new user """
        user = User.objects.create_user(lti_username, email)
        user.set_unusable_password()
        if first_name: user.first_name = first_name
        if last_name: user.last_name = last_name
        user.save()
    except User.MultipleObjectsReturned:
        """ If the application is not requiring unique emails, multiple users may be returned if there was an existing
        User table before implementing this app with multiple users for the same email address.  Could add code to merge them, but for now we return 404 if 
        the user with the lti_username does not exist """    
        user = get_object_or_404(User, username=lti_username)
            
    """ CHECK IF ANY OF USER'S ROLES ARE IN THE VELVET_ADMIN_ROLES SETTING, IF SO MAKE SUPERUSER IF IS NOT ALREADY """
    if not user.is_superuser and settings.VELVET_ADMIN_ROLES:
        if [m for l in settings.VELVET_ADMIN_ROLES for m in roles if l.lower() in m.lower()]:
            user.is_superuser = True
            user.is_staff = True
            user.save()
    
    """ Save extra info to custom profile model (add/remove fields in models.py)""" 
    lti_userprofile = get_object_or_404(LTIProfile, user=user)
    lti_userprofile.roles = (",").join(all_user_roles)
#    lti_userprofile.avatar = avatar  #TO BE ADDED:  function to grab user profile image if exists
    lti_userprofile.save()
    
    """ Log in user and redirect to LOGIN_REDIRECT_URL defined in settings (default: accounts/profile) """
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    login(request, user)

    return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) 
    

Example 123

Project: ocf Source File: views.py
def opt_in_from_file(request):
    '''
    This is doing the same as add_opt_in function except the input data
    is coming from an uploaded file
    '''
    
    profile = UserProfile.get_or_create_profile(request.user)
     
    if (not profile.is_net_admin):
        return HttpResponseRedirect("/dashboard")
    else:
        # find all experiments that the admin can opt into them.
        all_exps = Experiment.objects.all()
        admin_fs = AdminFlowSpace.objects.filter(user=request.user)
        exps = []
        for exp in all_exps:
            exp_fs = ExperimentFLowSpace.objects.filter(exp=exp)
            intersection = multi_fs_intersect(exp_fs,admin_fs,FlowSpace)
            if (len(intersection)>0):
                exps.append(exp)

        error_msg = []
        
        if (len(exps)>0):
            exp_exist = True
            first_exp = exps[0].id
        else:
            exp_exist = False
            first_exp = 0
        
        if (request.method == "POST"):
            uform = UploadFileForm(request.POST, request.FILES)
            
            # validate upload file form
            if uform.is_valid():
                
                # parse the file and find the list of flowspaces to be opted-in
                result = read_fs(request.FILES['file'])
                
                # check if an error happened while parsing the file, 
                if len(result["error"])==0:
                    
                    # find the priority for first opt-in
                    assigned_priority = profile.max_priority_level - Priority.Strict_Priority_Offset - 1
                    all_this_admin_opts = UserOpts.objects.filter(user=request.user,nice=True)
                    for admin_opt in all_this_admin_opts:
                            if admin_opt.priority <= assigned_priority:
                                assigned_priority = admin_opt.priority - 1
                    
                    fv_args = []
                    match_list = []
                    opt_expression = ""
                    for i in range(len(result['flowspace'])):
                        
                        # check if slice_id is specified
                        if result['slice_id'][i]==None:
                            error_msg.append("No opt-in slice specified for flowspace %s"%result['flowspace'])
                            transaction.rollback()
                            break
                        
                        #check if slice_id is valid
                        exp = Experiment.objects.filter(slice_id=result['slice_id'][i])
                        if exp.count()==0:
                            error_msg.append("No slice exist with id %s"%result['slice_id'][i])
                            transaction.rollback()
                            break
                        elif exp.count()>1:
                            raise Exception("Found more than one slice with the same id: %s. This is unexpected!"%result['slice_id'][i])
                        else:
                            exp = exp[0]
                            
                        if assigned_priority <= 0:
                            error_msg.append("Too many opt-ins")
                            transaction.rollback()
                            break
                            
                        # find the intersection of requested opt-in flowspace, admin's flowspace
                        # and the experiemnt's flowspace:
                        adminFS = AdminFlowSpace.objects.filter(user = request.user)
                        intersected_flowspace = multi_fs_intersect([result['flowspace'][i]],adminFS,FlowSpace)
                                                
                        if len(intersected_flowspace) == 0:
                            error_msg.append("Selected flowspace doesn't have any intersection with admin FS. Admin FS: %s, Selected FS: %s"%\
                                         (adminFS,result['flowspace'][i]))
                            transaction.rollback()
                            break
                        

                        # get the fv args for this opt-in
                        [new_fv_args,new_match_list] = opt_fs_into_exp(intersected_flowspace,
                                            exp,request.user,assigned_priority,True)
                        
                        fv_args = fv_args + new_fv_args
                        match_list = match_list + new_match_list
                        
                        opt_expression = opt_expression + exp.project_name + ":" + exp.slice_name + ", "
                        
                        # decrease assigned priority for next opt-in
                        assigned_priority = assigned_priority - 1
                        

                    if len(fv_args)==0:
                        error_msg.append("Nothing to opt-in!")
                        transaction.rollback()
                        
                    # now send FV Args using an XMLRPC call to FV
                    if len(error_msg)==0:
                        try:
                            fv = FVServerProxy.objects.all()[0]
                            try:
                                returned_ids = fv.proxy.api.changeFlowSpace(fv_args)
                                for i in range(len(match_list)):
                                    match_list[i].fv_id = returned_ids[i]
                                    match_list[i].save()
                                opt_expression = opt_expression[:-2]
                                return simple.direct_to_template(request, 
                                    template ="openflow/optin_manager/opts/opt_in_successful_admin.html",
                                    extra_context = {
                                    'expname':opt_expression,
                                    },
                                )
                            except Exception,e:
                                import traceback
                                traceback.print_exc()
                                transaction.rollback()
                                error_msg.append("Couldn't opt into the requested experiment, Flowvisor error: %s"%str(e))
                        except Exception,e:
                            import traceback
                            traceback.print_exc()
                            transaction.rollback()
                            error_msg.append("Flowvisor not set: %s"%str(e)) 
                        
                        
                    
                    
                # if there is an error while parsing the file         
                else:
                    error_msg = result["error"]

        
        form = AdminOptInForm()
        upload_form = UploadFileForm()
        return simple.direct_to_template(request, 
            template = 'openflow/optin_manager/opts/admin_opt_in.html', 
            extra_context = {
                'user':request.user,
                'experiments':exps,
                'error_msg':error_msg,
                'exp_exist':exp_exist,
                'first_exp':first_exp,
                'form':form,
                'upload_form':upload_form,
            },
        )

Example 124

Project: soclone Source File: views.py
Function: edit_question
def _edit_question(request, question):
    """
    Allows the user to edit a Question's title, text and tags.

    If the Question is not already in wiki mode, the user can put it in
    wiki mode, or it will automatically be put in wiki mode if the
    question has been edited five times by the person who asked it, or
    has been edited by four different users.
    """
    latest_revision = question.get_latest_revision()
    preview = None
    revision_form = None
    if request.method == 'POST':
        if 'select_revision' in request.POST:
            # The user submitted to change the revision to start editing from
            revision_form = RevisionForm(question, latest_revision, request.POST)
            if revision_form.is_valid():
                # Replace Question details with those from the selected revision
                form = EditQuestionForm(question,
                    QuestionRevision.objects.get(question=question,
                        revision=revision_form.cleaned_data['revision']))
            else:
                # Make sure we keep a hold of the user's other input, even
                # though they appear to be messing about.
                form = EditQuestionForm(question, latest_revision, request.POST)
        else:
            # Always check modifications against the latest revision
            form = EditQuestionForm(question, latest_revision, request.POST)
            if form.is_valid():
                html = sanitize_html(
                    markdowner.convert(form.cleaned_data['text']))
                if 'preview' in request.POST:
                    # The user submitted to preview the formatted question
                    preview = mark_safe(html)
                elif 'submit' in request.POST:
                    if form.has_changed():
                        edited_at = datetime.datetime.now()
                        tags_changed = (latest_revision.tagnames !=
                                        form.cleaned_data['tags'])
                        tags_updated = False
                        # Update the Question itself
                        updated_fields = {
                            'title': form.cleaned_data['title'],
                            'last_edited_at': edited_at,
                            'last_edited_by': request.user,
                            'last_activity_at': edited_at,
                            'last_activity_by': request.user,
                            'tagnames': form.cleaned_data['tags'],
                            'summary': strip_tags(html)[:180],
                            'html': html,
                        }
                        if ('wiki' in form.cleaned_data and
                            form.cleaned_data['wiki']):
                            updated_fields['wiki'] = True
                            updated_fields['wikified_at'] = edited_at
                        Question.objects.filter(
                            id=question.id).update(**updated_fields)
                        # Update the Question's tag associations
                        if tags_changed:
                            tags_updated = Question.objects.update_tags(
                                question, question.tagnames, request.user)
                        # Create a new revision
                        revision = QuestionRevision(
                            question   = question,
                            title      = form.cleaned_data['title'],
                            author     = request.user,
                            revised_at = edited_at,
                            tagnames   = form.cleaned_data['tags'],
                            text       = form.cleaned_data['text']
                        )
                        if form.cleaned_data['summary']:
                            revision.summary = form.cleaned_data['summary']
                        else:
                            revision.summary = \
                                diff.generate_question_revision_summary(
                                    latest_revision, revision,
                                    ('wiki' in updated_fields))
                        revision.save()
                        # TODO 5 body edits by the author = automatic wiki mode
                        # TODO 4 individual editors = automatic wiki mode
                        # TODO Badges related to Tag usage
                        # TODO Badges related to editing Questions
                    return HttpResponseRedirect(question.get_absolute_url())
    else:
        if 'revision' in request.GET:
            revision_form = RevisionForm(question, latest_revision, request.GET)
            if revision_form.is_valid():
                # Replace Question details with those from the selected revision
                form = EditQuestionForm(question,
                    QuestionRevision.objects.get(question=question,
                        revision=revision_form.cleaned_data['revision']))
        else:
            revision_form = RevisionForm(question, latest_revision)
            form = EditQuestionForm(question, latest_revision)
    if revision_form is None:
        # We're about to redisplay after a POST where we didn't care which
        # revision was selected - make sure the revision the user started from
        # is still selected on redisplay.
        revision_form = RevisionForm(question, latest_revision, request.POST)
    return render_to_response('edit_question.html', {
        'title': u'Edit Question',
        'question': question,
        'revision_form': revision_form,
        'form': form,
        'preview': preview,
    }, context_instance=RequestContext(request))

Example 125

Project: sentry Source File: helper.py
    def _handle_unknown_identity(self, identity):
        """
        Flow is activated upon a user logging in to where an AuthIdentity is
        not present.

        The flow will attempt to answer the following:

        - Is there an existing user with the same email address? Should they be
          merged?

        - Is there an existing user (via authentication) that shoudl be merged?

        - Should I create a new user based on this identity?
        """
        request = self.request
        op = request.POST.get('op')

        if not request.user.is_authenticated():
            # TODO(dcramer): its possible they have multiple accounts and at
            # least one is managed (per the check below)
            try:
                existing_user = auth.find_users(identity['email'], is_active=True)[0]
            except IndexError:
                existing_user = None

            # If they already have an SSO account and the identity provider says
            # the email matches we go ahead and let them merge it. This is the
            # only way to prevent them having duplicate accounts, and because
            # we trust identity providers, its considered safe.
            if existing_user and existing_user.is_managed:
                # we only allow this flow to happen if the existing user has
                # membership, otherwise we short circuit because it might be
                # an attempt to hijack membership of another organization
                has_membership = OrganizationMember.objects.filter(
                    user=existing_user,
                    organization=self.organization,
                ).exists()
                if has_membership:
                    if not auth.login(request, existing_user,
                                      after_2fa=request.build_absolute_uri(),
                                      organization_id=self.organization.id):
                        return HttpResponseRedirect(auth.get_login_redirect(
                            self.request))
                    # assume they've confirmed they want to attach the identity
                    op = 'confirm'
                else:
                    # force them to create a new account
                    existing_user = None

            login_form = self._get_login_form(existing_user)
        elif request.user.is_managed:
            # per the above, try to auto merge if the user was originally an
            # SSO account but is still logged in
            has_membership = OrganizationMember.objects.filter(
                user=request.user,
                organization=self.organization,
            ).exists()
            if has_membership:
                # assume they've confirmed they want to attach the identity
                op = 'confirm'

        if op == 'confirm' and request.user.is_authenticated():
            auth_identity = self._handle_attach_identity(identity)
        elif op == 'newuser':
            auth_identity = self._handle_new_user(identity)
        elif op == 'login' and not request.user.is_authenticated():
            # confirm authentication, login
            op = None
            if login_form.is_valid():
                # This flow is special.  If we are going through a 2FA
                # flow here (login returns False) we want to instruct the
                # system to return upon completion of the 2fa flow to the
                # current URL and continue with the dialog.
                #
                # If there is no 2fa we don't need to do this and can just
                # go on.
                if not auth.login(request, login_form.get_user(),
                                  after_2fa=request.build_absolute_uri(),
                                  organization_id=self.organization.id):
                    return HttpResponseRedirect(auth.get_login_redirect(
                        self.request))
            else:
                auth.log_auth_failure(request, request.POST.get('username'))
        else:
            op = None

        if not op:
            if request.user.is_authenticated():
                return self.respond('sentry/auth-confirm-link.html', {
                    'identity': identity,
                    'existing_user': request.user,
                    'identity_display_name': self._get_display_name(identity),
                    'identity_identifier': self._get_identifier(identity)
                })

            return self.respond('sentry/auth-confirm-identity.html', {
                'existing_user': existing_user,
                'identity': identity,
                'login_form': login_form,
                'identity_display_name': self._get_display_name(identity),
                'identity_identifier': self._get_identifier(identity)
            })

        user = auth_identity.user
        user.backend = settings.AUTHENTICATION_BACKENDS[0]

        # XXX(dcramer): this is repeated from above
        if not auth.login(request, user,
                          after_2fa=request.build_absolute_uri(),
                          organization_id=self.organization.id):
            return HttpResponseRedirect(auth.get_login_redirect(self.request))

        self.clear_session()

        return HttpResponseRedirect(auth.get_login_redirect(self.request))

Example 126

Project: ANALYSE Source File: views.py
@csrf_exempt
def provider_login(request):
    """
    OpenID login endpoint
    """

    # make and validate endpoint
    endpoint = get_xrds_url('login', request)
    if not endpoint:
        return default_render_failure(request, "Invalid OpenID request")

    # initialize store and server
    store = DjangoOpenIDStore()
    server = Server(store, endpoint)

    # first check to see if the request is an OpenID request.
    # If so, the client will have specified an 'openid.mode' as part
    # of the request.
    querydict = dict(request.REQUEST.items())
    error = False
    if 'openid.mode' in request.GET or 'openid.mode' in request.POST:
        # decode request
        try:
            openid_request = server.decodeRequest(querydict)
        except (UntrustedReturnURL, ProtocolError):
            openid_request = None

        if not openid_request:
            return default_render_failure(request, "Invalid OpenID request")

        # don't allow invalid and non-trusted trust roots
        if not validate_trust_root(openid_request):
            return default_render_failure(request, "Invalid OpenID trust root")

        # checkid_immediate not supported, require user interaction
        if openid_request.mode == 'checkid_immediate':
            return provider_respond(server, openid_request,
                                    openid_request.answer(False), {})

        # checkid_setup, so display login page
        # (by falling through to the provider_login at the
        # bottom of this method).
        elif openid_request.mode == 'checkid_setup':
            if openid_request.idSelect():
                # remember request and original path
                request.session['openid_setup'] = {
                    'request': openid_request,
                    'url': request.get_full_path(),
                    'post_params': request.POST,
                }

                # user failed login on previous attempt
                if 'openid_error' in request.session:
                    error = True
                    del request.session['openid_error']

        # OpenID response
        else:
            return provider_respond(server, openid_request,
                                    server.handleRequest(openid_request), {})

    # handle login redirection:  these are also sent to this view function,
    # but are distinguished by lacking the openid mode.  We also know that
    # they are posts, because they come from the popup
    elif request.method == 'POST' and 'openid_setup' in request.session:
        # get OpenID request from session
        openid_setup = request.session['openid_setup']
        openid_request = openid_setup['request']
        openid_request_url = openid_setup['url']
        post_params = openid_setup['post_params']
        # We need to preserve the parameters, and the easiest way to do this is
        # through the URL
        url_post_params = {
            param: post_params[param] for param in post_params if param.startswith('openid')
        }

        encoded_params = urllib.urlencode(url_post_params)

        if '?' not in openid_request_url:
            openid_request_url = openid_request_url + '?' + encoded_params
        else:
            openid_request_url = openid_request_url + '&' + encoded_params

        del request.session['openid_setup']

        # don't allow invalid trust roots
        if not validate_trust_root(openid_request):
            return default_render_failure(request, "Invalid OpenID trust root")

        # check if user with given email exists
        # Failure is redirected to this method (by using the original URL),
        # which will bring up the login dialog.
        email = request.POST.get('email', None)
        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            request.session['openid_error'] = True
            if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
                AUDIT_LOG.warning("OpenID login failed - Unknown user email")
            else:
                msg = "OpenID login failed - Unknown user email: {0}".format(email)
                AUDIT_LOG.warning(msg)
            return HttpResponseRedirect(openid_request_url)

        # attempt to authenticate user (but not actually log them in...)
        # Failure is again redirected to the login dialog.
        username = user.username
        password = request.POST.get('password', None)
        try:
            user = authenticate(username=username, password=password, request=request)
        except RateLimitException:
            AUDIT_LOG.warning('OpenID - Too many failed login attempts.')
            return HttpResponseRedirect(openid_request_url)

        if user is None:
            request.session['openid_error'] = True
            if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
                AUDIT_LOG.warning("OpenID login failed - invalid password")
            else:
                msg = "OpenID login failed - password for {0} is invalid".format(email)
                AUDIT_LOG.warning(msg)
            return HttpResponseRedirect(openid_request_url)

        # authentication succeeded, so fetch user information
        # that was requested
        if user is not None and user.is_active:
            # remove error from session since login succeeded
            if 'openid_error' in request.session:
                del request.session['openid_error']

            if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
                AUDIT_LOG.info("OpenID login success - user.id: {0}".format(user.id))
            else:
                AUDIT_LOG.info("OpenID login success - {0} ({1})".format(
                               user.username, user.email))

            # redirect user to return_to location
            url = endpoint + urlquote(user.username)
            response = openid_request.answer(True, None, url)

            # Note too that this is hardcoded, and not really responding to
            # the extensions that were registered in the first place.
            results = {
                'nickname': user.username,
                'email': user.email,
                'fullname': user.profile.name,
            }

            # the request succeeded:
            return provider_respond(server, openid_request, response, results)

        # the account is not active, so redirect back to the login page:
        request.session['openid_error'] = True
        if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
            AUDIT_LOG.warning("Login failed - Account not active for user.id {0}".format(user.id))
        else:
            msg = "Login failed - Account not active for user {0}".format(username)
            AUDIT_LOG.warning(msg)
        return HttpResponseRedirect(openid_request_url)

    # determine consumer domain if applicable
    return_to = ''
    if 'openid.return_to' in request.REQUEST:
        return_to = request.REQUEST['openid.return_to']
        matches = re.match(r'\w+:\/\/([\w\.-]+)', return_to)
        return_to = matches.group(1)

    # display login page
    response = render_to_response('provider_login.html', {
        'error': error,
        'return_to': return_to
    })

    # add custom XRDS header necessary for discovery process
    response['X-XRDS-Location'] = get_xrds_url('xrds', request)
    return response

Example 127

Project: django-webfaction Source File: views.py
@never_cache
@staff_member_required
def email_changeform(request, id=None):
    if request.method == 'POST':
        # Submitting the form
        form = EmailForm(request.POST)
        change = False
        if form.is_valid():
            f = form.cleaned_data
            server = xmlrpclib.Server('https://api.webfaction.com/')
            session_id, account = server.login(settings.WEBFACTION_USERNAME, settings.WEBFACTION_PASSWORD)
            if id == None:
                # Creating a new email
                if f['create_mailbox']:
                    mailbox_name = generate_mailbox_name(f['email_address'])
                    password = server.create_mailbox(session_id, mailbox_name, f['enable_spam_protection'])['password']
                    targets = generate_targets(mailbox_name, f['redirect'])
                else:
                    targets = generate_targets(None, f['redirect'])
                server.create_email(session_id, f['email_address'], targets, f['autoresponder_on'], f['autoresponder_subject'], f['autoresponder_message'])
                email_msg = "Created email address %s" % f['email_address']
                l = Log(user=request.user, action=email_msg)
                l.save()
                request.user.message_set.create(message=email_msg)
                if f['create_mailbox']:
                    mailbox_msg = "Created mailbox %s" % mailbox_name
                    password_msg = mailbox_msg +" with password %s" % password
                    if settings.WEBFACTION_LOG_PASSWORD:
                        l = Log(user=request.user, action=password_msg)
                    else:
                        l = Log(user=request.user, action=mailbox_msg)
                    l.save()
                    request.user.message_set.create(message=password_msg)
            else:
                # Editing an existing email
                change = True
                messages = []
                update_email = False
                if f['autoresponder_on']!=f['autoresponder_on_prev']:
                    messages.append("Autoresponder Status for %s changed to %s" % (f['email_address'], f['autoresponder_on']))
                    update_email = True
                if f['autoresponder_subject']!=f['autoresponder_subject_prev']:
                    messages.append("Autoresponder Subject for %s changed from '%s' to '%s'" % (f['email_address'], f['autoresponder_subject_prev'], f['autoresponder_subject']))
                    update_email = True
                if f['autoresponder_message']!=f['autoresponder_message_prev']:
                    messages.append("Autoresponder Message for %s changed from '%s' to '%s'" % (f['email_address'], f['autoresponder_message_prev'], f['autoresponder_message']))
                    update_email = True
                if f['redirect']!=f['redirect_prev']:
                    messages.append("Redirect Address for %s changed from '%s' to '%s'" % (f['email_address'], f['redirect_prev'], f['redirect']))
                    update_email = True
                if update_email:
                    mailbox_name = f.get('mailbox_prev', None)
                    targets = generate_targets(mailbox_name, f['redirect'])
                    server.update_email(session_id, f['email_address'], targets, f['autoresponder_on'], f['autoresponder_subject'], f['autoresponder_message'], f['email_address'])
                if f['enable_spam_protection']!=f['enable_spam_protection_prev']:
                    try:
                        server.update_mailbox(session_id, mailbox_name, f['enable_spam_protection'])
                        messages.append("Spam Protection Status for %s changed to %s" % (f['enable_spam_protection'], f['email_address']))
                    except xmlrpclib.Fault: #Probably means this is a redirect only address
                        messages.append("Error. Can only change spam protection status on addresses with their own mailbox")
                for msg in messages:
                    request.user.message_set.create(message=msg)
                    l = Log(user=request.user, action=msg)
                    l.save()
            return HttpResponseRedirect('..')
    else:
        # Blank form
        if id==None: # We are creating
            change = False
            form = EmailForm()
        else: # We are updating
            change = True
            email_accounts = get_email_accounts()
            email_account = [x for x in email_accounts if x['id']==int(id)][0] # Assume only one match
            if email_account.get('mailbox', None):
                # Has a mailbox
                enable_spam_protection = email_account['mailbox']['enable_spam_protection']
            else:
                # Is just a redirect
                enable_spam_protection = False
            if email_account.get('mailbox', False):
                mailbox_name = email_account['mailbox']['mailbox']
            else:
                mailbox_name = ''
            form = EmailForm({
                'email_address': email_account['email_address'],
                'email_address_prev': email_account['email_address'],
                'autoresponder_on': email_account['autoresponder_on'],
                'autoresponder_on_prev': email_account['autoresponder_on'],
                'autoresponder_subject': email_account['autoresponder_subject'],
                'autoresponder_subject_prev': email_account['autoresponder_subject'],
                'autoresponder_message': email_account['autoresponder_message'],
                'autoresponder_message_prev': email_account['autoresponder_message'],
                'enable_spam_protection': enable_spam_protection,
                'enable_spam_protection_prev': enable_spam_protection ,
                'create_mailbox': email_account.get('mailbox', False),
                'mailbox_prev' : mailbox_name,
                'redirect': email_account.get('redirect', ''),
                'redirect_prev': email_account.get('redirect', ''),
            })
            del form.fields['create_mailbox']
    return render_to_response('email_changeform.html', {
        'change': change,
        'form': form,
        },
        RequestContext(request),
    )

Example 128

Project: gnowsys-studio Source File: userpreference.py
def userpreference(request):
	user = str(request.user)
	#url=request.get_full_path
	#print url,'url'
	#re = request.REQUEST.get("next","")
	#print re,"url"
	if request.method=="POST":
		fontcolor = request.POST.get("fontcolor","")
		bgcolor= request.POST.get("bgcolor","")
		colorsave = request.POST.get("colorsave","")
		#re = request.REQUEST.get("next","")
		#print re
		editcolorsave = request.POST.get("editcolorsave","")
		if colorsave:
			attributetype_fc = Attributetype.objects.filter(title="font_color")
			attributetype_bg = Attributetype.objects.filter(title="bg_color")
			if not attributetype_fc:
				newattributetype = Attributetype()
				newattributetype.title = "font_color"
				newattributetype.slug = "font_color"
				newattributetype.dataType = '2'
				newattributetype.applicable_nodetypes = "OB"
				newattributetype.subjecttype_id="7"
				newattributetype.content="text"
				newattributetype.save()
			if not attributetype_bg:
				newattributetype = Attributetype()
				newattributetype.title = "bg_color"
				newattributetype.slug = "bg_color"
				newattributetype.dataType = '2'
				newattributetype.subjecttype_id="7"
				newattributetype.applicable_nodetypes = "OB"
			        newattributetype.content="text"
				newattributetype.save()	
			usergb = Gbobject.objects.filter(title =user+"_preference")
			if not usergb:
				gb=Gbobject()
				gb.title= user+"_preference"
				gb.slug=user+"_loom_preference"
				gb.save()
				gb.objecttypes.add(Objecttype.objects.get(title="Factory_Object"))
				s=Author.objects.get(username=user)
				gb.authors.add(s)
			gb = Gbobject.objects.get(title =user+"_preference")
			print fontcolor,"font"
			if fontcolor:
				atf=Attribute()
				atf.attributetype=Attributetype.objects.get(title="font_color")
				atf.subject=gb
				atf.svalue=fontcolor
				atf.save()
			if bgcolor:
				atb=Attribute()
				atb.attributetype=Attributetype.objects.get(title="bg_color")
				atb.subject=gb
				atb.svalue=bgcolor
				atb.save()
			vars=RequestContext(request,{})
			template="gstudio/userpreference.html"
			return render_to_response(template, vars)
		
		if editcolorsave:
			a_id = Gbobject.objects.get(title=user+"_preference").id
			atypebg_id = Attributetype.objects.get(title="bg_color").id
			atypefc_id = Attributetype.objects.get(title="font_color").id
			allattri = Attribute.objects.all()
			print fontcolor,atypefc_id,"test"
			if bgcolor:
				for each in allattri:
					if each.subject_id == a_id and each.attributetype_id == atypebg_id:
						each.svalue = bgcolor
					        each.save()
			if fontcolor:
				for each in allattri:
					if each.subject_id == a_id and each.attributetype_id == atypefc_id:
						each.svalue = fontcolor
					        each.save()
			vars=RequestContext(request,{})
			template="gstudio/userpreference.html"
			return HttpResponseRedirect("/home/")
			
						
			


	usergbobject = Gbobject.objects.filter(title=user+"_preference")
	if usergbobject:
		usergbobject = Gbobject.objects.get(title=user+"_preference")
		usergbobjectattribute = usergbobject.get_attributes()
		if usergbobjectattribute:
			bgc = ""
			fc = ""
			for key in usergbobjectattribute.keys():
				if key == 'bg_color':
					bgc = str(usergbobjectattribute['bg_color'][0])
				if key == 'font_color':
					fc =  str(usergbobjectattribute['font_color'][0])
			if bgc or fc :
				print "edit"
				vars = RequestContext(request,{'bgcolor':bgc,'fontcolor':fc,'edit':'edit'})
				template="gstudio/userpreference.html"
				return render_to_response(template, vars)
		
					
		
        vars=RequestContext(request,{'show':'show'})
        template="gstudio/userpreference.html"
        return render_to_response(template, vars)

Example 129

Project: django-haystackbrowser Source File: admin.py
    def index(self, request):
        """The view for showing all the results in the Haystack index. Emulates
        the standard Django ChangeList mostly.

        :param request: the current request.
        :type request: WSGIRequest

        :return: A template rendered into an HttpReponse
        """
        if not self.has_change_permission(request, None):
            raise PermissionDenied("Not a superuser")

        page_var = self.get_paginator_var(request)
        form = PreSelectedModelSearchForm(request.GET or None, load_all=False)
        minimum_page = form.fields[page_var].min_value
        # Make sure there are some models indexed
        available_models = model_choices()
        if len(available_models) <= 0:
            raise Search404('No search indexes bound via Haystack')

        # We've not selected any models, so we're going to redirect and select
        # all of them. This will bite me in the ass if someone searches for a string
        # but no models, but I don't know WTF they'd expect to return, anyway.
        # Note that I'm only doing this to sidestep this issue:
        # https://gist.github.com/3766607
        if 'models' not in request.GET.keys():
            # TODO: make this betterererer.
            new_qs = ['&models=%s' % x[0] for x in available_models]
            # if we're in haystack2, we probably want to provide the 'default'
            # connection so that it behaves as if "initial" were in place.
            if form.has_multiple_connections():
                new_qs.append('&connection=' + form.fields['connection'].initial)
            new_qs = ''.join(new_qs)
            existing_query = request.GET.copy()
            if page_var in existing_query:
                existing_query.pop(page_var)
            existing_query[page_var] = minimum_page
            location = '%(path)s?%(existing_qs)s%(new_qs)s' % {
                'existing_qs': existing_query.urlencode(),
                'new_qs': new_qs,
                'path': request.path_info,
            }
            return HttpResponseRedirect(location)

        sqs = form.search()
        cleaned_GET = form.cleaned_data_querydict
        try:
            page_no = int(cleaned_GET.get(PAGE_VAR, minimum_page))
        except ValueError:
            page_no = minimum_page
        results_per_page = self.get_results_per_page(request)
        paginator = Paginator(sqs, results_per_page)
        try:
            page = paginator.page(page_no+1)
        except (InvalidPage, ValueError):
            # paginator.page may raise InvalidPage if we've gone too far
            # meanwhile, casting the querystring parameter may raise ValueError
            # if it's None, or '', or other silly input.
            raise Search404("Invalid page")

        query = request.GET.get(self.get_search_var(request), None)
        connection = request.GET.get('connection', None)
        title = self.model._meta.verbose_name_plural

        wrapped_facets = FacetWrapper(
            sqs.facet_counts(), querydict=form.cleaned_data_querydict.copy())

        context = {
            'results': self.get_wrapped_search_results(page.object_list),
            'pagination_required': page.has_other_pages(),
            # this may be expanded into xrange(*page_range) to copy what
            # the paginator would yield. This prevents 50000+ pages making
            # the page slow to render because of django-debug-toolbar.
            'page_range': (1, paginator.num_pages + 1),
            'page_num': page.number,
            'result_count': paginator.count,
            'opts': self.model._meta,
            'title': force_text(title),
            'root_path': getattr(self.admin_site, 'root_path', None),
            'app_label': self.model._meta.app_label,
            'filtered': True,
            'form': form,
            'form_valid': form.is_valid(),
            'query_string': self.get_current_query_string(request, remove=[page_var]),
            'search_model_count': len(cleaned_GET.getlist('models')),
            'search_facet_count': len(cleaned_GET.getlist('possible_facets')),
            'search_var': self.get_search_var(request),
            'page_var': page_var,
            'facets': wrapped_facets,
            'applied_facets': form.applied_facets(),
            'module_name': force_text(self.model._meta.verbose_name_plural),
            'cl': FakeChangeListForPaginator(request, page, results_per_page, self.model._meta),
            'haystack_version': _haystack_version,
            # Note: the empty Media object isn't specficially required for the
            # standard Django admin, but is apparently a pre-requisite for
            # things like Grappelli.
            # See #1 (https://github.com/kezabelle/django-haystackbrowser/pull/1)
            'media': Media()
        }
        return self.do_render(request=request,
                              template_name='admin/haystackbrowser/result_list.html',
                              context=context)

Example 130

Project: ocf Source File: PolicyDispatcher.py
Function: rule_create
def rule_create(request,table_name=None):

	errors = list()
	formMode = request.POST.get("conditionMode")
	tableName = request.POST.get("table")
	PreviousPriority = request.POST.get("ppriority")
        editing = request.POST.get("editing")
        ruleid = request.POST.get("uuid")
        ruleCondition = request.POST.get("condition")
        ruleDesc = request.POST.get("description")
        ruleError = request.POST.get("error_message")
        ruleType = request.POST.get("type")
        ruleAction = request.POST.get("action")
        ruleValue = request.POST.get("value")
        rulePriority = request.POST.get("priority")
        ruleEnable = request.POST.get("enable")
        previousTable = request.POST.get("hidden_name")
	expertRule = request.POST.get("expertRule")
	newConditions = request.POST.get("conditionID")	
	saved = request.POST.get("saved")

        if rulePriority == 'Last' or rulePriority == '':
                priority = None
        else:
                priority = int(rulePriority)

	if formMode == "easy":
	#Avoid empty fields
#        	if ruleDesc == "":
#                	errors.append("Description Field is empty")
        	if ruleError == "":
                	errors.append("Error Message field is empty")
        	if ruleCondition == "":
                	errors.append("Condition field is empty")
		try:
			str(ruleDesc)
		except:
			errors.append("Only ascii characters are allowed in Description field")
		try:
			str(ruleError)
		except:
			errors.append("Only ascii characters are allowed in Error Message field")
		try:
			str(ruleCondition)
		except:
			errors.append("Only ascii characters are allowed in Conditions")

	

        if request.POST.get("enable") == 'enable':
           enable = True
        else:
           enable = False
	if ruleType == "terminal":
		ruleType = ""
	
	if saved == None:
		saved = False
	#Rule String convertion required
	if formMode == "easy":
		if ruleAction != "None":
			strings = "if " + ruleCondition +  " then " + ruleValue + " " + ruleType  + " do " + ruleAction + " denyMessage " + ruleError + " #" + ruleDesc
		else:
			strings = "if " + ruleCondition +  " then " + ruleValue + " " + ruleType  + " denyMessage " + ruleError + " #" + ruleDesc
	else:
		strings = expertRule
		try:
			str(expertRule)
		except:
			errors.append("Only ascii characters are allowed in a Rule")
	
	try:
		if errors:
                        raise Exception("")
		
		if editing == '1':
			#Editing Rules Case:
                	if previousTable == tableName:
				try:
					RuleTableManager.editRule(strings,enable,priority,PreviousPriority,tableName)
				except Exception as e:
					raise e
                	#else:
				#Moving a rule to a different RuleTable --> this is not possible yet 
                        	#print 'Changing table...'
                        	#RuleTableManager.AddRule(strings,enable,priority,tableName=tableName)
                        	#print 'successful add to ' + tableName
                        	#RuleTableManager.RemoveRule(None,int(PreviousPriority),'oldTableName')
                        	#print 'remove from ' +  previousTable + ' successful'
        	else:
                	RuleTableManager.AddRule(strings,enable,priority,tableName=tableName)

                return HttpResponseRedirect("/policies")		

	except Exception as e:

		errors.append(e)
		errors.insert(0,"The Rule cannot be generated. Reason(s):")#Insterting the main message error in the first position of the table
		priority = RuleTableManager.getPriorityList(tableName)
		priority = RuleTableManager.getPriorityList(tableName)
		
		#if a rule index is the last, insert "LAST" in the rule priority instead the true index.
		try:
			int(rulePriority)
			if int(rulePriority) in priority:
				priority.pop(priority.index(int(rulePriority)))
		except:
			rulePriority = "Last"

		if ruleValue == "accept":
			value2 = ["deny"]
		else:
			value2 = ["accept"]

		if ruleType == "nonterminal":
			type2 = ["terminal"]
		else:
			ruleType = "terminal"
			type2 = ["nonterminal"]


		context = {'user': request.user,
                           'saved':True,
                           'CurrentTable':tableName,
                           'priority':PreviousPriority,
                           'enabled':ruleEnable,
			   'load':'True',
                           'valueS':ruleValue,
                           'valueD':value2,
                           'terminalS':ruleType,
                           'terminalD':type2,
                           'errorMsg':ruleError,
                           'description':ruleDesc,
                           'condition':" " + ruleCondition + " ",
                           'ptable':tableName,
			   'edit': request.POST.get('edit'),
                           'action':ruleAction,
                           'PrioritySel':rulePriority,
                           'priorityList':priority,
                           'allMappings':RuleTableManager.GetResolverMappings(tableName),
                           'ConditionMappings':RuleTableManager.getConditionMappings(),
                           'ActionMappings':RuleTableManager.getActionMappings(),
                           'errors': errors,
                           'rule_uuid':ruleid,}

		return simple.direct_to_template(request,
        	       		template = 'policyEngine/policy_create.html',
                		extra_context = context)

Example 131

Project: django-youtube Source File: views.py
@csrf_exempt
@login_required
def direct_upload(request):
    """
    direct upload method
    starts with uploading video to our server
    then sends the video file to youtube

    param:
        (optional) `only_data`: if set, a json response is returns i.e. {'video_id':'124weg'}

    return:
        if `only_data` set, a json object.
        otherwise redirects to the video display page
    """
    if request.method == "POST":
        try:
            form = YoutubeDirectUploadForm(request.POST, request.FILES)
            # upload the file to our server
            if form.is_valid():
                uploaded_video = form.save()

                # send this file to youtube
                api = Api()
                api.authenticate()
                video_entry = api.upload_direct(uploaded_video.file_on_server.path, "Uploaded video from zuqqa")

                # get data from video entry
                swf_url = video_entry.GetSwfUrl()
                youtube_url = video_entry.id.text

                # getting video_id is tricky, I can only reach the url which
                # contains the video_id.
                # so the only option is to parse the id element
                # https://groups.google.com/forum/?fromgroups=#!topic/youtube-api-gdata/RRl_h4zuKDQ
                url_parts = youtube_url.split("/")
                url_parts.reverse()
                video_id = url_parts[0]

                # save video_id to video instance
                video = Video()
                video.user = request.user
                video.video_id = video_id
                video.title = 'tmp video'
                video.youtube_url = youtube_url
                video.swf_url = swf_url
                video.save()

                # send a signal
                video_created.send(sender=video, video=video)

                # delete the uploaded video instance
                uploaded_video.delete()

                # return the response
                return_only_data = request.GET.get('only_data')
                if return_only_data:
                    return HttpResponse(json.dumps({"video_id": video_id}), content_type="application/json")
                else:
                    # Redirect to the video page or the specified page
                    try:
                        next_url = settings.YOUTUBE_UPLOAD_REDIRECT_URL
                    except AttributeError:
                        next_url = reverse(
                            "django_youtube.views.video", kwargs={"video_id": video_id})

                    return HttpResponseRedirect(next_url)
        except:
            import sys
            logger.error("Unexpected error: %s - %s" % (sys.exc_info()[
                0], sys.exc_info()[1]))
            # @todo: proper error management
            return HttpResponse("error happened")

    form = YoutubeDirectUploadForm()

    if return_only_data:
        return HttpResponse(json.dumps({"error": 500}), content_type="application/json")
    else:
        return render_to_response(
            "django_youtube/direct-upload.html",
            {"form": form},
            context_instance=RequestContext(request)
        )

Example 132

Project: ganetimgr Source File: __init__.py
@login_required
def apply(request):
    user_groups = request.user.groups.all()
    user_networks = Network.objects.filter(groups__in=user_groups).distinct()
    if user_networks:
        InstanceApplicationForm.base_fields["network"] = \
            forms.ModelChoiceField(
                queryset=user_networks, required=False,
                label=_("Network"),
                help_text=_(
                    "Optionally, select a network to connect the virtual"
                    "machine to if you have a special requirement"
                )
        )
    else:
        try:
            del InstanceApplicationForm.base_fields["network"]
        except KeyError:
            pass
    if request.method == "GET":
        # If the user is a superuser, then he does not need to fill the form
        # and review it again, so we can load a template for administrators
        # only which sends the data to the review_application form
        if request.user.is_superuser:
            form = InstanceApplicationReviewForm()
            return render(
                request,
                'apply/admin_apply.html',
                {
                    'form': form
                }
            )
        else:
            form = InstanceApplicationForm()
            org = request.user.get_profile().organization
            if org and settings.BRANDING['SHOW_ORGANIZATION_FORM']:
                form.fields['organization'].initial = org
            if settings.BRANDING['SHOW_ADMINISTRATIVE_FORM']:
                telephone = request.user.get_profile().telephone
                if telephone:
                    form.fields['admin_contact_phone'].initial = telephone
                full_name = '%s %s' % (request.user.first_name, request.user.last_name)
                if full_name:
                    form.fields['admin_contact_name'].initial = full_name
                form.fields['admin_contact_email'].initial = request.user.email
            return render(
                request,
                'apply/apply.html',
                {'form': form},
            )
    else:
        form = InstanceApplicationForm(request.POST)
        if form.is_valid():
            application = form.save(commit=False)
            application.operating_system = form.cleaned_data['operating_system']
            application.applicant = request.user
            application.status = STATUS_PENDING
            net = request.POST.get('network', '')

            # fill user profile with any missing data
            user_profile = request.user.get_profile()
            # organization
            if not user_profile.organization and settings.BRANDING['SHOW_ORGANIZATION_FORM']:
                user_profile.organization = form.cleaned_data['organization']
            # telephone
            if not request.user.get_profile().telephone and settings.BRANDING['SHOW_ADMINISTRATIVE_FORM']:
                user_profile.telephone = form.cleaned_data['admin_contact_phone']
            user_profile.save()
            if net:
                network = Network.objects.get(pk=net)
                application.instance_params = {
                    "cluster": network.cluster.slug,
                    "network": network.link,
                    "mode": network.mode
                }
            application.save()
            fqdn = Site.objects.get_current().domain
            admin_url = "https://%s%s" % (
                fqdn,
                reverse(
                    'application-review',
                    kwargs={"application_id": application.pk}
                )
            )
            mail_body = render_to_string(
                'apply/emails/apply_mail.txt',
                {
                    "application": application,
                    "user": request.user,
                    "url": admin_url
                }
            )
            mail_managers(
                "New instance request by %s: %s" % (
                    request.user, application.hostname
                ),
                mail_body
            )
            messages.add_message(
                request,
                messages.INFO,
                _(
                    "Your request has been filed with id #%d and"
                    " will be processed shortly."
                ) % application.id
            )
            return HttpResponseRedirect(reverse("user-instances"))
        else:
            return render(
                request,
                'apply/apply.html',
                {'form': form}
            )

Example 133

Project: lava-server Source File: views.py
def image_chart_filter_form(request, bread_crumb_trail, chart_instance=None,
                            instance=None):

    if instance:
        chart_instance = instance.image_chart

    if request.method == 'POST':

        form = ImageChartFilterForm(request.user, request.POST,
                                    instance=instance)

        if form.is_valid():

            chart_filter = form.save()

            if not chart_filter.is_all_tests_included:
                if chart_filter.image_chart.chart_type != 'measurement':

                    image_chart_tests = Test.objects.filter(
                        imagecharttest__image_chart_filter=chart_filter).order_by('id')

                    tests = form.cleaned_data['image_chart_tests']

                    for test in tests:
                        if test in image_chart_tests:
                            chart_test = ImageChartTest.objects.get(
                                image_chart_filter=chart_filter, test=test)
                            chart_test.save()
                        else:
                            chart_test = ImageChartTest()
                            chart_test.image_chart_filter = chart_filter
                            chart_test.test = test
                            chart_test.save()

                    for chart_test in image_chart_tests:
                        if chart_test not in tests:
                            ImageChartTest.objects.get(
                                image_chart_filter=chart_filter,
                                test=chart_test).delete()

                else:

                    image_chart_test_cases = TestCase.objects.filter(
                        imagecharttestcase__image_chart_filter=chart_filter
                    ).order_by('id')

                    test_cases = form.cleaned_data['image_chart_test_cases']

                    for test_case in test_cases:
                        if test_case in image_chart_test_cases:
                            chart_test_case = ImageChartTestCase.objects.get(
                                image_chart_filter=chart_filter,
                                test_case=test_case)
                            chart_test_case.save()
                        else:
                            chart_test_case = ImageChartTestCase()
                            chart_test_case.image_chart_filter = chart_filter
                            chart_test_case.test_case = test_case
                            chart_test_case.save()

                    for chart_test_case in image_chart_test_cases:
                        if chart_test_case not in test_cases:
                            ImageChartTestCase.objects.get(
                                image_chart_filter=chart_filter,
                                test_case=chart_test_case).delete()

            return HttpResponseRedirect(
                chart_filter.get_absolute_url())

    else:
        form = ImageChartFilterForm(request.user, instance=instance,
                                    initial={'image_chart': chart_instance})
    template = loader.get_template('dashboard_app/image_chart_filter_form.html')
    return HttpResponse(template.render(
        {
            'bread_crumb_trail': bread_crumb_trail,
            'image_chart': chart_instance,
            'instance': instance,
            'form': form,
        }, request=request))

Example 134

Project: ocf Source File: views.py
def confirm_requests(request):
    """Confirm the approval of the permission requests."""
    
    approved_req_ids = request.session.setdefault("approved_req_ids", [])
    delegatable_req_ids = request.session.setdefault("delegatable_req_ids", [])
    denied_req_ids = request.session.setdefault("denied_req_ids", [])

    approved_reqs = []
    for req_id in approved_req_ids:
        req = get_object_or_404(PermissionRequest, id=req_id)
        delegatable = req_id in delegatable_req_ids
        approved_reqs.append((req, delegatable))
    
    denied_reqs = []
    for req_id in denied_req_ids:
        denied_reqs.append(
            get_object_or_404(PermissionRequest, id=req_id))

    if request.method == "POST":
        # check if confirmed and then do actions.
        if request.POST.get("post", "no") == "yes":
            for req in denied_reqs:
                req.deny()
#                DatedMessage.objects.post_message_to_user(
#                    "Request for permission %s for object %s denied."
#                    % (req.requested_permission.permission.name,
#                       req.requested_permission.target),
#                    user=req.requesting_user,
#                    sender=req.permission_owner,
#                    msg_type=DatedMessage.TYPE_WARNING)

                post_message = "Request for %s denied." % str(req.requested_permission.target).capitalize()
                if req.requested_permission.permission.name == "can_create_project":
                    # Removes "* Project name: "
                    try:
                        project_name = req.message.split("||")[0].strip()[16:]
                        post_message = "Request for project %s creation denied." % project_name

                        # Notify requesting user
                        try:
                            send_mail(
                                     settings.EMAIL_SUBJECT_PREFIX + "Denied project request for '%s'" % (project_name),
                                     "Your request for the creation of project '%s' has been denied.\n\n\nYou may want to get in contact with the Island Manager for further details." % project_name, 
                                     from_email = settings.DEFAULT_FROM_EMAIL,
                                     recipient_list = [req.requesting_user.email],
                             )
                        except Exception as e:
                            print "[WARNING] User e-mail notification could not be sent. Details: %s" % str(e)

                    except:
                        pass
                # -------------------------------------------
                # It is not about permission granting anymore
                # -------------------------------------------
                # Notify requesting user
                DatedMessage.objects.post_message_to_user(
                    post_message,
                    user = req.requesting_user,
                    sender = req.permission_owner,
                    msg_type = DatedMessage.TYPE_WARNING)

                # Notify user with permission (e.g. root)
                DatedMessage.objects.post_message_to_user(
                    post_message,
                    user = request.user,
                    sender = req.permission_owner,
                    msg_type = DatedMessage.TYPE_WARNING)

            for req, delegate in approved_reqs:
                # --------------------------------------------------------
                # Do NOT grant permission to create projects in the future
                # --------------------------------------------------------
#                req.allow(can_delegate=delegate)
                req.deny()
#                DatedMessage.objects.post_message_to_user(
#                    "Request for permission %s for object %s approved."
#                    % (req.requested_permission.permission.name,
#                       req.requested_permission.target),
#                    user=req.requesting_user,
#                    sender=req.permission_owner,
#                    msg_type=DatedMessage.TYPE_SUCCESS)

                post_message = "Request for %s approved." % str(req.requested_permission.target).capitalize()
                permission_user_post = post_message
                requesting_user_post = post_message
                email_header = post_message
                email_body = "%s." % post_message
                message_type = DatedMessage.TYPE_SUCCESS
                # ---------------------------------------
                # Project will be created in a direct way
                # ---------------------------------------
                if req.requested_permission.permission.name == "can_create_project":
                    project_name = ""
                    try:
                        project = Project()
                        project.uuid = uuid.uuid4()
                        message = req.message.split("||")
                        # Removes "* Project name: "
                        project.name = message[0].strip()[16:]
                        project_name = project.name
                        # Removes "* Project description: "
                        project.description = message[3].strip()[23:]
                        post_message = "Successfully created project %s" % project.name
                        project.save()
                        create_project_roles(project, req.requesting_user)
                        project.save()
                        email_header = "Approved project request for '%s'" % project_name
                        email_body = "Your request for the creation of project '%s' has been approved." % project_name
                    except Exception as e:
                        # Any error when creating a project results into:
                            # 1. Denying the petition
                            # 2. Notifying user in their Expedient
                            # 3. Notifying user via e-mail
                        post_message = "Project '%s' could not be created" % project_name
                        permission_user_post = post_message
                        requesting_user_post = post_message

                        # Handle exception text for user
                        if "duplicate entry" in str(e).lower():
                            email_body = "There is already a project with name '%s'. Try using a different name" % project_name
                            requesting_user_post += ". Details: project '%s' already exists" % project_name
                        else:
                            email_body = "There might have been a problem when interpreting the information for project '%s'" % str(project_name)
                        requesting_user_post += ". Contact your Island Manager for further details"

                        # Handle exception text for admin
                        if "Details" not in post_message:
                            permission_user_post = "%s. Details: %s" % (post_message, str(e))

                        message_type = DatedMessage.TYPE_ERROR
                        # Email for requesting user
                        email_header = "Denied project request for '%s'" % project_name
                        email_body = "Your request for the creation of project '%s' has been denied because of the following causes:\n\n%s\n\n\nYou may want to get in contact with the Island Manager for further details." % (project_name, email_body)

                    # Notify requesting user
                    DatedMessage.objects.post_message_to_user(
                        requesting_user_post,
                        user = req.requesting_user,
                        sender = req.permission_owner,
                        msg_type = message_type)

                    try:
                        send_mail(
                                 settings.EMAIL_SUBJECT_PREFIX + email_header,
                                 email_body,
                                 from_email = settings.DEFAULT_FROM_EMAIL,
                                 recipient_list = [req.requesting_user.email],
                         )
                    except Exception as e:
                        print "[WARNING] User e-mail notification could not be sent. Details: %s" % str(e)

                    # Notify user with permission (e.g. root)
                    DatedMessage.objects.post_message_to_user(
                        permission_user_post,
                        user = request.user,
                        sender = req.permission_owner,
                        msg_type = message_type)
                    

        # After this post we will be done with all this information
        del request.session["approved_req_ids"]
        del request.session["delegatable_req_ids"]
        del request.session["denied_req_ids"]
        
        return HttpResponseRedirect(reverse("home"))
    
    else:
        return direct_to_template(
            request=request,
            template=TEMPLATE_PATH+"/confirm_requests.html",
            extra_context={
                "approved_reqs": approved_reqs,
                "denied_reqs": denied_reqs,
            }
        )

Example 135

Project: django-publications Source File: import_bibtex.py
def import_bibtex(request):
	if request.method == 'POST':
		# try to parse BibTex
		bib = parse(request.POST['bibliography'])

		# container for error messages
		errors = {}

		# publication types
		types = Type.objects.all()

		# check for errors
		if not bib:
			if not request.POST['bibliography']:
				errors['bibliography'] = 'This field is required.'

		if not errors:
			publications = []

			# try adding publications
			for entry in bib:
				if 'title' in entry and \
				   'author' in entry and \
				   'year' in entry:
					# parse authors
					authors = entry['author'].split(' and ')
					for i in range(len(authors)):
						author = authors[i].split(',')
						author = [author[-1]] + author[:-1]
						authors[i] = ' '.join(author)
					authors = ', '.join(authors)

					# add missing keys
					keys = [
						'journal',
						'booktitle',
						'publisher',
						'institution',
						'url',
						'doi',
						'isbn',
						'keywords',
						'note',
						'abstract',
						'month']

					for key in keys:
						if not key in entry:
							entry[key] = ''

					# map integer fields to integers
					entry['month'] = MONTHS.get(entry['month'].lower(), 0)

					entry['volume'] = entry.get('volume', None)
					entry['number'] = entry.get('number', None)

					if isinstance(entry['volume'], six.text_type):
						entry['volume'] = int(re.sub('[^0-9]', '', entry['volume']))
					if isinstance(entry['number'], six.text_type):
						entry['number'] = int(re.sub('[^0-9]', '', entry['number']))

					# remove whitespace characters (likely due to line breaks)
					entry['url'] = re.sub(r'\s', '', entry['url'])

					# determine type
					type_id = None

					for t in types:
						if entry['type'] in t.bibtex_type_list:
							type_id = t.id
							break

					if type_id is None:
						errors['bibliography'] = 'Type "' + entry['type'] + '" unknown.'
						break

					# add publication
					publications.append(Publication(
						type_id=type_id,
						citekey=entry['key'],
						title=entry['title'],
						authors=authors,
						year=entry['year'],
						month=entry['month'],
						journal=entry['journal'],
						book_title=entry['booktitle'],
						publisher=entry['publisher'],
						institution=entry['institution'],
						volume=entry['volume'],
						number=entry['number'],
						note=entry['note'],
						url=entry['url'],
						doi=entry['doi'],
						isbn=entry['isbn'],
						external=False,
						abstract=entry['abstract'],
						keywords=entry['keywords']))
				else:
					errors['bibliography'] = 'Make sure that the keys title, author and year are present.'
					break

		if not errors and not publications:
			errors['bibliography'] = 'No valid BibTex entries found.'

		if errors:
			# some error occurred
			return render(
				request,
				'admin/publications/import_bibtex.html', {
					'errors': errors,
					'title': 'Import BibTex',
					'types': Type.objects.all(),
					'request': request})
		else:
			try:
				# save publications
				for publication in publications:
					publication.save()
			except:
				msg = 'Some error occured during saving of publications.'
			else:
				if len(publications) > 1:
					msg = 'Successfully added ' + str(len(publications)) + ' publications.'
				else:
					msg = 'Successfully added ' + str(len(publications)) + ' publication.'

			# show message
			messages.info(request, msg)

			# redirect to publication listing
			return HttpResponseRedirect('../')
	else:
		return render(
			request,
			'admin/publications/import_bibtex.html', {
				'title': 'Import BibTex',
				'types': Type.objects.all(),
				'request': request})

Example 136

Project: ganetimgr Source File: clusters.py
@login_required
@csrf_exempt
def reinstalldestreview(request, application_hash, action_id):
    action_id = int(action_id)
    instance = None
    if action_id not in [1, 2, 3, 4]:
        return HttpResponseRedirect(reverse('user-instances'))
    # Normalize before trying anything with it.
    activation_key = application_hash.lower()
    try:
        action = InstanceAction.objects.get(
            activation_key=activation_key,
            action=action_id
        )
    except InstanceAction.DoesNotExist:
        activated = True
        return render(
            request,
            'instances/verify_action.html',
            {
                'action': action_id,
                'activated': activated,
                'instance': instance,
                'hash': application_hash
            }
        )
    if action_id == 4:
        instance_action = InstanceAction.objects.activate_request(
            application_hash
        )
        user = User.objects.get(username=request.user)
        user.email = action.action_value
        user.save()
        messages.add_message(
            request,
            messages.INFO,
            _('Mail changed succesfully.')
        )
        return HttpResponseRedirect(reverse('profile'))
    instance = action.instance
    cluster = action.cluster
    if not request.user.userprofile.is_owner(cluster.get_instance(instance)):
        action = ''
        if action_id is 1:
            action = 'reinstall'
        elif action_id is 3:
            action = 'rename'
        elif action_id is 2:
            action = 'destroy'
        auditlog_entry(request, 'Unauthorized ' + action + ' attempt',
                       instance, cluster.slug, True, False)
        mail_unauthorized_action(
            action, instance, request.user.userprofile.user.username
        )
        raise PermissionDenied
    action_value = action.action_value
    activated = False
    try:
        instance_object = Instance.objects.get(name=instance)
    except:
        # This should occur only when user changes email
        pass
    if action.activation_key_expired():
        activated = True
    if request.method == 'POST':
        if not activated:
            instance_action = InstanceAction.objects.activate_request(
                application_hash
            )
            if not instance_action:
                return render(
                    request,
                    'instances/verify_action.html',
                    {
                        'action': action_id,
                        'activated': activated,
                        'instance': instance,
                        'hash': application_hash
                    }
                )
            if action_id in [1, 2, 3]:
                auditlog = auditlog_entry(request, "", instance, cluster.slug, save=False)
            if action_id == 1:
                auditlog.update(action="Reinstall")
                jobid = cluster.reinstall_instance(instance, instance_action)
                # in case there is no selected os
                if jobid:
                    auditlog.update(job_id=jobid)
                else:
                    return HttpResponseServerError()
            if action_id == 2:
                auditlog.update(action="Destroy")
                jobid = cluster.destroy_instance(instance)
                auditlog.update(job_id=jobid)
            if action_id == 3:
                # As rename causes cluster lock we perform some cache
                # engineering on the cluster instances,
                # nodes and the users cache
                refresh_cluster_cache(cluster, instance)
                auditlog.update(action="Rename to %s" % action_value)
                jobid = cluster.rename_instance(instance, action_value)
                auditlog.update(job_id=jobid)
            activated = True
            return HttpResponseRedirect(reverse('user-instances'))
        else:
            return render(
                request,
                'instances/verify_action.html',
                {
                    'action': action_id,
                    'activated': activated,
                    'instance': instance,
                    'instance_object': instance_object,
                    'hash': application_hash
                }
            )
    elif request.method == 'GET':
        return render(
            request,
            'instances/verify_action.html',
            {
                'instance': instance,
                'instance_object': instance_object,
                'action': action_id,
                'action_value': action_value,
                'cluster': cluster,
                'activated': activated,
                'hash': application_hash
            }
        )
    else:
        return HttpResponseRedirect(reverse('user-instances'))

Example 137

Project: django-calendar Source File: events.py
Function: edit
@login_required
def edit(request, event_slug, cal_type="5", template_name=None, next=None):
    """ edit a withcal """
    (event, err) = fetch_from_url(request, event_slug)
    if err:
        return err
    request_user = request.user
    if request.method == 'POST':
        f = BaseEventForm(request.POST)
        if f.is_valid():
            event.start = f.cleaned_data['start_time']
            event.end = f.cleaned_data['end_time']
            event.allDay = f.cleaned_data['check_whole_day']
            event.category = f.cleaned_data['category']
            event.priority = f.cleaned_data['priority']
            event.end_recurring_period = f.cleaned_data['end_recurring_period']
            recursion_frequency = f.cleaned_data['recursion_frequency']
            recursion_count = f.cleaned_data['recursion_count']
            recursion_byweekday = f.cleaned_data['recursion_byweekday']
            recursion_bymonthday = f.cleaned_data['recursion_bymonthday']

            #first we have to check if the current event is recurring, if so we:
            #the recursion parameters are required
            if f.cleaned_data['add_recursion']:
                recursion_params = recursion_count + recursion_byweekday + recursion_bymonthday
                if event.recursion is None:
                    recursion = Recursion(frequency=recursion_frequency, params=recursion_params)
                    recursion.save()
                    event.recursion = recursion
                else :
                    recursion = event.recursion
                    recursion.frequency = recursion_frequency
                    recursion.params = recursion_params
                    recursion.save()
            else :
                if event.recursion is not None:
                    recursion = event.recursion
                    event.recursion = None
                    event.save()
                    recursion.delete()

            event.save()
            #notify all concerned users by the object by the new comment
            #users_tonotify = ToNotify.objects.filter(event=event).exclude(user=request_user)
            #for user_tonotify in users_tonotify:
                #user = user_tonotify.user
                #notification.send([user], "cal_updated", {'event': event, 'user':request_user,})

            if not request.is_ajax():
                return HttpResponseRedirect(reverse(next, args=(event.get_url(),)))
            response = ({'success':'True'})
        else:
            response = errors_as_json(f)
        if request.is_ajax():
            json = simplejson.dumps(response, ensure_ascii=False)
            return HttpResponse(json, mimetype="application/json")
    else:

        if event.recursion:
            params = event.recursion.get_params()
            count = ''
            byweekday = ''
            bymonthday = ''
            if 'count' in params:
                count = params['count']
            if 'byweekday' in params:
                try:
                    byweekday = [int(params['byweekday'])]
                except:
                    byweekday = params['byweekday']
            if 'bymonthday' in params:
                try:
                    bymonthday = [int(params['bymonthday'])]
                except:
                    bymonthday = params['bymonthday']
            f = BaseEventForm({'start_date': event.start.date(),
                      'start_time': event.start.time().strftime("%I:%M %p"),
                      'end_date': event.end.date(),
                      'end_time': event.end.time().strftime("%I:%M %p"),
                      'category': event.cal_category,
                      'priority': event.priority,
                      'check_whole_day': event.allDay,
                      'end_recurring_period': event.end_recurring_period,
                      'recursion_frequency' : event.recursion.frequency,
                      'add_recursion': True,
                      'recursion_count': count,
                      'recursion_byweekday':byweekday,
                      'recursion_bymonthday':bymonthday,
                      })
        else :
            f = BaseEventForm({'start_date': event.start.date(),
                      'start_time': event.start.time().strftime("%I:%M %p"),
                      'end_date': event.end.date(),
                      'end_time': event.end.time().strftime("%I:%M %p"),
                      'check_whole_day': event.allDay,
                      'category': event.category,
                      'priority': event.priority,
                      'end_recurring_period': event.end_recurring_period,
                      })
    c = RequestContext(request, {'form': f,
                                 'action': event.get_edit_url(),
                                 'event': event,
                                 })

    return render_to_response(template_name, c)

Example 138

Project: courtlistener Source File: views.py
@sensitive_post_parameters('password1', 'password2')
@sensitive_variables('salt', 'activation_key', 'email_body')
@check_honeypot(field_name='skip_me_if_alive')
@never_cache
def register(request):
    """allow only an anonymous user to register"""
    redirect_to = request.GET.get('next', '')
    if 'sign-in' in redirect_to:
        # thus, we don't redirect people back to the sign-in form
        redirect_to = ''

    # security checks:
    # Light security check -- make sure redirect_to isn't garbage.
    if not redirect_to or ' ' in redirect_to:
        redirect_to = settings.LOGIN_REDIRECT_URL

    # Heavier security check -- redirects to http://example.com should
    # not be allowed, but things like /view/?param=http://example.com
    # should be allowed. This regex checks if there is a '//' *before* a
    # question mark.
    elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
        redirect_to = settings.LOGIN_REDIRECT_URL

    if request.user.is_anonymous():
        if request.method == 'POST':
            try:
                stub_account = User.objects.filter(
                    profile__stub_account=True,
                ).get(
                    email__iexact=request.POST.get('email'),
                )
            except User.DoesNotExist:
                stub_account = False

            if stub_account:
                form = UserCreationFormExtended(
                    request.POST,
                    instance=stub_account
                )
            else:
                form = UserCreationFormExtended(request.POST)

            if form.is_valid():
                cd = form.cleaned_data
                if not stub_account:
                    # make a new user that is active, but has not confirmed
                    # their email address
                    user = User.objects.create_user(
                        cd['username'],
                        cd['email'],
                        cd['password1']
                    )
                    up = UserProfile(user=user)
                else:
                    # Upgrade the stub account to make it a regular account.
                    user = stub_account
                    user.set_password(cd['password1'])
                    user.username = cd['username']
                    up = stub_account.profile
                    up.stub_account = False

                if cd['first_name']:
                    user.first_name = cd['first_name']
                if cd['last_name']:
                    user.last_name = cd['last_name']
                user.save()

                # Build and assign the activation key
                salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
                up.activation_key = hashlib.sha1(
                    salt + user.username).hexdigest()
                up.key_expires = now() + timedelta(days=5)
                up.save()

                email = emails['confirm_your_new_account']
                send_mail(
                    email['subject'],
                    email['body'] % (user.username, up.activation_key),
                    email['from'],
                    [user.email]
                )
                email = emails['new_account_created']
                send_mail(
                    email['subject'] % up.user.username,
                    email['body'] % (
                        up.user.get_full_name() or "Not provided",
                        up.user.email
                    ),
                    email['from'],
                    email['to'],
                )
                tally_stat('user.created')
                return HttpResponseRedirect(reverse('register_success') +
                                            '?next=%s' % redirect_to)
        else:
            form = UserCreationFormExtended()
        return render_to_response("register/register.html",
                                  {'form': form, 'private': False},
                                  RequestContext(request))
    else:
        # The user is already logged in. Direct them to their settings page as
        # a logical fallback
        return HttpResponseRedirect(reverse('view_settings'))

Example 139

Project: kitsune Source File: views.py
@markup_json
@handle_es_errors(_es_down_template)
@mobile_template('search/{mobile/}results.html')
def simple_search(request, template=None):
    """Elasticsearch-specific simple search view.

    This view is for end user searching of the Knowledge Base and
    Support Forum. Filtering options are limited to:

    * product (`product=firefox`, for example, for only Firefox results)
    * docuement type (`w=2`, for example, for Support Forum questions only)

    """

    to_json = JSONRenderer().render

    # 1. Prep request.
    # Redirect to old Advanced Search URLs (?a={1,2}) to the new URL.
    if request.GET.get('a') in ['1', '2']:
        new_url = reverse('search.advanced') + '?' + request.GET.urlencode()
        return HttpResponseRedirect(new_url)

    # 2. Build form.
    search_form = SimpleSearchForm(request.GET, auto_id=False)

    # 3. Validate request.
    if not search_form.is_valid():
        if request.IS_JSON:
            return HttpResponse(
                json.dumps({'error': _('Invalid search data.')}),
                content_type=request.CONTENT_TYPE,
                status=400)

        t = template if request.MOBILE else 'search/form.html'
        return cache_control(
            render(request, t, {
                'advanced': False,
                'request': request,
                'search_form': search_form}),
            settings.SEARCH_CACHE_PERIOD)

    # 4. Generate search.
    cleaned = search_form.cleaned_data

    # On mobile, we default to just wiki results.
    if request.MOBILE and cleaned['w'] == constants.WHERE_BASIC:
        cleaned['w'] = constants.WHERE_WIKI

    language = locale_or_default(cleaned['language'] or request.LANGUAGE_CODE)
    lang_name = settings.LANGUAGES_DICT.get(language.lower()) or ''

    searcher = generate_simple_search(search_form, language, with_highlights=True)
    searcher = searcher[:settings.SEARCH_MAX_RESULTS]

    # 5. Generate output.
    pages = paginate(request, searcher, settings.SEARCH_RESULTS_PER_PAGE)

    if pages.paginator.count == 0:
        fallback_results = _fallback_results(language, cleaned['product'])
        results = []

    else:
        fallback_results = None
        results = build_results_list(pages, request.IS_JSON)

    product = Product.objects.filter(slug__in=cleaned['product'])
    if product:
        product_titles = [pgettext('DB: products.Product.title', p.title) for p in product]
    else:
        product_titles = [_('All Products')]

    # FIXME: This is probably bad l10n.
    product_titles = ', '.join(product_titles)

    data = {
        'num_results': pages.paginator.count,
        'results': results,
        'fallback_results': fallback_results,
        'product_titles': product_titles,
        'q': cleaned['q'],
        'w': cleaned['w'],
        'lang_name': lang_name,
        'products': Product.objects.filter(visible=True)}

    if request.IS_JSON:
        data['total'] = len(data['results'])
        data['products'] = [{'slug': p.slug, 'title': p.title}
                            for p in data['products']]

        if product:
            data['product'] = product[0].slug

        pages = Paginator(pages)
        data['pagination'] = dict(
            number=pages.pager.number,
            num_pages=pages.pager.paginator.num_pages,
            has_next=pages.pager.has_next(),
            has_previous=pages.pager.has_previous(),
            max=pages.max,
            span=pages.span,
            dotted_upper=pages.pager.dotted_upper,
            dotted_lower=pages.pager.dotted_lower,
            page_range=pages.pager.page_range,
            url=pages.pager.url,
        )
        if not results:
            data['message'] = _('No pages matched the search criteria')

        json_data = to_json(data)
        if request.JSON_CALLBACK:
            json_data = request.JSON_CALLBACK + '(' + json_data + ');'
        return HttpResponse(json_data, content_type=request.CONTENT_TYPE)

    data.update({
        'product': product,
        'pages': pages,
        'search_form': search_form,
        'advanced': False,
    })
    resp = cache_control(render(request, template, data), settings.SEARCH_CACHE_PERIOD)
    resp.set_cookie(settings.LAST_SEARCH_COOKIE, urlquote(cleaned['q']),
                    max_age=3600, secure=False, httponly=False)
    return resp

Example 140

Project: synnefo Source File: im.py
@transaction.commit_on_success
@require_http_methods(["GET", "POST"])
@cookie_fix
def signup(request, template_name='im/signup.html', on_success='index',
           extra_context=None, activation_backend=None):
    """
    Allows a user to create a local account.

    In case of GET request renders a form for entering the user information.
    In case of POST handles the signup.

    The user activation will be delegated to the backend specified by the
    ``activation_backend`` keyword argument if present, otherwise to the
    ``astakos.im.activation_backends.InvitationBackend`` if
    settings.ASTAKOS_INVITATIONS_ENABLED is True or
    ``astakos.im.activation_backends.SimpleBackend`` if not (see
    activation_backends);

    Upon successful user creation, if ``next`` url parameter is present the
    user is redirected there otherwise renders the same page with a success
    message.

    On unsuccessful creation, renders ``template_name`` with an error message.

    **Arguments**

    ``template_name``
        A custom template to render. This is optional;
        if not specified, this will default to ``im/signup.html``.

    ``extra_context``
        An dictionary of variables to add to the template context.

    ``on_success``
        Resolvable view name to redirect on registration success.

    **Template:**

    im/signup.html or ``template_name`` keyword argument.
    """
    extra_context = extra_context or {}
    if request.user.is_authenticated():
        logger.info("%s already signed in, redirect to index",
                    request.user.log_display)
        return HttpResponseRedirect(reverse('index'))

    provider = get_query(request).get('provider', 'local')
    try:
        auth.get_provider(provider)
    except auth.InvalidProvider, e:
        messages.error(request, e.message)
        return HttpResponseRedirect(reverse("signup"))

    if not auth.get_provider(provider).get_create_policy:
        logger.error("%s provider not available for signup", provider)
        raise PermissionDenied

    instance = None

    # user registered using third party provider
    third_party_token = request.REQUEST.get('third_party_token', None)
    unverified = None
    pending = None
    if third_party_token:
        # retreive third party entry. This was created right after the initial
        # third party provider handshake.
        pending = get_object_or_404(PendingThirdPartyUser,
                                    token=third_party_token)

        provider = pending.provider

        # clone third party instance into the corresponding AstakosUser
        instance = pending.get_user_instance()
        get_unverified = AstakosUserAuthProvider.objects.unverified

        # check existing unverified entries
        unverified = get_unverified(pending.provider,
                                    identifier=pending.third_party_identifier)

        get_verified = AstakosUserAuthProvider.objects.verified
        verified = get_verified(pending.provider,
                                identifier=pending.third_party_identifier)
        if verified:
            # an existing verified user already exists for the third party
            # identifier
            pending.delete()
            raise Http404

        if unverified and request.method == 'GET':
            messages.warning(request, unverified.get_pending_registration_msg)

    # prepare activation backend based on current request
    if not activation_backend:
        activation_backend = activation_backends.get_backend()

    form_kwargs = {'instance': instance, 'request': request}
    if third_party_token:
        form_kwargs['third_party_token'] = third_party_token

    if pending:
        form_kwargs['initial'] = {
            'first_name': pending.first_name,
            'last_name': pending.last_name,
            'email': pending.email
        }

    form = activation_backend.get_signup_form(
        provider, None, **form_kwargs)

    if request.method == 'POST':
        form = activation_backend.get_signup_form(
            provider,
            request.POST,
            **form_kwargs)

        if form.is_valid():
            user = form.create_user()
            result = activation_backend.handle_registration(user)
            if result.status == \
                    activation_backend.Result.PENDING_MODERATION:
                # user should be warned that his account is not active yet
                status = messages.WARNING
            else:
                status = messages.SUCCESS
            message = result.message
            activation_backend.send_result_notifications(result, user)

            # commit user entry
            transaction.commit()

            if user and user.is_active:
                # activation backend directly activated the user
                # log him in
                next = request.POST.get('next', '')
                response = prepare_response(request, user, next=next)
                return response

            messages.add_message(request, status, message)
            return HttpResponseRedirect(reverse(on_success))

    ldap_login_form = None
    if 'ldap' in settings.IM_MODULES:
        ldap_login_form = LDAPLoginForm(request)

    return render_response(
        template_name,
        login_form=ldap_login_form,
        signup_form=form,
        third_party_token=third_party_token,
        provider=provider,
        context_instance=get_context(request, extra_context))

Example 141

Project: remo Source File: decorators.py
def permission_check(permissions=[], group=None,
                     filter_field=None, owner_field=None, model=None):
    """Check if a user is logged in and has the required permissions.

    1. If user is not logged in then redirect to 'main', display login
    message

    2. If user logged in and len(/permissions/) == 0, group != None
    and /filter_field/ == None then allow access

    3. If user logged in and len(/permissions/) > 0, group != None
    and /filter_field/ == None then allow access only if user has all
    permissions

    4. If user logged in and len(/permissions/) > 0 and group == None
    and /filter_field/ != None then allow access if user has all
    permissions or there is an object in /model/ with attributes
    /filter_field/ == kwargs[filter_field] and /owner_field/ ==
    request.user.

    5. If user logged in and len(permissions) == 0 and group == None
    and filter_field != None then allow access only if there is an
    object in /model/ with attributes /filter_field/ ==
    kwargs[filter_field] and /owner_field/ == request.user.

    6. If user logged in and len(permissions) == 0 and group != None
    and /filter_field/ == None then allow access if user is member of Group.

    7. If user logged in and len(/permissions/) > 0 and group != None
    and /filter_field/ != None then allow access if user has all
    permissions or is part of group or there is an object in /model/
    with attributes /filter_field/ == kwargs[filter_field] and
    /owner_field/ == request.user.

    8. If user logged in and len(permissions) == 0 and group != None
    and filter_field != None then allow access only if user is part of
    group or there is an object in /model/ with attributes
    /filter_field/ == kwargs[filter_field] and /owner_field/ ==
    request.user.

    """

    def decorator(func):

        @wraps(func)
        def wrapper(request, *args, **kwargs):

            def _check_if_user_has_permissions():
                if (((permissions and request.user.has_perms(permissions)) or
                     request.user.groups.filter(name=group).exists())):
                    return True
                return False

            def _check_if_user_owns_page():
                if owner_field and model:
                    if not kwargs.get(filter_field):
                        return True

                    obj = get_object_or_none(model, **{filter_field:
                                                       kwargs[filter_field]})
                    if obj and getattr(obj, owner_field) == request.user:
                        return True
                return False

            if request.user.is_authenticated():
                if (((not permissions and not group and not filter_field) or
                     request.user.is_superuser or
                     _check_if_user_owns_page() or
                     _check_if_user_has_permissions())):
                    return func(request, *args, **kwargs)
                else:
                    messages.error(request, 'Permission denied.')
                    return redirect('main')
            else:
                messages.warning(request, 'Please login.')
                next_url = urlparams(reverse('main'), next=request.path)
                return HttpResponseRedirect(next_url)

        return wrapper
    return decorator

Example 142

Project: element43 Source File: views.py
@login_required
def api_character(request, api_id, api_verification_code):

    """
    Validate key / ID combination. If it's valid, check security bitmask.
    """

    # Try to authenticate with supplied key / ID pair and fetch api key meta data.
    try:
        # Fetch info
        api = eveapi.EVEAPIConnection()
        auth = api.auth(keyID=api_id, vCode=api_verification_code)
        key_info = auth.account.APIKeyInfo()
    except:
        # Message and redirect
        messages.error(request, """Verification of your API key failed.
                                   Please follow the instructions on the right half of this page to generate a valid one.""")
        return HttpResponseRedirect(reverse('manage_api_keys'))

    if key_info.key.type == "Character" or key_info.key.type == "Account":

        # Minimum access mask
        min_access_mask = 8

        # attributes & implants
        implant = {}
        i_stats = {}
        attributes = ['memory', 'intelligence', 'perception', 'willpower', 'charisma']

        # Do a simple bitwise operation to determine if we have sufficient rights with this key.
        if not ((min_access_mask & key_info.key.accessMask) == min_access_mask):
            # Message and redirect
            messages.error(request, """The API key you supplied does not have sufficient rights.
                                       Please follow the instructions on the right half of this page to generate a valid one.""")
            return HttpResponseRedirect(reverse('manage_api_keys'))

        # Get characters associated with this key
        characters = auth.account.Characters().characters

        # If form is submitted, add characters to account
        if request.method == 'POST':
            post_characters = request.POST.getlist('characters')

            added_chars = False

            for char in characters:
                if str(char.characterID) in post_characters:
                    # Add key to DB if it does not exist
                    if not APIKey.objects.filter(keyid=api_id, vcode=api_verification_code):

                        # Handle keys which never expire
                        try:
                            key_expiration = datetime.datetime.fromtimestamp(key_info.key.expires)
                        except:
                            key_expiration = "9999-12-31 00:00:00"

                        key = APIKey(user=request.user,
                                     keyid=api_id,
                                     vcode=api_verification_code,
                                     expires=key_expiration,
                                     accessmask=key_info.key.accessMask,
                                     is_valid=True,
                                     is_character_key=True)

                        key.save()

                    else:
                        key = APIKey.objects.get(user=request.user, keyid=api_id, vcode=api_verification_code)

                    # If char already is assigned to another key, just move it
                    try:
                        char_to_move = Character.objects.get(id=char.characterID, user=request.user)
                        char_to_move.apikey_id = key.id
                        char_to_move.save()

                        # Update timers
                        manage_character_api_timers(char_to_move)

                        added_chars = True

                    except Character.DoesNotExist:
                        # Add character
                        me = auth.character(char.characterID)
                        sheet = me.CharacterSheet()
                        i_stats['name'] = ""
                        i_stats['value'] = 0
                        for attr in attributes:
                            implant[attr] = i_stats

                        # have to check because if you don't have an implant in you get nothing back
                        try:
                            implant['memory'] = {'name': sheet.attributeEnhancers.memoryBonus.augmentatorName,
                                                 'value': sheet.attributeEnhancers.memoryBonus.augmentatorValue}
                        except:
                            pass
                        try:
                            implant['perception'] = {'name': sheet.attributeEnhancers.perceptionBonus.augmentatorName,
                                                     'value': sheet.attributeEnhancers.perceptionBonus.augmentatorValue}
                        except:
                            pass
                        try:
                            implant['intelligence'] = {'name': sheet.attributeEnhancers.intelligenceBonus.augmentatorName,
                                                       'value': sheet.attributeEnhancers.intelligenceBonus.augmentatorValue}
                        except:
                            pass
                        try:
                            implant['willpower'] = {'name': sheet.attributeEnhancers.willpowerBonus.augmentatorName,
                                                    'value': sheet.attributeEnhancers.willpowerBonus.augmentatorValue}
                        except:
                            pass
                        try:
                            implant['charisma'] = {'name': sheet.attributeEnhancers.charismaBonus.augmentatorName,
                                                   'value': sheet.attributeEnhancers.charismaBonus.augmentatorValue}
                        except:
                            pass
                        try:
                            a_name = sheet.allianceName
                            a_id = sheet.allianceID

                        except:
                            a_name = ""
                            a_id = 0

                        new_char = Character(id=char.characterID,
                                            name=char.name,
                                            user=request.user,
                                            apikey=key,
                                            corp_name=sheet.corporationName,
                                            corp_id=sheet.corporationID,
                                            alliance_name=a_name,
                                            alliance_id=a_id,
                                            dob=pytz.utc.localize(datetime.datetime.utcfromtimestamp(sheet.DoB)),
                                            race=sheet.race,
                                            bloodline=sheet.bloodLine,
                                            ancestry=sheet.ancestry,
                                            gender=sheet.gender,
                                            clone_name=sheet.cloneName,
                                            clone_skill_points=sheet.cloneSkillPoints,
                                            balance=sheet.balance,
                                            implant_memory_name=implant['memory']['name'],
                                            implant_memory_bonus=implant['memory']['value'],
                                            implant_perception_name=implant['perception']['name'],
                                            implant_perception_bonus=implant['perception']['value'],
                                            implant_intelligence_name=implant['intelligence']['name'],
                                            implant_intelligence_bonus=implant['intelligence']['value'],
                                            implant_willpower_name=implant['willpower']['name'],
                                            implant_willpower_bonus=implant['willpower']['value'],
                                            implant_charisma_name=implant['charisma']['name'],
                                            implant_charisma_bonus=implant['charisma']['value'])
                        new_char.save()

                        new_apitimer = APITimer(character=new_char,
                                                corporation=None,
                                                apisheet="CharacterSheet",
                                                nextupdate=pytz.utc.localize(datetime.datetime.utcfromtimestamp(sheet._meta.cachedUntil)))
                        new_apitimer.save()

                        # Update other timers
                        manage_character_api_timers(new_char)

                        for skill in sheet.skills:
                            new_skill = CharSkill(character=new_char,
                                                  skill_id=skill.typeID,
                                                  skillpoints=skill.skillpoints,
                                                  level=skill.level)
                            new_skill.save()

                        added_chars = True

            # Change message depending on what we did
            if added_chars:
                messages.success(request, "Successfully added the selected character(s) to your account.")
            else:
                messages.info(request, "No characters were added.")
            return HttpResponseRedirect(reverse('manage_characters'))

    else:
        # This must be a corporation key then
        # Add key to DB if it does not exist
        if not APIKey.objects.filter(keyid=api_id, vcode=api_verification_code):

            # Handle keys which never expire
            try:
                key_expiration = datetime.datetime.fromtimestamp(key_info.key.expires)
            except:
                key_expiration = "9999-12-31 00:00:00"

            key = APIKey(user=request.user,
                         keyid=api_id,
                         vcode=api_verification_code,
                         expires=key_expiration,
                         accessmask=key_info.key.accessMask,
                         is_valid=True,
                         is_character_key=False)

            key.save()

            messages.success(request, "Successfully added your corporate key.")

        else:
            messages.info(request, "No keys were added.")

        return HttpResponseRedirect(reverse('manage_api_keys'))

    rcontext = RequestContext(request, {'chars': characters})
    return render_to_response('api_character.haml', rcontext)

Example 143

Project: django-inviting Source File: views.py
def register(request,
             invitation_key,
             wrong_key_template='invitation/wrong_invitation_key.html',
             redirect_to_if_authenticated='/',
             success_url=None,
             form_class=RegistrationFormInvitation,
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register via invitation.

    Send invitation email and then redirect to success URL if the
    invitation form is valid. Redirect named URL ``invitation_unavailable``
    on InvitationError. Render invitation form template otherwise. Sends
    registration.signals.user_registered after creating the user.

    **Required arguments:**

    :invitation_key:
        An invitation key in the form of ``[\da-e]{40}``

    **Optional arguments:**

    :wrong_key_template:
        Template to be used when an invalid invitation key is supplied.
        Default value is ``invitation/wrong_invitation_key.html``.

    :redirect_to_if_authenticated:
        URL to be redirected when an authenticated user calls this view.
        Defaults value is ``/``

    :success_url:
        The URL to redirect to on successful registration. Default value is
        ``None``, ``invitation_registered`` will be resolved in this case.

    :form_class:
        A form class to use for registration. Takes the invited email as first
        argument to its constructor.

    :template_name:
        A custom template to use. Default value is
        ``registration/registration_form.html``.

    :extra_context:
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    **Templates:**

    ``invitation/invitation_form.html`` or ``template_name`` keyword
    argument as the *main template*.

    ``invitation/wrong_invitation_key.html`` or ``wrong_key_template`` keyword
    argument as the *wrong key template*.

    **Context:**

    ``RequestContext`` instances are used rendering both templates. Context,
    in addition to ``extra_context``, contains:

    For wrong key template
        :invitation_key: supplied invitation key

    For main template
        :form:
            The registration form.
    """
    if request.user.is_authenticated():
        return HttpResponseRedirect(redirect_to_if_authenticated)
    try:
        invitation = Invitation.objects.find(invitation_key)
    except Invitation.DoesNotExist:
        context = apply_extra_context(RequestContext(request), extra_context)
        return render_to_response(wrong_key_template,
                                  {'invitation_key': invitation_key},
                                  context_instance=context)
    if request.method == 'POST':
        form = form_class(invitation.email, request.POST, request.FILES)
        if form.is_valid():
            new_user = form.save()
            invitation.mark_accepted(new_user)
            user_registered.send(sender="invitation",
                                 user=new_user,
                                 request=request)
            return HttpResponseRedirect(success_url or \
                                             reverse('invitation_registered'))
    else:
        form = form_class(invitation.email)
    context = apply_extra_context(RequestContext(request), extra_context)
    return render_to_response(template_name,
                              {'form': form},
                              context_instance=context)

Example 144

Project: rust-ci Source File: views.py
def github_callback(request):
    state = request.session.get('state')
    state_param = request.GET['state']
    if not state or state_param != state:
        logger.error('github_callback failed, no state given or ' +
            'not matching. session={}, param={}'.format(state, state_param))
        return HttpResponse('Unauthorized', status=401)

    project_id = request.session['project_id']
    project = Project.objects.get(pk = project_id)

    auth_reason = request.session['auth_reason']

    request.session.clear()

    data = {
        'client_id': private_settings.GITHUB_CLIENT_ID,
        'client_secret': private_settings.GITHUB_CLIENT_SECRET,
        'code': request.GET['code'],
        'state': request.GET['state']
    }
    req = urllib2.Request('https://github.com/login/oauth/access_token',
            urlencode(data))
    req.add_header('Accept', 'application/json')
    response = json.loads(urllib2.urlopen(req).read())

    if 'access_token' in response and response['access_token']:
        github_token = response['access_token']

        req = urllib2.Request('https://api.github.com/user')
        req.add_header('Accept', 'application/json')
        req.add_header('Authorization', 'token {}'.
                format(github_token))
        github_user = json.loads(urllib2.urlopen(req).read())
       
        #print(json.dumps(github_user, sort_keys=True, indent=4))

        # Get organizations for user (to allow members of orgs to 
        # add projects on behalf of their organization)
        orgs_req = urllib2.Request(github_user['organizations_url'])
        orgs_req.add_header('Accept', 'application/json')
        orgs_req.add_header('Authorization', 'token {}'.
                format(github_token))
        github_user_orgs = json.loads(urllib2.urlopen(orgs_req).read())

        #print(json.dumps(github_user_orgs, sort_keys=True, indent=4))

        is_authorized = False
        # Check that we got token for the right user or organization
        if project.username == github_user['login']:
            is_authorized = True
        else:
            for github_org in github_user_orgs:
                if project.username == github_org['login']:
                    is_authorized = True
                    break

        if not is_authorized:
            if auth_reason == 'add_project':
                # Unable to authorize when adding, delete
                project.delete()

            error_message = 'Neither authenticated GitHub user ({}) \
                    or that users organizations matches project \
                    owner ({})'.format(github_user['login'],
                    project.username)
            return index(request, error_message)

        if auth_reason == 'delete_project':
            if not settings.DEBUG:
                mail_message = "{}/{} - {}\n\n".\
                        format(project.username, project.repository,
                                project.branch)
                mail_admins('Project deleted', mail_message)
            
            project.mark_project_deleted()
            return HttpResponseRedirect(reverse('ppatrigger.views.index'))

        else:
            travis_token = travisclient.get_travis_token(github_token)

            if travis_token:
                if auth_reason == 'add_project':
                    project.auth_token = travis_token
                    project.save()
                    
                    if not settings.DEBUG:
                        mail_message = "{}/{} - {}\n\n".\
                                format(project.username, project.repository,
                                        project.branch)
                        mail_admins('Project added', mail_message)

                elif auth_reason == 'get_auth_token':
                    # Used if initial auth failed for some reason
                    # (i.e. no auth_token in db)
                    project.auth_token = travis_token
                    project.save()

                    if not settings.DEBUG:
                        mail_message = "{}/{} - {}\n\n".\
                                format(project.username, project.repository,
                                        project.branch)
                        mail_admins('Project authenticated', mail_message)

                elif auth_reason == 'trigger_rebuild':
                    project.auth_token = travis_token
                    project.build_requested = True 
                    project.save()                
            
                elif auth_reason == 'edit_project':
                    request.session['session_auth'] = project.rustci_token
       
                    return HttpResponseRedirect(reverse(
                        'project.action.edit_project',
                        args=(project.id,)))

                return HttpResponseRedirect(reverse('ppatrigger.views.index'))
            else:
                error_message = 'Error in response from Travis CI'

    else:
        if auth_reason == 'add_project':
            # Unable to authorize when adding, delete
            project.delete()

        error_message = 'Error in response from GitHub: {}'.\
                format(response.get('error'))

    return index(request, error_message)

Example 145

Project: geonode Source File: views.py
@login_required
def layer_metadata(request, layername, template='layers/layer_metadata.html'):
    layer = _resolve_layer(
        request,
        layername,
        'base.change_resourcebase_metadata',
        _PERMISSION_MSG_METADATA)
    layer_attribute_set = inlineformset_factory(
        Layer,
        Attribute,
        extra=0,
        form=LayerAttributeForm,
    )
    topic_category = layer.category

    poc = layer.poc
    metadata_author = layer.metadata_author

    if request.method == "POST":
        if layer.metadata_uploaded_preserve:  # layer metadata cannot be edited
            out = {
                'success': False,
                'errors': METADATA_UPLOADED_PRESERVE_ERROR
            }
            return HttpResponse(
                json.dumps(out),
                content_type='application/json',
                status=400)

        layer_form = LayerForm(request.POST, instance=layer, prefix="resource")
        attribute_form = layer_attribute_set(
            request.POST,
            instance=layer,
            prefix="layer_attribute_set",
            queryset=Attribute.objects.order_by('display_order'))
        category_form = CategoryForm(
            request.POST,
            prefix="category_choice_field",
            initial=int(
                request.POST["category_choice_field"]) if "category_choice_field" in request.POST else None)

    else:
        layer_form = LayerForm(instance=layer, prefix="resource")
        attribute_form = layer_attribute_set(
            instance=layer,
            prefix="layer_attribute_set",
            queryset=Attribute.objects.order_by('display_order'))
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)

    if request.method == "POST" and layer_form.is_valid(
    ) and attribute_form.is_valid() and category_form.is_valid():
        new_poc = layer_form.cleaned_data['poc']
        new_author = layer_form.cleaned_data['metadata_author']

        if new_poc is None:
            if poc is None:
                poc_form = ProfileForm(
                    request.POST,
                    prefix="poc",
                    instance=poc)
            else:
                poc_form = ProfileForm(request.POST, prefix="poc")
            if poc_form.is_valid():
                if len(poc_form.cleaned_data['profile']) == 0:
                    # FIXME use form.add_error in django > 1.7
                    errors = poc_form._errors.setdefault('profile', ErrorList())
                    errors.append(_('You must set a point of contact for this resource'))
                    poc = None
            if poc_form.has_changed and poc_form.is_valid():
                new_poc = poc_form.save()

        if new_author is None:
            if metadata_author is None:
                author_form = ProfileForm(request.POST, prefix="author",
                                          instance=metadata_author)
            else:
                author_form = ProfileForm(request.POST, prefix="author")
            if author_form.is_valid():
                if len(author_form.cleaned_data['profile']) == 0:
                    # FIXME use form.add_error in django > 1.7
                    errors = author_form._errors.setdefault('profile', ErrorList())
                    errors.append(_('You must set an author for this resource'))
                    metadata_author = None
            if author_form.has_changed and author_form.is_valid():
                new_author = author_form.save()

        new_category = TopicCategory.objects.get(
            id=category_form.cleaned_data['category_choice_field'])

        for form in attribute_form.cleaned_data:
            la = Attribute.objects.get(id=int(form['id'].id))
            la.description = form["description"]
            la.attribute_label = form["attribute_label"]
            la.visible = form["visible"]
            la.display_order = form["display_order"]
            la.save()

        if new_poc is not None and new_author is not None:
            new_keywords = [x.strip() for x in layer_form.cleaned_data['keywords']]
            layer.keywords.clear()
            layer.keywords.add(*new_keywords)
            the_layer = layer_form.save()
            up_sessions = UploadSession.objects.filter(layer=the_layer.id)
            if up_sessions.count() > 0 and up_sessions[0].user != the_layer.owner:
                up_sessions.update(user=the_layer.owner)
            the_layer.poc = new_poc
            the_layer.metadata_author = new_author
            Layer.objects.filter(id=the_layer.id).update(
                category=new_category
                )

            if getattr(settings, 'SLACK_ENABLED', False):
                try:
                    from geonode.contrib.slack.utils import build_slack_message_layer, send_slack_messages
                    send_slack_messages(build_slack_message_layer("layer_edit", the_layer))
                except:
                    print "Could not send slack message."

            return HttpResponseRedirect(
                reverse(
                    'layer_detail',
                    args=(
                        layer.service_typename,
                    )))

    if poc is not None:
        layer_form.fields['poc'].initial = poc.id
        poc_form = ProfileForm(prefix="poc")
        poc_form.hidden = True
    else:
        poc_form = ProfileForm(prefix="poc")
        poc_form.hidden = False

    if metadata_author is not None:
        layer_form.fields['metadata_author'].initial = metadata_author.id
        author_form = ProfileForm(prefix="author")
        author_form.hidden = True
    else:
        author_form = ProfileForm(prefix="author")
        author_form.hidden = False

    return render_to_response(template, RequestContext(request, {
        "layer": layer,
        "layer_form": layer_form,
        "poc_form": poc_form,
        "author_form": author_form,
        "attribute_form": attribute_form,
        "category_form": category_form,
    }))

Example 146

Project: gpgvote Source File: views.py
def vote(request, poll_id):
  if not request.user.is_authenticated():
    return HttpResponseRedirect('/')
  else:
    logged_in = True
    
  error = ''
  success = ''
  try:
      poll = Poll.objects.get(pk = poll_id)
  except Poll.DoesNotExist:
      raise Http404
  
  username = request.user.username
  if (not poll.is_allowed_voter(username)) \
    or poll.has_voted(username) \
    or (poll.starts > datetime.datetime.now()) \
    or (poll.ends < datetime.datetime.now()):
      return HttpResponseRedirect('/mypolls')
      
  poll_choices = Choice.objects.filter(poll = poll).order_by('id')
  choice_type = "radio"
  if poll.max_choices > 1:
    choice_type = "checkbox"
  
  vote_tag = ''
  vote_receipt_encrypted = ''
  
  if request.POST:
    form = Form(request.POST)
    if form.is_valid():
      choices = request.POST.getlist('choices')
      
      # Check that the submitted choices exist and belong to the poll
      for choice in choices:
        try:
          c = Choice.objects.get(pk = choice, poll = poll)
        except Choice.DoesNotExist:
	  error = "The submitted choices are not valid choices of the poll"
      
      # Check that the submitted choices are between min and max number of choices allowed for the poll
      if len(choices) > poll.max_choices:
	error = 'You cannot vote for more than ' + str(poll.max_choices) + ' choices'
      if len(choices) < poll.min_choices:
	error = 'You must vote for at least ' + str(poll.min_choices) + ' choices'
	if poll.max_choices == 1: # a better error message for single choice polls
	  error = 'You must select a choice'
      if list_has_duplicates(choices):
	error = 'Each choice can be selected only once'
      
      if not error:
	# Construct a unique, random string to use as a vote tag
	while not vote_tag:
	  vote_tag = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(35))
	  try:
	    v = Vote.objects.get(tag = vote_tag)
	    vote_tag = ''
	  except Vote.DoesNotExist:  # our random string is unique so we can use it as a vote tag
	    # Encrypt the vote tag with user's public pgp key and sign it with the key of the system authority
	    gpg = GPG(gpgbinary=settings.GNUPGBINARY, gnupghome=settings.GNUPGHOME)
	    vote_receipt = """GPGVote: Vote Receipt
---------------------

You are voter: 
  %s

You voted for Poll:
  \'%s\'

Created by: 
  %s

Your Vote Tag is: %s
  
You made the following choices:"""  % (request.user.pgpkey.name + ' <' + request.user.username + '>', poll.question, \
                                       poll.creator.pgpkey.name + ' <' + poll.creator.username + '>', vote_tag)
	    
	    for choice in choices:
	      choice = Choice.objects.get(pk = choice, poll = poll)
	      vote_receipt = vote_receipt + '\n  * %s' % choice.choice
	      
	    vote_receipt_encrypted = gpg.encrypt(vote_receipt, request.user.pgpkey.fingerprint, always_trust = True,
	                                     sign = settings.SYSTEM_KEY_FINGERPRINT, 
	                                     passphrase = settings.SYSTEM_KEY_PASSWD)
	    # Create the actual vote records in database
	    for choice in choices:
	      vote = Vote(choice = Choice.objects.get(id = choice), tag = vote_tag)
	      vote.save()
	    poll.add_voter(voter = username, To = 'who_voted')
	    poll.save()
	   
	success = 'You have successfully voted for the poll'
  
  return render_to_response('vote.html',
                           {         'user': username,
                                     'poll': poll,
                                  'choices': poll_choices,
                              'choice_type': choice_type,
                                    'error': error,
                                  'success': success,
                             'vote_receipt': vote_receipt_encrypted,
                                'logged_in': logged_in }, context_instance = RequestContext(request))

Example 147

Project: django-peavy Source File: views.py
@permission_required("peavy.view_logs")
def dashboard(request):
    """
    The main view: all the logs, with filters and pagination.
    """
    
    records = LogRecord.objects.all()

    applications = request.GET.getlist("application")
    if applications:
        records = records.filter(application__in=applications)

    client_ips = request.GET.getlist("client_ip")
    if client_ips:
        records = records.filter(client_ip__in=client_ips)

    levels = request.GET.getlist("level")
    if levels:
        records = records.filter(level__in=levels)

    loggers = request.GET.getlist("logger")
    if loggers:
        records = records.filter(logger__in=loggers)

    origin_servers = request.GET.getlist("origin_server")
    if origin_servers:
        records = records.filter(origin_server__in=origin_servers)

    request_ids = request.GET.getlist("request_id")
    if request_ids:
        records = records.filter(uuid__in=request_ids)

    show_anonymous_users = False
    user_pks = []
    for pk in request.GET.getlist("user_pk"):
        if pk == "None":
            show_anonymous_users = True
        else:
            user_pks.append(pk)

    user_pk_filter = None

    if show_anonymous_users:
        user_pk_filter = Q(user_pk__isnull=True)

    if user_pks:
        if not user_pk_filter:
            user_pk_filter = Q(user_pk__in=user_pks)
        else:
            user_pk_filter |= Q(user_pk__in=user_pks)
    
    if user_pk_filter:
        records = records.filter(user_pk_filter)

    usernames = request.GET.getlist("username")
    if usernames:
        records = records.filter(username__in=usernames)

    message_filters = request.GET.getlist("message")
    if message_filters:
        message_query = None
        for term in message_filters:
            if not term:
                continue
            if message_query is None:
                message_query = Q(message__iregex=term)
            else:
                message_query &= Q(message__iregex=term)
        if message_query is not None:
            records = records.filter(message_query)

    page_number = int(request.GET.get("page", 1))
    count = int(request.GET.get("count", 20))

    paginator = Paginator(object_list=records, per_page=count, allow_empty_first_page=True)

    if page_number < 1:
        redirect = re.sub("page=\d+", "page=%s" % paginator.num_pages, request.get_full_path())
        return http.HttpResponseRedirect(redirect)
    if page_number > paginator.num_pages:
        redirect = re.sub("page=\d+", "page=1", request.get_full_path())
        return http.HttpResponseRedirect(redirect)

    records = paginator.page(page_number)

    data = {
        "records": records,
    }

    return render_to_response(
        "peavy/dashboard.html",
        data,
        context_instance = RequestContext(request)
    )

Example 148

Project: ocf Source File: GUIdispatcher.py
def manageEthernet(request,rangeId=None,action=None,macId=None):

	if not action in NETWORKING_POSSIBLE_ACTIONS:
		raise Exception("Unknown action") 

	#Define context	
	extra_context = {"section": "networking","subsection":"ethernet",}	

	
	#Add process	
	if (action == NETWORKING_ACTION_ADD):
		if request.method == "GET":
			#Show form
			extra_context["form"] = HttpUtils.getFormFromModel(MacRange)
			return simple.direct_to_template(
				request,
				extra_context = extra_context, 
				template="networking/ethernet/rangeCrud.html",
			)
			return 
		
		elif request.method == "POST":
			try:
				instance = HttpUtils.getInstanceFromForm(request,MacRange)
				#Create Range
				EthernetController.createRange(instance)
				return HttpResponseRedirect("/networking/ethernet/")
			except Exception as e:
				print e
				extra_context["form"] = HttpUtils.processExceptionForm(e,request,MacRange)
				#Process creation query
				return simple.direct_to_template(
					request,
					extra_context = extra_context, 
					template="networking/ethernet/rangeCrud.html",
				)
			
			
	#Show
	if ((action == None) or (action==NETWORKING_ACTION_SHOW)) and (not rangeId==None):

		instance = EthernetController.getRange(rangeId)
		extra_context["range"] = instance 
		#return HttpResponseRedirect("/networking/ethernet/")

		return simple.direct_to_template(
			request,
			extra_context = extra_context, 
			template="networking/ethernet/rangeDetail.html",
		)
		
			
	#Edit
	#TODO

	#Add excluded Mac 
	if (action == NETWORKING_ACTION_ADDEXCLUDED) and (request.method == "POST"):
		if not request.method == "POST":
			raise Exception("Invalid method")
		try:	
			instance = EthernetController.getRange(rangeId)
			extra_context["range"] = instance 
		
			#Create excluded
			EthernetController.addExcludedMac(instance,request)

			return HttpResponseRedirect("/networking/ethernet/"+rangeId)

		except Exception as e:
			print e
			extra_context["errors"] = HttpUtils.processException(e)
			pass	
					
		return simple.direct_to_template(
			request,
			extra_context = extra_context, 
			template="networking/ethernet/rangeDetail.html",
		)
		
	#Release excluded Mac
	if (action == NETWORKING_ACTION_REMOVEXCLUDED) and (request.method == "POST"):

		try:	
			instance = EthernetController.getRange(rangeId)
		
			#Create excluded
			#FIXME: Why initial instance is not refreshed?
			EthernetController.removeExcludedMac(instance,macId)
			instance = EthernetController.getRange(rangeId)
			extra_context["range"] = instance 
			return HttpResponseRedirect("/networking/ethernet/"+rangeId)
		except Exception as e:
			print e
			extra_context["errors"] = HttpUtils.processException(e)
			pass	
					
		return simple.direct_to_template(
			request,
			extra_context = extra_context, 
			template="networking/ethernet/rangeDetail.html",
		)
	
	#Delete
	if (action == NETWORKING_ACTION_DELETE) and (request.method == "POST"):

		try:	
			EthernetController.deleteRange(rangeId)
			return HttpResponseRedirect("/networking/ethernet/")

		except Exception as e:
			print e
			extra_context["errors"] = HttpUtils.processException(e)
			pass	
	

	#Listing ranges
	extra_context["ranges"] = EthernetController.listRanges()
	return simple.direct_to_template(
			request,
			extra_context = extra_context, 
			template = "networking/ethernet/index.html",
		)

Example 149

Project: django-powerdns-manager Source File: views.py
@login_required
@csrf_protect
def zone_clone_view(request, zone_id):
    """Clones zone.
    
    Accepts a single Domain object ID.
    
    An intermediate page asking for the origin of the new zone.

    Clones:
    
      - Resource Records
      - Dynamic setting
      - Domain Metadata
      
    """
    # Permission check on models.
    if not request.user.has_perms([
            'powerdns_manager.add_domain',
            'powerdns_manager.change_domain',
            'powerdns_manager.add_record',
            'powerdns_manager.change_record',
            'powerdns_manager.add_domainmetadata',
            'powerdns_manager.change_domainmetadata',
            'powerdns_manager.add_dynamiczone',
            'powerdns_manager.change_dynamiczone',
        ]):
        messages.error(request, 'Insufficient permissions for this action.')
        return HttpResponseRedirect(reverse('admin:powerdns_manager_domain_changelist'))
    
    if request.method == 'POST':
        form = ClonedZoneDomainForm(request.POST)
        if form.is_valid():
            
            # Store Data from the form
            
            # Store the new domain name for the clone.
            clone_domain_name = form.cleaned_data['clone_domain_name']
            
            option_clone_dynamic = form.cleaned_data['option_clone_dynamic']
            option_clone_metadata = form.cleaned_data['option_clone_metadata']
            
            # Get the models
            Domain = get_model('powerdns_manager', 'Domain')
            Record = get_model('powerdns_manager', 'Record')
            DynamicZone = get_model('powerdns_manager', 'DynamicZone')
            DomainMetadata = get_model('powerdns_manager', 'DomainMetadata')
            
            # Clone base zone
            
            # Get the Domain object which will be cloned.
            domain_obj = Domain.objects.get(id=zone_id)
            
            # Check zone ownership.
            if request.user != domain_obj.created_by:
                messages.error(request, "Insufficient permissions to clone domain '%s'" % force_unicode(domain_obj))
                return HttpResponseRedirect(reverse('admin:powerdns_manager_domain_changelist'))
            
            # Create the clone (Check for uniqueness takes place in forms.ClonedZoneDomainForm 
            clone_obj = Domain.objects.create(
                name = clone_domain_name,
                master = domain_obj.master,
                #last_check = domain_obj.last_check,
                type = domain_obj.type,
                #notified_serial = domain_obj.notified_serial,
                account = domain_obj.account,
                created_by = request.user   # We deliberately do not use the domain_obj.created_by
            )
            #modeladmin.log_addition(request, clone_obj)
            
            # Clone Resource Records
            
            # Find all resource records of this domain (also clones empty non-terminals)
            domain_rr_qs = Record.objects.filter(domain=domain_obj)
            
            # Create the clone's RRs
            for rr in domain_rr_qs:
                
                # Construct RR name with interchanged domain
                clone_rr_name = interchange_domain(rr.name, domain_obj.name, clone_domain_name)
                
                # Special treatment to the content of SOA and SRV RRs
                if rr.type == 'SOA':
                    content_parts = rr.content.split()
                    # primary
                    content_parts[0] = interchange_domain(content_parts[0], domain_obj.name, clone_domain_name)
                    # hostmaster
                    content_parts[1] = interchange_domain(content_parts[1], domain_obj.name, clone_domain_name)
                    # Serial. Set new serial
                    content_parts[2] = generate_serial()
                    clone_rr_content = ' '.join(content_parts)
                elif rr.type == 'SRV':
                    content_parts = rr.content.split()
                    # target
                    content_parts[2] = interchange_domain(content_parts[2], domain_obj.name, clone_domain_name)
                    clone_rr_content = ' '.join(content_parts)
                else:
                    clone_rr_content = interchange_domain(rr.content, domain_obj.name, clone_domain_name)
                
                # Create and save the cloned record.
                clone_rr = Record(
                    domain = clone_obj,
                    name = clone_rr_name,
                    type = rr.type,
                    content = clone_rr_content,
                    ttl = rr.ttl,
                    prio = rr.prio,
                    auth = rr.auth,
                    ordername = rr.ordername
                )
                clone_rr.save()
                #modeladmin.log_addition(request, clone_rr)
            
            # Clone Dynamic Zone setting
            
            if option_clone_dynamic:
                
                # Get the base domain's dynamic zone.
                # There is only one Dynamic Zone object for each zone.
                try:
                    domain_dynzone_obj = DynamicZone.objects.get(domain=domain_obj)
                except DynamicZone.DoesNotExist:
                    pass
                else:
                    # Create and save the dynamic zone object for the clone.
                    clone_dynzone_obj = DynamicZone(
                        domain = clone_obj,
                        is_dynamic = domain_dynzone_obj.is_dynamic
                        )
                    clone_dynzone_obj.save()
            
            # Clone the zone's metadata
            
            if option_clone_metadata:
                
                # Get the base domain's metadata object.
                # There is only one metadata object for each zone.
                try:
                    domain_metadata_obj = DomainMetadata.objects.get(domain=domain_obj)
                except DomainMetadata.DoesNotExist:
                    pass
                else:
                    # Create and save the metadata object for the clone.
                    clone_metadata_obj = DomainMetadata(
                        domain = clone_obj,
                        kind = domain_metadata_obj.kind,
                        content = domain_metadata_obj.content
                        )
                    clone_metadata_obj.save()
            
            messages.info(request, 'Successfully cloned %s zone to %s' % \
                (domain_obj.name, clone_domain_name))
            
            # Redirect to the new zone's change form.
            return HttpResponseRedirect(reverse('admin:powerdns_manager_domain_change', args=(clone_obj.id,)))

    else:
        form = ClonedZoneDomainForm()
    
    info_dict = {
        'form': form,
        'zone_id': zone_id,
    }
    return render_to_response(
        'powerdns_manager/zone/clone.html', info_dict, context_instance=RequestContext(request))

Example 150

Project: mednet Source File: admin.py
    def changelist_view(self, request, extra_context=None):
        # Copied from parent and modified where marked to add map based on
        # change list and media.
        "The 'change list' admin view for this model."
        from django.contrib.admin.views.main import ChangeList, ERROR_FLAG
        opts = self.model._meta
        app_label = opts.app_label
        if not self.has_change_permission(request, None):
            raise PermissionDenied

        # Check actions to see if any are available on this changelist
        actions = self.get_actions(request)

        # Remove action checkboxes if there aren't any actions available.
        list_display = list(self.list_display)
        if not actions:
            try:
                list_display.remove('action_checkbox')
            except ValueError:
                pass

        try:
            cl = ChangeList(request, self.model, list_display, self.list_display_links, self.list_filter,
                self.date_hierarchy, self.search_fields, self.list_select_related, self.list_per_page, self.list_editable, self)
        except IncorrectLookupParameters:
            # Wacky lookup parameters were given, so redirect to the main
            # changelist page, without parameters, and pass an 'invalid=1'
            # parameter via the query string. If wacky parameters were given and
            # the 'invalid=1' parameter was already in the query string, something
            # is screwed up with the database, so display an error page.
            if ERROR_FLAG in request.GET.keys():
                return render_to_response('admin/invalid_setup.html', {'title': _('Database error')})
            return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')

        # If the request was POSTed, this might be a bulk action or a bulk edit.
        # Try to look up an action first, but if this isn't an action the POST
        # will fall through to the bulk edit check, below.
        if actions and request.method == 'POST':
            response = self.response_action(request, queryset=cl.get_query_set())
            if response:
                return response

        # If we're allowing changelist editing, we need to construct a formset
        # for the changelist given all the fields to be edited. Then we'll
        # use the formset to validate/process POSTed data.
        formset = cl.formset = None


        # Handle POSTed bulk-edit data.
        if request.method == "POST" and self.list_editable:
            FormSet = self.get_changelist_formset(request)
            formset = cl.formset = FormSet(request.POST, request.FILES, queryset=cl.result_list)
            if formset.is_valid():
                changecount = 0
                for form in formset.forms:
                    if form.has_changed():
                        obj = self.save_form(request, form, change=True)
                        self.save_model(request, obj, form, change=True)
                        form.save_m2m()
                        change_msg = self.construct_change_message(request, form, None)
                        self.log_change(request, obj, change_msg)
                        changecount += 1

                if changecount:
                    if changecount == 1:
                        name = force_unicode(opts.verbose_name)
                    else:
                        name = force_unicode(opts.verbose_name_plural)
                    msg = ungettext("%(count)s %(name)s was changed successfully.",
                                    "%(count)s %(name)s were changed successfully.",
                                    changecount) % {'count': changecount,
                                                    'name': name,
                                                    'obj': force_unicode(obj)}
                    self.message_user(request, msg)

                return HttpResponseRedirect(request.get_full_path())

        # Handle GET -- construct a formset for display.
        elif self.list_editable:
            FormSet = self.get_changelist_formset(request)
            formset = cl.formset = FormSet(queryset=cl.result_list)

        # Build the list of media to be used by the formset.
        if formset:
            media = self.media + formset.media
        else:
            media = self.media

        # Build the action form and populate it with available actions.
        if actions:
            action_form = self.action_form(auto_id=None)
            action_form.fields['action'].choices = self.get_action_choices(request)
        else:
            action_form = None

        context = {
            'title': cl.title,
            'is_popup': cl.is_popup,
            'cl': cl,
            'media': media,
            'has_add_permission': self.has_add_permission(request),
            'root_path': self.admin_site.root_path,
            'app_label': app_label,
            'action_form': action_form,
            'actions_on_top': self.actions_on_top,
            'actions_on_bottom': self.actions_on_bottom,
        }

        # MODIFICATION
        map = self.get_changelist_map(cl)
        if map:
            context['media'] += map.media
            context['map'] = map
        # END MODIFICATION

        context.update(extra_context or {})
        return render_to_response(self.change_list_template or [
            'admin/%s/%s/change_list.html' % (app_label, opts.object_name.lower()),
            'admin/%s/change_list.html' % app_label,
            'admin/change_list.html'
        ], context, context_instance=template.RequestContext(request))
See More Examples - Go to Next Page
Page 1 Page 2 Page 3 Selected Page 4