Code

Ticket #2332: is_logged_in.diff

File is_logged_in.diff, 13.3 KB (added by Gary Wilson <gary.wilson@…>, 8 years ago)

is_logged_in implementation with doc changes and deprecation warnings in is_anonymous

Line 
1Index: django/views/generic/create_update.py
2===================================================================
3--- django/views/generic/create_update.py       (revision 3335)
4+++ django/views/generic/create_update.py       (working copy)
5@@ -20,7 +20,7 @@
6             the form wrapper for the object
7     """
8     if extra_context is None: extra_context = {}
9-    if login_required and request.user.is_anonymous():
10+    if login_required and not request.user.is_logged_in():
11         return redirect_to_login(request.path)
12 
13     manipulator = model.AddManipulator(follow=follow)
14@@ -39,7 +39,7 @@
15             # No errors -- this means we can save the data!
16             new_object = manipulator.save(new_data)
17 
18-            if not request.user.is_anonymous():
19+            if request.user.is_logged_in():
20                 request.user.message_set.create(message="The %s was created successfully." % model._meta.verbose_name)
21 
22             # Redirect to the new object: first by trying post_save_redirect,
23@@ -86,7 +86,7 @@
24             the original object being edited
25     """
26     if extra_context is None: extra_context = {}
27-    if login_required and request.user.is_anonymous():
28+    if login_required and not request.user.is_logged_in():
29         return redirect_to_login(request.path)
30 
31     # Look up the object to be edited
32@@ -113,7 +113,7 @@
33         if not errors:
34             object = manipulator.save(new_data)
35 
36-            if not request.user.is_anonymous():
37+            if request.user.is_logged_in():
38                 request.user.message_set.create(message="The %s was updated successfully." % model._meta.verbose_name)
39 
40             # Do a post-after-redirect so that reload works, etc.
41@@ -162,7 +162,7 @@
42             the original object being deleted
43     """
44     if extra_context is None: extra_context = {}
45-    if login_required and request.user.is_anonymous():
46+    if login_required and not request.user.is_logged_in():
47         return redirect_to_login(request.path)
48 
49     # Look up the object to be edited
50@@ -180,7 +180,7 @@
51 
52     if request.method == 'POST':
53         object.delete()
54-        if not request.user.is_anonymous():
55+        if request.user.is_logged_in():
56             request.user.message_set.create(message="The %s was deleted." % model._meta.verbose_name)
57         return HttpResponseRedirect(post_delete_redirect)
58     else:
59Index: django/contrib/auth/models.py
60===================================================================
61--- django/contrib/auth/models.py       (revision 3335)
62+++ django/contrib/auth/models.py       (working copy)
63@@ -124,7 +124,13 @@
64 
65     def is_anonymous(self):
66         "Always returns False. This is a way of comparing User objects to anonymous users."
67+        import warnings
68+        warnings.warn("is_anonymous is deprecated. Use is_logged_in instead.")
69         return False
70+   
71+    def is_logged_in(self):
72+        "Always return True.  This is a way of comparing User objects to anonymous users."
73+        return True
74 
75     def get_full_name(self):
76         "Returns the first_name plus the last_name, with a space in between."
77@@ -292,4 +298,9 @@
78         return []
79 
80     def is_anonymous(self):
81+        import warnings
82+        warnings.warn("is_anonymous is deprecated. Use is_logged_in instead.")
83         return True
84+   
85+    def is_logged_in(self):
86+        return False
87Index: django/contrib/auth/decorators.py
88===================================================================
89--- django/contrib/auth/decorators.py   (revision 3335)
90+++ django/contrib/auth/decorators.py   (working copy)
91@@ -17,7 +17,7 @@
92         return _checklogin
93     return _dec
94 
95-login_required = user_passes_test(lambda u: not u.is_anonymous())
96+login_required = user_passes_test(lambda u: u.is_logged_in())
97 login_required.__doc__ = (
98     """
99     Decorator for views that checks that the user is logged in, redirecting
100Index: django/contrib/comments/templatetags/comments.py
101===================================================================
102--- django/contrib/comments/templatetags/comments.py    (revision 3335)
103+++ django/contrib/comments/templatetags/comments.py    (working copy)
104@@ -114,7 +114,7 @@
105         comment_list = get_list_function(**kwargs).order_by(self.ordering + 'submit_date').select_related()
106 
107         if not self.free:
108-            if context.has_key('user') and not context['user'].is_anonymous():
109+            if context.has_key('user') and context['user'].is_logged_in():
110                 user_id = context['user'].id
111                 context['user_can_moderate_comments'] = Comment.objects.user_is_moderator(context['user'])
112             else:
113Index: django/contrib/comments/views/karma.py
114===================================================================
115--- django/contrib/comments/views/karma.py      (revision 3335)
116+++ django/contrib/comments/views/karma.py      (working copy)
117@@ -15,7 +15,7 @@
118     rating = {'up': 1, 'down': -1}.get(vote, False)
119     if not rating:
120         raise Http404, "Invalid vote"
121-    if request.user.is_anonymous():
122+    if not request.user.is_logged_in():
123         raise Http404, _("Anonymous users cannot vote")
124     try:
125         comment = Comment.objects.get(pk=comment_id)
126Index: django/contrib/comments/views/comments.py
127===================================================================
128--- django/contrib/comments/views/comments.py   (revision 3335)
129+++ django/contrib/comments/views/comments.py   (working copy)
130@@ -63,7 +63,7 @@
131                 validator_list=get_validator_list(8),
132             ),
133         ])
134-        if not user.is_anonymous():
135+        if user.is_logged_in():
136             self["username"].is_required = False
137             self["username"].validator_list = []
138             self["password"].is_required = False
139Index: django/contrib/comments/templates/comments/form.html
140===================================================================
141--- django/contrib/comments/templates/comments/form.html        (revision 3335)
142+++ django/contrib/comments/templates/comments/form.html        (working copy)
143@@ -2,10 +2,10 @@
144 {% if display_form %}
145 <form {% if photos_optional or photos_required %}enctype="multipart/form-data" {% endif %}action="/comments/post/" method="post">
146 
147-{% if user.is_anonymous %}
148+{% if user.is_logged_in %}
149+<p>{% trans "Username:" %} <strong>{{ user.username }}</strong> (<a href="/accounts/logout/">{% trans "Log out" %}</a>)</p>
150+{% else %}
151 <p><label for="id_username">{% trans "Username:" %}</label> <input type="text" name="username" id="id_username" /><br />{% trans "Password:" %} <input type="password" name="password" id="id_password" /> (<a href="/accounts/password_reset/">{% trans "Forgotten your password?" %}</a>)</p>
152-{% else %}
153-<p>{% trans "Username:" %} <strong>{{ user.username }}</strong> (<a href="/accounts/logout/">{% trans "Log out" %}</a>)</p>
154 {% endif %}
155 
156 {% if ratings_optional or ratings_required %}
157Index: django/contrib/flatpages/views.py
158===================================================================
159--- django/contrib/flatpages/views.py   (revision 3335)
160+++ django/contrib/flatpages/views.py   (working copy)
161@@ -22,7 +22,7 @@
162     f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID)
163     # If registration is required for accessing this page, and the user isn't
164     # logged in, redirect to the login page.
165-    if f.registration_required and request.user.is_anonymous():
166+    if f.registration_required and not request.user.is_logged_in():
167         from django.contrib.auth.views import redirect_to_login
168         return redirect_to_login(request.path)
169     if f.template_name:
170Index: django/contrib/admin/views/decorators.py
171===================================================================
172--- django/contrib/admin/views/decorators.py    (revision 3335)
173+++ django/contrib/admin/views/decorators.py    (working copy)
174@@ -46,7 +46,7 @@
175     member, displaying the login page if necessary.
176     """
177     def _checklogin(request, *args, **kwargs):
178-        if not request.user.is_anonymous() and request.user.is_staff:
179+        if request.user.is_logged_in() and request.user.is_staff:
180             # The user is valid. Continue to the admin page.
181             if request.POST.has_key('post_data'):
182                 # User must have re-authenticated through a different window
183Index: django/contrib/admin/templates/admin/base.html
184===================================================================
185--- django/contrib/admin/templates/admin/base.html      (revision 3335)
186+++ django/contrib/admin/templates/admin/base.html      (working copy)
187@@ -20,7 +20,7 @@
188         <div id="branding">
189         {% block branding %}{% endblock %}
190         </div>
191-        {% if not user.is_anonymous %}{% if user.is_staff %}
192+        {% if user.is_logged_in %}{% if user.is_staff %}
193         <div id="user-tools">{% trans 'Welcome,' %} <strong>{% if user.first_name %}{{ user.first_name|escape }}{% else %}{{ user.username }}{% endif %}</strong>. {% block userlinks %}<a href="doc/">{% trans 'Documentation' %}</a> / <a href="password_change/">{% trans 'Change password' %}</a> / <a href="logout/">{% trans 'Log out' %}</a>{% endblock %}</div>
194         {% endif %}{% endif %}
195         {% block nav-global %}{% endblock %}
196Index: docs/request_response.txt
197===================================================================
198--- docs/request_response.txt   (revision 3335)
199+++ docs/request_response.txt   (working copy)
200@@ -106,12 +106,12 @@
201     A ``django.contrib.auth.models.User`` object representing the currently
202     logged-in user. If the user isn't currently logged in, ``user`` will be set
203     to an instance of ``django.contrib.auth.models.AnonymousUser``. You
204-    can tell them apart with ``is_anonymous()``, like so::
205+    can tell them apart with ``is_logged_in()``, like so::
206 
207-        if request.user.is_anonymous():
208+        if request.user.is_logged_in():
209+            # Do something for logged-in users.
210+        else:
211             # Do something for anonymous users.
212-        else:
213-            # Do something for logged-in users.
214 
215     ``user`` is only available if your Django installation has the
216     ``AuthenticationMiddleware`` activated. For more, see
217Index: docs/authentication.txt
218===================================================================
219--- docs/authentication.txt     (revision 3335)
220+++ docs/authentication.txt     (working copy)
221@@ -94,7 +94,7 @@
222 In addition to those automatic API methods, ``User`` objects have the following
223 custom methods:
224 
225-    * ``is_anonymous()`` -- Always returns ``False``. This is a way of
226+    * ``is_logged_in()`` -- Always returns ``True``. This is a way of
227       comparing ``User`` objects to anonymous users.
228 
229     * ``get_full_name()`` -- Returns the ``first_name`` plus the ``last_name``,
230@@ -218,7 +218,7 @@
231 the ``django.contrib.auth.models.User`` interface, with these differences:
232 
233     * ``id`` is always ``None``.
234-    * ``is_anonymous()`` returns ``True`` instead of ``False``.
235+    * ``is_logged_in()`` returns ``False`` instead of ``True``.
236     * ``has_perm()`` always returns ``False``.
237     * ``set_password()``, ``check_password()``, ``save()``, ``delete()``,
238       ``set_groups()`` and ``set_permissions()`` raise ``NotImplementedError``.
239@@ -254,12 +254,12 @@
240 ``request.user`` in views. ``request.user`` will give you a ``User`` object
241 representing the currently logged-in user. If a user isn't currently logged in,
242 ``request.user`` will be set to an instance of ``AnonymousUser`` (see the
243-previous section). You can tell them apart with ``is_anonymous()``, like so::
244+previous section). You can tell them apart with ``is_logged_in()``, like so::
245 
246-    if request.user.is_anonymous():
247+    if request.user.is_logged_in():
248+        # Do something for logged-in users.
249+    else:
250         # Do something for anonymous users.
251-    else:
252-        # Do something for logged-in users.
253 
254 .. _request objects: http://www.djangoproject.com/documentation/request_response/#httprequest-objects
255 .. _session documentation: http://www.djangoproject.com/documentation/sessions/
256@@ -323,19 +323,19 @@
257 ~~~~~~~~~~~
258 
259 The simple, raw way to limit access to pages is to check
260-``request.user.is_anonymous()`` and either redirect to a login page::
261+``request.user.is_logged_in()`` and either redirect to a login page::
262 
263     from django.http import HttpResponseRedirect
264 
265     def my_view(request):
266-        if request.user.is_anonymous():
267+        if not request.user.is_logged_in():
268             return HttpResponseRedirect('/login/?next=%s' % request.path)
269         # ...
270 
271 ...or display an error message::
272 
273     def my_view(request):
274-        if request.user.is_anonymous():
275+        if not request.user.is_logged_in():
276             return render_to_response('myapp/login_error.html')
277         # ...
278 
279@@ -439,7 +439,7 @@
280 permission ``polls.can_vote``::
281 
282     def my_view(request):
283-        if request.user.is_anonymous() or not request.user.has_perm('polls.can_vote'):
284+        if not request.user.is_logged_in() or not request.user.has_perm('polls.can_vote'):
285             return HttpResponse("You can't vote in this poll.")
286         # ...
287 
288@@ -605,10 +605,10 @@
289 The currently logged-in user, either a ``User`` instance or an``AnonymousUser``
290 instance, is stored in the template variable ``{{ user }}``::
291 
292-    {% if user.is_anonymous %}
293+    {% if user.is_logged_in %}
294+        <p>Welcome, {{ user.username }}. Thanks for logging in.</p>   
295+    {% else %}
296         <p>Welcome, new user. Please log in.</p>
297-    {% else %}
298-        <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
299     {% endif %}
300 
301 Permissions