def can_create_election(request): user = get_user(request) if user and user.admin_p: return True return False
def index(request): """ the page from which one chooses how to log in. """ user = get_user(request) # single auth system? if len(helios_auth.ENABLED_AUTH_SYSTEMS) == 1 and not user: return HttpResponseRedirect( reverse(AUTH_START, args=[helios_auth.ENABLED_AUTH_SYSTEMS[0]]) + '?return_url=' + request.GET.get('return_url', '')) #if helios_auth.DEFAULT_AUTH_SYSTEM and not user: # return HttpResponseRedirect(reverse(start, args=[helios_auth.DEFAULT_AUTH_SYSTEM])+ '?return_url=' + request.GET.get('return_url', '')) default_auth_system_obj = None if helios_auth.DEFAULT_AUTH_SYSTEM: default_auth_system_obj = AUTH_SYSTEMS[helios_auth.DEFAULT_AUTH_SYSTEM] #form = password.LoginForm() return render_template( request, 'index', { 'return_url': request.GET.get('return_url', '/'), 'enabled_auth_systems': helios_auth.ENABLED_AUTH_SYSTEMS, 'default_auth_system': helios_auth.DEFAULT_AUTH_SYSTEM, 'default_auth_system_obj': default_auth_system_obj })
def index(request): """ the page from which one chooses how to log in. """ user = get_user(request) # single auth system? if len(helios_auth.ENABLED_AUTH_SYSTEMS) == 1 and not user: return HttpResponseRedirect( reverse(start, args=[helios_auth.ENABLED_AUTH_SYSTEMS[0]]) + "?return_url=" + request.GET.get("return_url", "") ) # if auth.DEFAULT_AUTH_SYSTEM and not user: # return HttpResponseRedirect(reverse(start, args=[auth.DEFAULT_AUTH_SYSTEM])+ '?return_url=' + request.GET.get('return_url', '')) default_auth_system_obj = None if helios_auth.DEFAULT_AUTH_SYSTEM: default_auth_system_obj = AUTH_SYSTEMS[helios_auth.DEFAULT_AUTH_SYSTEM] # form = password.LoginForm() return render_template( request, "index", { "return_url": request.GET.get("return_url", "/"), "enabled_auth_systems": helios_auth.ENABLED_AUTH_SYSTEMS, "default_auth_system": helios_auth.DEFAULT_AUTH_SYSTEM, "default_auth_system_obj": default_auth_system_obj, }, )
def follow_view(request): if request.method == "GET": from helios_auth.view_utils import render_template from helios_auth.views import after return render_template( request, "twitter/follow", {"user_to_follow": USER_TO_FOLLOW, "reason_to_follow": REASON_TO_FOLLOW}, ) if request.method == "POST": follow_p = bool(request.POST.get("follow_p", False)) if follow_p: from helios_auth.security import get_user user = get_user(request) twitter_client = _get_client_by_token(user.token) result = twitter_client.oauth_request( "http://api.twitter.com/1/friendships/create.json", args={"screen_name": USER_TO_FOLLOW}, method="POST", ) from helios_auth.url_names import AUTH_AFTER_INTERVENTION return HttpResponseRedirect(reverse(AUTH_AFTER_INTERVENTION))
def voters_eligibility(request, election): """ set eligibility for voters """ user = get_user(request) if request.method == "GET": # this shouldn't happen, only POSTs return HttpResponseRedirect("/") # for now, private elections cannot change eligibility if election.private_p: return HttpResponseRedirect(settings.SECURE_URL_HOST + reverse(voters_list_pretty, args=[election.uuid])) # eligibility eligibility = request.POST['eligibility'] if eligibility in ['openreg', 'limitedreg']: election.openreg= True if eligibility == 'closedreg': election.openreg= False if eligibility == 'limitedreg': # now process the constraint category_id = request.POST['category_id'] constraint = AUTH_SYSTEMS[user.user_type].generate_constraint(category_id, user) election.eligibility = [{'auth_system': user.user_type, 'constraint': [constraint]}] else: election.eligibility = None election.save() return HttpResponseRedirect(settings.SECURE_URL_HOST + reverse(voters_list_pretty, args=[election.uuid]))
def one_election_view(request, election): user = get_user(request) admin_p = security.user_can_admin_election(user, election) can_feature_p = security.user_can_feature_election(user, election) notregistered = False eligible_p = True election_url = get_election_url(election) election_badge_url = get_election_badge_url(election) status_update_message = None vote_url = "%s/booth/vote.html?%s" % (settings.SECURE_URL_HOST, urllib.urlencode({'election_url' : reverse(one_election, args=[election.uuid])})) test_cookie_url = "%s?%s" % (reverse(test_cookie), urllib.urlencode({'continue_url' : vote_url})) if user: voter = Voter.get_by_election_and_user(election, user) if not voter: try: eligible_p = _check_eligibility(election, user) except AuthenticationExpired: return user_reauth(request, user) notregistered = True else: voter = get_voter(request, user, election) if voter: # cast any votes? votes = CastVote.get_by_voter(voter) else: votes = None # status update message? if election.openreg: if election.voting_has_started: status_update_message = u"Vote in %s" % election.name else: status_update_message = u"Register to vote in %s" % election.name # result! if election.result: status_update_message = u"Results are in for %s" % election.name # a URL for the social buttons socialbuttons_url = get_socialbuttons_url(election_url, status_update_message) trustees = Trustee.get_by_election(election) # should we show the result? show_result = election.result_released_at or (election.result and admin_p) return render_template(request, 'election_view', {'election' : election, 'trustees': trustees, 'admin_p': admin_p, 'user': user, 'voter': voter, 'votes': votes, 'notregistered': notregistered, 'eligible_p': eligible_p, 'can_feature_p': can_feature_p, 'election_url' : election_url, 'vote_url': vote_url, 'election_badge_url' : election_badge_url, 'show_result': show_result, 'test_cookie_url': test_cookie_url, 'socialbuttons_url' : socialbuttons_url})
def user_can_see_election(request, election): user = get_user(request) if not election.private_p: return True # election is private # but maybe this user is the administrator? if user_can_admin_election(user, election): return True # or maybe this is a trustee of the election? trustee = get_logged_in_trustee(request) if trustee and trustee.election.uuid == election.uuid: return True # then this user has to be a voter #return (get_voter(request, user, election) != None) # Testa se esta logado if user: return True else: return False
def election_admin_wrapper(request, election_uuid=None, *args, **kw): election = get_election_by_uuid(election_uuid) user = get_user(request) if 'perm_needed' in checks: perm = Permission.objects.get(codename=checks['perm_needed']) #user is an Election Officer if not user_can_officiate_election(user, election): messages.error(request, "You don't have the required permission (%s) to execute that activity." % (perm)) return HttpResponseRedirect(get_referer_view(request)) #raise PermissionDenied() #user should at least have the required permission if 'perm_needed' in checks: kw['perm_needed'] = checks['perm_needed'] if not user_has_perm(user, election, checks['perm_needed'], request=request): messages.error(request, "You don't have the required permission (%s) to execute that activity." % (perm)) return HttpResponseRedirect(get_referer_view(request)) #raise PermissionDenied() #if the view does not explicitly put any required permission, #then the view must have required an admin user by default #else: # if not user_can_admin_election(user, election): # raise PermissionDenied() # do checks, ok means it's alright to proceed with the action ok = do_election_checks(election, checks, request) if not ok: return HttpResponseRedirect(get_referer_view(request)) return func(request, election, *args, **kw)
def home(request): # load the featured elections featured_elections = Election.get_featured() user = get_user(request) create_p = can_create_election(request) output = _('NoFeatured') if create_p: elections_administered = Election.get_by_user_as_admin(user, archived_p=False, limit=5) else: elections_administered = None if user: elections_voted = Election.get_by_user_as_voter(user, limit=5) else: elections_voted = None auth_systems = copy.copy(settings.AUTH_ENABLED_SYSTEMS) try: auth_systems.remove('password') except: pass login_box = auth_views.login_box_raw(request, return_url="/", auth_systems=auth_systems) return render_template(request, "index", {'elections': featured_elections, 'elections_administered' : elections_administered, 'elections_voted' : elections_voted, 'create_p':create_p, 'login_box' : login_box})
def follow_view(request): if request.method == "GET": from helios_auth.view_utils import render_template from helios_auth.views import after return render_template(request, 'twitter/follow', { 'user_to_follow': USER_TO_FOLLOW, 'reason_to_follow': REASON_TO_FOLLOW }) if request.method == "POST": follow_p = bool(request.POST.get('follow_p', False)) if follow_p: from helios_auth.security import get_user user = get_user(request) twitter_client = _get_client_by_token(user.token) result = twitter_client.oauth_request( 'http://api.twitter.com/1/friendships/create.json', args={'screen_name': USER_TO_FOLLOW}, method='POST') from helios_auth.views import after_intervention return HttpResponseRedirect(reverse(after_intervention))
def home(request): user = get_user(request) if user: elections = Election.get_by_user_as_admin(user, archived_p = False) else: elections = [] return render_template(request, "index", {'elections' : elections})
def elections_administered(request): if not can_create_election(request): return HttpResponseForbidden('only an administrator has elections to administer') user = get_user(request) elections = Election.get_by_user_as_admin(user) return render_template(request, "elections_administered", {'elections': elections})
def voters_list_pretty(request, election): """ Show the list of voters now using Django pagination """ # for django pagination support page = int(request.GET.get('page', 1)) limit = int(request.GET.get('limit', 50)) q = request.GET.get('q','') order_by = 'user__user_id' # unless it's by alias, in which case we better go by UUID if election.use_voter_aliases: order_by = 'alias' user = get_user(request) admin_p = security.user_can_admin_election(user, election) categories = None eligibility_category_id = None try: if admin_p and can_list_categories(user.user_type): categories = AUTH_SYSTEMS[user.user_type].list_categories(user) eligibility_category_id = election.eligibility_category_id(user.user_type) except AuthenticationExpired: return user_reauth(request, user) # files being processed voter_files = election.voterfile_set.all() # load a bunch of voters # voters = Voter.get_by_election(election, order_by=order_by) voters = Voter.objects.filter(election = election).order_by(order_by).defer('vote') if q != '': if election.use_voter_aliases: voters = voters.filter(alias__icontains = q) else: voters = voters.filter(voter_name__icontains = q) voter_paginator = Paginator(voters, limit) voters_page = voter_paginator.page(page) total_voters = voter_paginator.count return render_template(request, 'voters_list', {'election': election, 'voters_page': voters_page, 'voters': voters_page.object_list, 'admin_p': admin_p, 'email_voters': helios.VOTERS_EMAIL, 'limit': limit, 'total_voters': total_voters, 'upload_p': helios.VOTERS_UPLOAD, 'q' : q, 'voter_files': voter_files, 'categories': categories, 'eligibility_category_id' : eligibility_category_id})
def _get_messages_queryset(self): """ Returns the QuerySet containing all user messages (or ``None`` if request.user is not a contrib.auth User). """ #user = getattr(self.request, 'user', None) user = get_user(self.request) if isinstance(user, User): return user._message_set.all()
def can_create_election(request): user = get_user(request) if not user: return False if helios.ADMIN_ONLY: return user.admin_p else: return user != None
def election_new(request): if not can_create_election(request): return HttpResponseForbidden('only an administrator can create an election') error = None user = get_user(request) if request.method == "GET": election_form = forms.ElectionForm(initial={'private_p': settings.HELIOS_PRIVATE_DEFAULT, 'help_email': user.info.get("email", '')}) else: check_csrf(request) election_form = forms.ElectionForm(request.POST) if election_form.is_valid(): # create the election obj election_params = dict(election_form.cleaned_data) # is the short name valid if helios_utils.urlencode(election_params['short_name']) == election_params['short_name']: election_params['uuid'] = str(uuid.uuid1()) election_params['cast_url'] = settings.SECURE_URL_HOST + reverse(one_election_cast, args=[election_params['uuid']]) # registration starts closed election_params['openreg'] = False user = get_user(request) election_params['admin'] = user election, created_p = Election.get_or_create(**election_params) if created_p: # add Helios as a trustee by default election.generate_trustee(ELGAMAL_PARAMS) return HttpResponseRedirect(settings.SECURE_URL_HOST + reverse(one_election_view, args=[election.uuid])) else: error = "An election with short name %s already exists" % election_params['short_name'] else: error = "No special characters allowed in the short name." return render_template(request, "election_new", {'election_form': election_form, 'error': error})
def admin_actions(request): user = get_user(request) page = int(request.GET.get('page', 1)) limit = int(request.GET.get('limit', 25)) actions = HeliosLog.objects.filter(user=user).order_by('-at') actions_paginator = Paginator(actions, limit) actions_page = actions_paginator.page(page) return render_template(request, "stats_admin_actions", {'actions' : actions_page.object_list, 'actions_page': actions_page, 'limit' : limit})
def render_template(request, template_name, vars = {}): t = loader.get_template(template_name + '.html') vars_with_user = vars.copy() vars_with_user['user'] = get_user(request) vars_with_user['settings'] = settings vars_with_user['CURRENT_URL'] = request.path if 'election' in vars and get_user(request): try: vars_with_user['officer'] = ElectionOfficer.get_by_election_and_user(election=vars['election'], user=get_user(request)) except: pass # csrf protection if request.session.has_key('csrf_token'): vars_with_user['csrf_token'] = request.session['csrf_token'] return render_to_response('server_ui/templates/%s.html' % template_name, vars_with_user)
def trustee_check_wrapper(request, election_uuid, trustee_uuid, *args, **kwargs): election = get_election_by_uuid(election_uuid) trustee = Trustee.get_by_election_and_uuid(election, trustee_uuid) user = get_user(request) if (user and user == trustee.user) or (trustee == get_logged_in_trustee(request)): return func(request, election, trustee, *args, **kwargs) else: raise PermissionDenied()
def election_admin_wrapper(request, election_uuid=None, *args, **kw): election = get_election_by_uuid(election_uuid) user = get_user(request) if not user_can_admin_election(user, election): raise PermissionDenied() # do checks do_election_checks(election, checks) return func(request, election, *args, **kw)
def can_create_election(request): user = get_user(request) # can create election - usuarios ldap tambem podem if user and user.user_type == 'ldap': return True if user and user.admin_p: return True return False
def render_template(request, template_name, values=None): vars_with_user = values.copy() if values is not None else {} vars_with_user['user'] = get_user(request) vars_with_user['settings'] = settings vars_with_user['CURRENT_URL'] = request.path # csrf protection if 'csrf_token' in request.session: vars_with_user['csrf_token'] = request.session['csrf_token'] return render_to_response('server_ui/templates/%s.html' % template_name, vars_with_user)
def one_election_cast(request, election): """ on a GET, this is a cancellation, on a POST it's a cast """ if request.method == "GET": return HttpResponseRedirect("%s%s" % (settings.SECURE_URL_HOST, reverse(one_election_view, args = [election.uuid]))) user = get_user(request) encrypted_vote = request.POST['encrypted_vote'] save_in_session_across_logouts(request, 'encrypted_vote', encrypted_vote) return HttpResponseRedirect("%s%s" % (settings.SECURE_URL_HOST, reverse(one_election_cast_confirm, args=[election.uuid])))
def one_election_register(request, election): if not election.openreg: return HttpResponseForbidden('registration is closed for this election') check_csrf(request) user = get_user(request) voter = Voter.get_by_election_and_user(election, user) if not voter: voter = _register_voter(election, user) return HttpResponseRedirect(settings.SECURE_URL_HOST + reverse(one_election_view, args=[election.uuid]))
def render_template(request, template_name, vars={}): t = loader.get_template(template_name + ".html") vars_with_user = vars.copy() vars_with_user["user"] = get_user(request) vars_with_user["settings"] = settings vars_with_user["CURRENT_URL"] = request.path # csrf protection if request.session.has_key("csrf_token"): vars_with_user["csrf_token"] = request.session["csrf_token"] return render_to_response("server_ui/templates/%s.html" % template_name, vars_with_user)
def require_institution_admin_wrapper(request, *args, **kw): from heliosinstitution.models import InstitutionUserProfile user = get_user(request) # TODO: check if user is active if not user: raise PermissionDenied(_("You don't have permission to access this view")) try: user.institutionuserprofile_set.get().django_user.groups.filter( name='Institution Admin') except InstitutionUserProfile.DoesNotExist: raise PermissionDenied(_("You don't have permission to access this view")) return func(request, *args, **kw)
def prepare_vars(request, vars): vars_with_user = vars.copy() vars_with_user['user'] = get_user(request) # csrf protection if request.session.has_key('csrf_token'): vars_with_user['csrf_token'] = request.session['csrf_token'] vars_with_user['utils'] = utils vars_with_user['settings'] = settings vars_with_user['HELIOS_STATIC'] = '/static/helios/helios' vars_with_user['TEMPLATE_BASE'] = helios.TEMPLATE_BASE vars_with_user['CURRENT_URL'] = request.path vars_with_user['SECURE_URL_HOST'] = settings.SECURE_URL_HOST if 'election' in vars and get_user(request): try: vars_with_user['officer'] = ElectionOfficer.get_by_election_and_user(election=vars['election'], user=get_user(request)) except: pass return vars_with_user
def render_template(request, template_name, vars={}): t = loader.get_template(template_name + '.html') vars_with_user = vars.copy() vars_with_user['user'] = get_user(request) vars_with_user['settings'] = settings vars_with_user['CURRENT_URL'] = request.path if 'election' in vars and get_user(request): try: vars_with_user[ 'officer'] = ElectionOfficer.get_by_election_and_user( election=vars['election'], user=get_user(request)) except: pass # csrf protection if request.session.has_key('csrf_token'): vars_with_user['csrf_token'] = request.session['csrf_token'] return render_to_response('server_ui/templates/%s.html' % template_name, vars_with_user)
def render_template(request, template_name, vars = {}): t = loader.get_template(template_name + '.html') vars_with_user = vars.copy() vars_with_user['user'] = get_user(request) vars_with_user['settings'] = settings vars_with_user['CURRENT_URL'] = request.path # csrf protection if request.session.has_key('csrf_token'): vars_with_user['csrf_token'] = request.session['csrf_token'] return render_to_response('heliosinstitution/templates/%s.html' % template_name, vars_with_user)
def stats(request): user = get_user(request) if not user or not user.admin_p: raise PermissionDenied() page = int(request.GET.get('page', 1)) limit = int(request.GET.get('limit', 25)) elections = Election.objects.all().order_by('-created_at') elections_paginator = Paginator(elections, limit) elections_page = elections_paginator.page(page) return render_template(request, "stats", {'elections' : elections_page.object_list, 'elections_page': elections_page, 'limit' : limit})
def one_election_set_result_and_proof(request, election): if election.tally_type != "homomorphic" or election.encrypted_tally == None: return HttpResponseRedirect(settings.SECURE_URL_HOST + reverse(one_election_view,args=[election.election_id])) # FIXME: check csrf election.result = utils.from_json(request.POST['result']) election.result_proof = utils.from_json(request.POST['result_proof']) election.save() if get_user(request): return HttpResponseRedirect(settings.SECURE_URL_HOST + reverse(one_election_view, args=[election.uuid])) else: return SUCCESS
def one_election_set_featured(request, election): """ Set whether this is a featured election or not """ user = get_user(request) if not security.user_can_feature_election(user, election): raise PermissionDenied() featured_p = bool(int(request.GET['featured_p'])) election.featured_p = featured_p election.save() return HttpResponseRedirect(settings.SECURE_URL_HOST + reverse(one_election_view, args=[election.uuid]))
def render_template(request, template_name, vars={}): t = loader.get_template(template_name + '.html') vars_with_user = vars.copy() vars_with_user['user'] = get_user(request) vars_with_user['settings'] = settings vars_with_user['current_url'] = request.path # CSRF Protection if request.session.has_key('csrf_token'): vars_with_user['csrf_token'] = request.session['csrf_token'] return render_to_response('server_ui/templates/%s.html' % template_name, vars_with_user)
def admin_actions(request): user = get_user(request) page = int(request.GET.get('page', 1)) limit = int(request.GET.get('limit', 25)) actions = HeliosLog.objects.filter(user=user).order_by('-at') actions_paginator = Paginator(actions, limit) actions_page = actions_paginator.page(page) return render_template( request, "stats_admin_actions", { 'actions': actions_page.object_list, 'actions_page': actions_page, 'limit': limit })
def render_template(request, template_name, vars={}): t = loader.get_template(template_name + '.html') vars_with_user = vars.copy() vars_with_user['user'] = get_user(request) vars_with_user['settings'] = settings vars_with_user['CURRENT_URL'] = request.path # csrf protection if request.session.has_key('csrf_token'): vars_with_user['csrf_token'] = request.session['csrf_token'] return render_to_response('server_ui/templates/%s.html' % template_name, vars_with_user)
def prepare_vars(request, vars): vars_with_user = vars.copy() vars_with_user['user'] = get_user(request) # csrf protection if request.session.has_key('csrf_token'): vars_with_user['csrf_token'] = request.session['csrf_token'] vars_with_user['utils'] = utils vars_with_user['settings'] = settings vars_with_user['HELIOS_STATIC'] = '/static/helios/helios' vars_with_user['TEMPLATE_BASE'] = helios.TEMPLATE_BASE vars_with_user['CURRENT_URL'] = request.path vars_with_user['SECURE_URL_HOST'] = settings.SECURE_URL_HOST if 'election' in vars and get_user(request): try: vars_with_user[ 'officer'] = ElectionOfficer.get_by_election_and_user( election=vars['election'], user=get_user(request)) except: pass return vars_with_user
def prepare_vars(request, values): vars_with_user = values.copy() if request: vars_with_user['user'] = get_user(request) vars_with_user['csrf_token'] = request.session['csrf_token'] vars_with_user['SECURE_URL_HOST'] = settings.SECURE_URL_HOST vars_with_user['STATIC'] = '/static/auth' vars_with_user['MEDIA_URL'] = '/static/auth/' vars_with_user['TEMPLATE_BASE'] = helios_auth.TEMPLATE_BASE vars_with_user['settings'] = settings return vars_with_user
def one_election_freeze(request, election): # figure out the number of questions and trustees issues = election.issues_before_freeze if request.method == "GET": return render_template(request, 'election_freeze', {'election': election, 'issues' : issues, 'issues_p' : len(issues) > 0}) else: check_csrf(request) election.freeze() if get_user(request): return HttpResponseRedirect(settings.SECURE_URL_HOST + reverse(one_election_view, args=[election.uuid])) else: return SUCCESS
def require_institution_admin_wrapper(request, *args, **kw): from heliosinstitution.models import InstitutionUserProfile user = get_user(request) # TODO: check if user is active if not user: raise PermissionDenied( _("You don't have permission to access this view")) try: user.institutionuserprofile_set.get().django_user.groups.filter( name='Institution Admin') except InstitutionUserProfile.DoesNotExist: raise PermissionDenied( _("You don't have permission to access this view")) return func(request, *args, **kw)
def prepare_vars(request, values): vars_with_user = values.copy() if values else {} if request: vars_with_user["user"] = get_user(request) vars_with_user["csrf_token"] = request.session["csrf_token"] vars_with_user["SECURE_URL_HOST"] = settings.SECURE_URL_HOST vars_with_user["STATIC"] = "/static" vars_with_user["MEDIA_URL"] = "/static/" vars_with_user["TEMPLATE_BASE"] = helios_auth.TEMPLATE_BASE vars_with_user["settings"] = settings return vars_with_user
def get_messages(request): """ Returns the message storage on the request if it exists, otherwise returns user.message_set.all() as the old auth context processor did. """ if hasattr(request, '_messages'): return request._messages user = get_user(request) if user: return lazy(memoize(user.get_and_delete_messages, {}, 0), list)() else: return None """
def prepare_vars(request, vars): vars_with_user = vars.copy() if request: vars_with_user['user'] = get_user(request) vars_with_user['csrf_token'] = request.session['csrf_token'] vars_with_user['SECURE_URL_HOST'] = settings.SECURE_URL_HOST vars_with_user['STATIC'] = '/static/auth' vars_with_user['MEDIA_URL'] = '/static/auth/' vars_with_user['TEMPLATE_BASE'] = helios_auth.TEMPLATE_BASE vars_with_user['settings'] = settings return vars_with_user
def prepare_vars(request, vars): vars_with_user = vars.copy() vars_with_user['user'] = get_user(request) # csrf protection if request.session.has_key('csrf_token'): vars_with_user['csrf_token'] = request.session['csrf_token'] vars_with_user['utils'] = utils vars_with_user['settings'] = settings vars_with_user['HELIOS_STATIC'] = '/static/helios/helios' vars_with_user['TEMPLATE_BASE'] = helios.TEMPLATE_BASE vars_with_user['CURRENT_URL'] = request.path vars_with_user['SECURE_URL_HOST'] = settings.SECURE_URL_HOST return vars_with_user
def add_message(request, level, message, extra_tags='', fail_silently=False): """ Attempts to add a message to the request using the 'messages' app, falling back to the user's message_set if MessageMiddleware hasn't been enabled. """ if hasattr(request, '_messages'): return request._messages.add(level, message, extra_tags) user = get_user(request) if user: return request.user.message_set.create(message=message) if not fail_silently: raise MessageFailure('Without the django.contrib.messages ' 'middleware, messages can only be added to ' 'authenticated users.')