/
auth.txt
2269 lines (1633 loc) · 85.5 KB
/
auth.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=============================
User authentication in Django
=============================
.. module:: django.contrib.auth
:synopsis: Django's authentication framework.
Django comes with a user authentication system. It handles user accounts,
groups, permissions and cookie-based user sessions. This document explains how
things work.
Overview
========
The auth system consists of:
* Users
* Permissions: Binary (yes/no) flags designating whether a user may perform
a certain task.
* Groups: A generic way of applying labels and permissions to more than one
user.
Installation
============
Authentication support is bundled as a Django application in
``django.contrib.auth``. To install it, do the following:
1. Put ``'django.contrib.auth'`` and ``'django.contrib.contenttypes'`` in
your :setting:`INSTALLED_APPS` setting.
(The :class:`~django.contrib.auth.models.Permission` model in
:mod:`django.contrib.auth` depends on :mod:`django.contrib.contenttypes`.)
2. Run the command ``manage.py syncdb``.
Note that the default :file:`settings.py` file created by
:djadmin:`django-admin.py startproject <startproject>` includes
``'django.contrib.auth'`` and ``'django.contrib.contenttypes'`` in
:setting:`INSTALLED_APPS` for convenience. If your :setting:`INSTALLED_APPS`
already contains these apps, feel free to run :djadmin:`manage.py syncdb
<syncdb>` again; you can run that command as many times as you'd like, and each
time it'll only install what's needed.
The :djadmin:`syncdb` command creates the necessary database tables, creates
permission objects for all installed apps that need 'em, and prompts you to
create a superuser account the first time you run it.
Once you've taken those steps, that's it.
Users
=====
.. class:: models.User
API reference
-------------
Fields
~~~~~~
.. class:: models.User
:class:`~django.contrib.auth.models.User` objects have the following
fields:
.. attribute:: models.User.username
Required. 30 characters or fewer. Usernames may contain alphanumeric,
``_``, ``@``, ``+``, ``.`` and ``-`` characters.
.. attribute:: models.User.first_name
Optional. 30 characters or fewer.
.. attribute:: models.User.last_name
Optional. 30 characters or fewer.
.. attribute:: models.User.email
Optional. Email address.
.. attribute:: models.User.password
Required. A hash of, and metadata about, the password. (Django doesn't
store the raw password.) Raw passwords can be arbitrarily long and can
contain any character. See the "Passwords" section below.
.. attribute:: models.User.is_staff
Boolean. Designates whether this user can access the admin site.
.. attribute:: models.User.is_active
Boolean. Designates whether this user account should be considered
active. We recommend that you set this flag to ``False`` instead of
deleting accounts; that way, if your applications have any foreign keys
to users, the foreign keys won't break.
This doesn't necessarily control whether or not the user can log in.
Authentication backends aren't required to check for the ``is_active``
flag, and the default backends do not. If you want to reject a login
based on ``is_active`` being ``False``, it's up to you to check that in
your own login view or a custom authentication backend. However, the
:class:`~django.contrib.auth.forms.AuthenticationForm` used by the
:func:`~django.contrib.auth.views.login` view (which is the default)
*does* perform this check, as do the permission-checking methods such
as :meth:`~models.User.has_perm` and the authentication in the Django
admin. All of those functions/methods will return ``False`` for
inactive users.
.. attribute:: models.User.is_superuser
Boolean. Designates that this user has all permissions without
explicitly assigning them.
.. attribute:: models.User.last_login
A datetime of the user's last login. Is set to the current date/time by
default.
.. attribute:: models.User.date_joined
A datetime designating when the account was created. Is set to the
current date/time by default when the account is created.
Methods
~~~~~~~
.. class:: models.User
:class:`~django.contrib.auth.models.User` objects have two many-to-many
fields: ``groups`` and ``user_permissions``.
:class:`~django.contrib.auth.models.User` objects can access their related
objects in the same way as any other :doc:`Django model
</topics/db/models>`:
.. code-block:: python
myuser.groups = [group_list]
myuser.groups.add(group, group, ...)
myuser.groups.remove(group, group, ...)
myuser.groups.clear()
myuser.user_permissions = [permission_list]
myuser.user_permissions.add(permission, permission, ...)
myuser.user_permissions.remove(permission, permission, ...)
myuser.user_permissions.clear()
In addition to those automatic API methods,
:class:`~django.contrib.auth.models.User` objects have the following custom
methods:
.. method:: models.User.is_anonymous()
Always returns ``False``. This is a way of differentiating
:class:`~django.contrib.auth.models.User` and
:class:`~django.contrib.auth.models.AnonymousUser` objects.
Generally, you should prefer using
:meth:`~django.contrib.auth.models.User.is_authenticated()` to this
method.
.. method:: models.User.is_authenticated()
Always returns ``True``. This is a way to tell if the user has been
authenticated. This does not imply any permissions, and doesn't check
if the user is active - it only indicates that the user has provided a
valid username and password.
.. method:: models.User.get_full_name()
Returns the :attr:`~django.contrib.auth.models.User.first_name` plus
the :attr:`~django.contrib.auth.models.User.last_name`, with a space in
between.
.. method:: models.User.set_password(raw_password)
Sets the user's password to the given raw string, taking care of the
password hashing. Doesn't save the
:class:`~django.contrib.auth.models.User` object.
.. method:: models.User.check_password(raw_password)
Returns ``True`` if the given raw string is the correct password for
the user. (This takes care of the password hashing in making the
comparison.)
.. method:: models.User.set_unusable_password()
Marks the user as having no password set. This isn't the same as
having a blank string for a password.
:meth:`~django.contrib.auth.models.User.check_password()` for this user
will never return ``True``. Doesn't save the
:class:`~django.contrib.auth.models.User` object.
You may need this if authentication for your application takes place
against an existing external source such as an LDAP directory.
.. method:: models.User.has_usable_password()
Returns ``False`` if
:meth:`~django.contrib.auth.models.User.set_unusable_password()` has
been called for this user.
.. method:: models.User.get_group_permissions(obj=None)
Returns a set of permission strings that the user has, through his/her
groups.
If ``obj`` is passed in, only returns the group permissions for
this specific object.
.. method:: models.User.get_all_permissions(obj=None)
Returns a set of permission strings that the user has, both through
group and user permissions.
If ``obj`` is passed in, only returns the permissions for this
specific object.
.. method:: models.User.has_perm(perm, obj=None)
Returns ``True`` if the user has the specified permission, where perm is
in the format ``"<app label>.<permission codename>"``. (see
`permissions`_ section below). If the user is inactive, this method will
always return ``False``.
If ``obj`` is passed in, this method won't check for a permission for
the model, but for this specific object.
.. method:: models.User.has_perms(perm_list, obj=None)
Returns ``True`` if the user has each of the specified permissions,
where each perm is in the format
``"<app label>.<permission codename>"``. If the user is inactive,
this method will always return ``False``.
If ``obj`` is passed in, this method won't check for permissions for
the model, but for the specific object.
.. method:: models.User.has_module_perms(package_name)
Returns ``True`` if the user has any permissions in the given package
(the Django app label). If the user is inactive, this method will
always return ``False``.
.. method:: models.User.email_user(subject, message, from_email=None)
Sends an email to the user. If
:attr:`~django.contrib.auth.models.User.from_email` is ``None``, Django
uses the :setting:`DEFAULT_FROM_EMAIL`.
.. method:: models.User.get_profile()
.. deprecated:: 1.5
With the introduction of :ref:`custom User models <auth-custom-user>`,
the use of :setting:`AUTH_PROFILE_MODULE` to define a single profile
model is no longer supported. See the
:doc:`Django 1.5 release notes</releases/1.5>` for more information.
Returns a site-specific profile for this user. Raises
:exc:`django.contrib.auth.models.SiteProfileNotAvailable` if the
current site doesn't allow profiles, or
:exc:`django.core.exceptions.ObjectDoesNotExist` if the user does not
have a profile. For information on how to define a site-specific user
profile, see the section on `storing additional user information`_ below.
.. _storing additional user information: #storing-additional-information-about-users
Manager functions
~~~~~~~~~~~~~~~~~
.. class:: models.UserManager
The :class:`~django.contrib.auth.models.User` model has a custom manager
that has the following helper functions:
.. method:: models.UserManager.create_user(username, email=None, password=None)
.. versionchanged:: 1.4
The ``email`` parameter was made optional. The username
parameter is now checked for emptiness and raises a
:exc:`ValueError` in case of a negative result.
Creates, saves and returns a :class:`~django.contrib.auth.models.User`.
The :attr:`~django.contrib.auth.models.User.username` and
:attr:`~django.contrib.auth.models.User.password` are set as given. The
domain portion of :attr:`~django.contrib.auth.models.User.email` is
automatically converted to lowercase, and the returned
:class:`~django.contrib.auth.models.User` object will have
:attr:`~models.User.is_active` set to ``True``.
If no password is provided,
:meth:`~django.contrib.auth.models.User.set_unusable_password()` will
be called.
See `Creating users`_ for example usage.
.. method:: models.UserManager.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
Returns a random password with the given length and given string of
allowed characters. (Note that the default value of ``allowed_chars``
doesn't contain letters that can cause user confusion, including:
* ``i``, ``l``, ``I``, and ``1`` (lowercase letter i, lowercase
letter L, uppercase letter i, and the number one)
* ``o``, ``O``, and ``0`` (uppercase letter o, lowercase letter o,
and zero)
Basic usage
-----------
.. _topics-auth-creating-users:
Creating users
~~~~~~~~~~~~~~
The most basic way to create users is to use the
:meth:`~django.contrib.auth.models.UserManager.create_user` helper function
that comes with Django::
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
# At this point, user is a User object that has already been saved
# to the database. You can continue to change its attributes
# if you want to change other fields.
>>> user.is_staff = True
>>> user.save()
You can also create users using the Django admin site. Assuming you've enabled
the admin site and hooked it to the URL ``/admin/``, the "Add user" page is at
``/admin/auth/user/add/``. You should also see a link to "Users" in the "Auth"
section of the main admin index page. The "Add user" admin page is different
than standard admin pages in that it requires you to choose a username and
password before allowing you to edit the rest of the user's fields.
Also note: if you want your own user account to be able to create users using
the Django admin site, you'll need to give yourself permission to add users
*and* change users (i.e., the "Add user" and "Change user" permissions). If
your account has permission to add users but not to change them, you won't be
able to add users. Why? Because if you have permission to add users, you have
the power to create superusers, which can then, in turn, change other users. So
Django requires add *and* change permissions as a slight security measure.
Changing passwords
~~~~~~~~~~~~~~~~~~
:djadmin:`manage.py changepassword *username* <changepassword>` offers a method
of changing a User's password from the command line. It prompts you to
change the password of a given user which you must enter twice. If
they both match, the new password will be changed immediately. If you
do not supply a user, the command will attempt to change the password
whose username matches the current user.
You can also change a password programmatically, using
:meth:`~django.contrib.auth.models.User.set_password()`:
.. code-block:: python
>>> from django.contrib.auth.models import User
>>> u = User.objects.get(username__exact='john')
>>> u.set_password('new password')
>>> u.save()
Don't set the :attr:`~django.contrib.auth.models.User.password` attribute
directly unless you know what you're doing. This is explained in the next
section.
.. _auth_password_storage:
How Django stores passwords
---------------------------
.. versionadded:: 1.4
Django 1.4 introduces a new flexible password storage system and uses
PBKDF2 by default. Previous versions of Django used SHA1, and other
algorithms couldn't be chosen.
The :attr:`~django.contrib.auth.models.User.password` attribute of a
:class:`~django.contrib.auth.models.User` object is a string in this format::
algorithm$hash
That's a storage algorithm, and hash, separated by the dollar-sign
character. The algorithm is one of a number of one way hashing or password
storage algorithms Django can use; see below. The hash is the result of the one-
way function.
By default, Django uses the PBKDF2_ algorithm with a SHA256 hash, a
password stretching mechanism recommended by NIST_. This should be
sufficient for most users: it's quite secure, requiring massive
amounts of computing time to break.
However, depending on your requirements, you may choose a different
algorithm, or even use a custom algorithm to match your specific
security situation. Again, most users shouldn't need to do this -- if
you're not sure, you probably don't. If you do, please read on:
Django chooses the an algorithm by consulting the :setting:`PASSWORD_HASHERS`
setting. This is a list of hashing algorithm classes that this Django
installation supports. The first entry in this list (that is,
``settings.PASSWORD_HASHERS[0]``) will be used to store passwords, and all the
other entries are valid hashers that can be used to check existing passwords.
This means that if you want to use a different algorithm, you'll need to modify
:setting:`PASSWORD_HASHERS` to list your prefered algorithm first in the list.
The default for :setting:`PASSWORD_HASHERS` is::
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.CryptPasswordHasher',
)
This means that Django will use PBKDF2_ to store all passwords, but will support
checking passwords stored with PBKDF2SHA1, bcrypt_, SHA1_, etc. The next few
sections describe a couple of common ways advanced users may want to modify this
setting.
.. _bcrypt_usage:
Using bcrypt with Django
~~~~~~~~~~~~~~~~~~~~~~~~
Bcrypt_ is a popular password storage algorithm that's specifically designed
for long-term password storage. It's not the default used by Django since it
requires the use of third-party libraries, but since many people may want to
use it Django supports bcrypt with minimal effort.
To use Bcrypt as your default storage algorithm, do the following:
1. Install the `py-bcrypt`_ library (probably by running ``sudo pip install
py-bcrypt``, or downloading the library and installing it with ``python
setup.py install``).
2. Modify :setting:`PASSWORD_HASHERS` to list ``BCryptPasswordHasher``
first. That is, in your settings file, you'd put::
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.CryptPasswordHasher',
)
(You need to keep the other entries in this list, or else Django won't
be able to upgrade passwords; see below).
That's it -- now your Django install will use Bcrypt as the default storage
algorithm.
.. admonition:: Other bcrypt implementations
There are several other implementations that allow bcrypt to be
used with Django. Django's bcrypt support is NOT directly
compatible with these. To upgrade, you will need to modify the
hashes in your database to be in the form `bcrypt$(raw bcrypt
output)`. For example:
`bcrypt$$2a$12$NT0I31Sa7ihGEWpka9ASYrEFkhuTNeBQ2xfZskIiiJeyFXhRgS.Sy`.
Increasing the work factor
~~~~~~~~~~~~~~~~~~~~~~~~~~
The PBKDF2 and bcrypt algorithms use a number of iterations or rounds of
hashing. This deliberately slows down attackers, making attacks against hashed
passwords harder. However, as computing power increases, the number of
iterations needs to be increased. We've chosen a reasonable default (and will
increase it with each release of Django), but you may wish to tune it up or
down, depending on your security needs and available processing power. To do so,
you'll subclass the appropriate algorithm and override the ``iterations``
parameters. For example, to increase the number of iterations used by the
default PBKDF2 algorithm:
1. Create a subclass of ``django.contrib.auth.hashers.PBKDF2PasswordHasher``::
from django.contrib.auth.hashers import PBKDF2PasswordHasher
class MyPBKDF2PasswordHasher(PBKDF2PasswordHasher):
"""
A subclass of PBKDF2PasswordHasher that uses 100 times more iterations.
"""
iterations = PBKDF2PasswordHasher.iterations * 100
Save this somewhere in your project. For example, you might put this in
a file like ``myproject/hashers.py``.
2. Add your new hasher as the first entry in :setting:`PASSWORD_HASHERS`::
PASSWORD_HASHERS = (
'myproject.hashers.MyPBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.CryptPasswordHasher',
)
That's it -- now your Django install will use more iterations when it
stores passwords using PBKDF2.
Password upgrading
~~~~~~~~~~~~~~~~~~
When users log in, if their passwords are stored with anything other than
the preferred algorithm, Django will automatically upgrade the algorithm
to the preferred one. This means that old installs of Django will get
automatically more secure as users log in, and it also means that you
can switch to new (and better) storage algorithms as they get invented.
However, Django can only upgrade passwords that use algorithms mentioned in
:setting:`PASSWORD_HASHERS`, so as you upgrade to new systems you should make
sure never to *remove* entries from this list. If you do, users using un-
mentioned algorithms won't be able to upgrade.
.. _sha1: http://en.wikipedia.org/wiki/SHA1
.. _pbkdf2: http://en.wikipedia.org/wiki/PBKDF2
.. _nist: http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
.. _bcrypt: http://en.wikipedia.org/wiki/Bcrypt
.. _py-bcrypt: http://pypi.python.org/pypi/py-bcrypt/
Anonymous users
---------------
.. class:: models.AnonymousUser
:class:`django.contrib.auth.models.AnonymousUser` is a class that
implements the :class:`django.contrib.auth.models.User` interface, with
these differences:
* :attr:`~django.contrib.auth.models.User.id` is always ``None``.
* :attr:`~django.contrib.auth.models.User.is_staff` and
:attr:`~django.contrib.auth.models.User.is_superuser` are always
``False``.
* :attr:`~django.contrib.auth.models.User.is_active` is always ``False``.
* :attr:`~django.contrib.auth.models.User.groups` and
:attr:`~django.contrib.auth.models.User.user_permissions` are always
empty.
* :meth:`~django.contrib.auth.models.User.is_anonymous()` returns ``True``
instead of ``False``.
* :meth:`~django.contrib.auth.models.User.is_authenticated()` returns
``False`` instead of ``True``.
* :meth:`~django.contrib.auth.models.User.set_password()`,
:meth:`~django.contrib.auth.models.User.check_password()`,
:meth:`~django.contrib.auth.models.User.save()`,
:meth:`~django.contrib.auth.models.User.delete()`,
:meth:`~django.contrib.auth.models.User.set_groups()` and
:meth:`~django.contrib.auth.models.User.set_permissions()` raise
:exc:`NotImplementedError`.
In practice, you probably won't need to use
:class:`~django.contrib.auth.models.AnonymousUser` objects on your own, but
they're used by Web requests, as explained in the next section.
.. _topics-auth-creating-superusers:
Creating superusers
-------------------
:djadmin:`manage.py syncdb <syncdb>` prompts you to create a superuser the
first time you run it after adding ``'django.contrib.auth'`` to your
:setting:`INSTALLED_APPS`. If you need to create a superuser at a later date,
you can use a command line utility::
manage.py createsuperuser --username=joe --email=joe@example.com
You will be prompted for a password. After you enter one, the user will be
created immediately. If you leave off the :djadminopt:`--username` or the
:djadminopt:`--email` options, it will prompt you for those values.
If you're using an older release of Django, the old way of creating a superuser
on the command line still works::
python /path/to/django/contrib/auth/create_superuser.py
...where :file:`/path/to` is the path to the Django codebase on your
filesystem. The ``manage.py`` command is preferred because it figures out the
correct path and environment for you.
.. _auth-profiles:
Storing additional information about users
------------------------------------------
.. deprecated:: 1.5
With the introduction of :ref:`custom User models <auth-custom-user>`,
the use of :setting:`AUTH_PROFILE_MODULE` to define a single profile
model is no longer supported. See the
:doc:`Django 1.5 release notes</releases/1.5>` for more information.
If you'd like to store additional information related to your users, Django
provides a method to specify a site-specific related model -- termed a "user
profile" -- for this purpose.
To make use of this feature, define a model with fields for the
additional information you'd like to store, or additional methods
you'd like to have available, and also add a
:class:`~django.db.models.Field.OneToOneField` named ``user`` from your model
to the :class:`~django.contrib.auth.models.User` model. This will ensure only
one instance of your model can be created for each
:class:`~django.contrib.auth.models.User`. For example::
from django.contrib.auth.models import User
class UserProfile(models.Model):
# This field is required.
user = models.OneToOneField(User)
# Other fields here
accepted_eula = models.BooleanField()
favorite_animal = models.CharField(max_length=20, default="Dragons.")
To indicate that this model is the user profile model for a given site, fill in
the setting :setting:`AUTH_PROFILE_MODULE` with a string consisting of the
following items, separated by a dot:
1. The name of the application (case sensitive) in which the user
profile model is defined (in other words, the
name which was passed to :djadmin:`manage.py startapp <startapp>` to create
the application).
2. The name of the model (not case sensitive) class.
For example, if the profile model was a class named ``UserProfile`` and was
defined inside an application named ``accounts``, the appropriate setting would
be::
AUTH_PROFILE_MODULE = 'accounts.UserProfile'
When a user profile model has been defined and specified in this manner, each
:class:`~django.contrib.auth.models.User` object will have a method --
:class:`~django.contrib.auth.models.User.get_profile()` -- which returns the
instance of the user profile model associated with that
:class:`~django.contrib.auth.models.User`.
The method :class:`~django.contrib.auth.models.User.get_profile()`
does not create a profile if one does not exist. You need to register a handler
for the User model's :attr:`django.db.models.signals.post_save` signal and, in
the handler, if ``created`` is ``True``, create the associated user profile::
# in models.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save
# definition of UserProfile from above
# ...
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
.. seealso:: :doc:`/topics/signals` for more information on Django's signal
dispatcher.
Adding UserProfile fields to the admin
--------------------------------------
To add the UserProfile fields to the user page in the admin, define an
:class:`~django.contrib.admin.InlineModelAdmin` (for this example, we'll use a
:class:`~django.contrib.admin.StackedInline`) in your app's ``admin.py`` and
add it to a ``UserAdmin`` class which is registered with the
:class:`~django.contrib.auth.models.User` class::
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from my_user_profile_app.models import UserProfile
# Define an inline admin descriptor for UserProfile model
# which acts a bit like a singleton
class UserProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
verbose_name_plural = 'profile'
# Define a new User admin
class UserAdmin(UserAdmin):
inlines = (UserProfileInline, )
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
Authentication in Web requests
==============================
Until now, this document has dealt with the low-level APIs for manipulating
authentication-related objects. On a higher level, Django can hook this
authentication framework into its system of
:class:`request objects <django.http.HttpRequest>`.
First, install the
:class:`~django.contrib.sessions.middleware.SessionMiddleware` and
:class:`~django.contrib.auth.middleware.AuthenticationMiddleware`
middlewares by adding them to your :setting:`MIDDLEWARE_CLASSES` setting. See
the :doc:`session documentation </topics/http/sessions>` for more information.
Once you have those middlewares installed, you'll be able to access
:attr:`request.user <django.http.HttpRequest.user>` in views.
:attr:`request.user <django.http.HttpRequest.user>` will give you a
:class:`~django.contrib.auth.models.User` object representing the currently
logged-in user. If a user isn't currently logged in,
:attr:`request.user <django.http.HttpRequest.user>` will be set to an instance
of :class:`~django.contrib.auth.models.AnonymousUser` (see the previous
section). You can tell them apart with
:meth:`~django.contrib.auth.models.User.is_authenticated()`, like so::
if request.user.is_authenticated():
# Do something for authenticated users.
else:
# Do something for anonymous users.
.. _how-to-log-a-user-in:
How to log a user in
--------------------
Django provides two functions in :mod:`django.contrib.auth`:
:func:`~django.contrib.auth.authenticate()` and
:func:`~django.contrib.auth.login()`.
.. function:: authenticate()
To authenticate a given username and password, use
:func:`~django.contrib.auth.authenticate()`. It takes two keyword
arguments, ``username`` and ``password``, and it returns a
:class:`~django.contrib.auth.models.User` object if the password is valid
for the given username. If the password is invalid,
:func:`~django.contrib.auth.authenticate()` returns ``None``. Example::
from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
if user is not None:
if user.is_active:
print("You provided a correct username and password!")
else:
print("Your account has been disabled!")
else:
print("Your username and password were incorrect.")
.. function:: login()
To log a user in, in a view, use :func:`~django.contrib.auth.login()`. It
takes an :class:`~django.http.HttpRequest` object and a
:class:`~django.contrib.auth.models.User` object.
:func:`~django.contrib.auth.login()` saves the user's ID in the session,
using Django's session framework, so, as mentioned above, you'll need to
make sure to have the session middleware installed.
Note that data set during the anonymous session is retained when the user
logs in.
This example shows how you might use both
:func:`~django.contrib.auth.authenticate()` and
:func:`~django.contrib.auth.login()`::
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
# Redirect to a success page.
else:
# Return a 'disabled account' error message
else:
# Return an 'invalid login' error message.
.. admonition:: Calling ``authenticate()`` first
When you're manually logging a user in, you *must* call
:func:`~django.contrib.auth.authenticate()` before you call
:func:`~django.contrib.auth.login()`.
:func:`~django.contrib.auth.authenticate()`
sets an attribute on the :class:`~django.contrib.auth.models.User` noting
which authentication backend successfully authenticated that user (see the
`backends documentation`_ for details), and this information is needed
later during the login process.
.. _backends documentation: #other-authentication-sources
Manually managing a user's password
-----------------------------------
.. currentmodule:: django.contrib.auth.hashers
.. versionadded:: 1.4
The :mod:`django.contrib.auth.hashers` module provides a set of functions
to create and validate hashed password. You can use them independently
from the ``User`` model.
.. function:: check_password(password, encoded)
.. versionadded:: 1.4
If you'd like to manually authenticate a user by comparing a plain-text
password to the hashed password in the database, use the convenience
function :func:`django.contrib.auth.hashers.check_password`. It takes two
arguments: the plain-text password to check, and the full value of a
user's ``password`` field in the database to check against, and returns
``True`` if they match, ``False`` otherwise.
.. function:: make_password(password[, salt, hashers])
.. versionadded:: 1.4
Creates a hashed password in the format used by this application. It takes
one mandatory argument: the password in plain-text. Optionally, you can
provide a salt and a hashing algorithm to use, if you don't want to use the
defaults (first entry of ``PASSWORD_HASHERS`` setting).
Currently supported algorithms are: ``'pbkdf2_sha256'``, ``'pbkdf2_sha1'``,
``'bcrypt'`` (see :ref:`bcrypt_usage`), ``'sha1'``, ``'md5'``,
``'unsalted_md5'`` (only for backward compatibility) and ``'crypt'``
if you have the ``crypt`` library installed. If the password argument is
``None``, an unusable password is returned (a one that will be never
accepted by :func:`django.contrib.auth.hashers.check_password`).
.. function:: is_password_usable(encoded_password)
.. versionadded:: 1.4
Checks if the given string is a hashed password that has a chance
of being verified against :func:`django.contrib.auth.hashers.check_password`.
How to log a user out
---------------------
.. currentmodule:: django.contrib.auth
.. function:: logout()
To log out a user who has been logged in via
:func:`django.contrib.auth.login()`, use
:func:`django.contrib.auth.logout()` within your view. It takes an
:class:`~django.http.HttpRequest` object and has no return value.
Example::
from django.contrib.auth import logout
def logout_view(request):
logout(request)
# Redirect to a success page.
Note that :func:`~django.contrib.auth.logout()` doesn't throw any errors if
the user wasn't logged in.
When you call :func:`~django.contrib.auth.logout()`, the session data for
the current request is completely cleaned out. All existing data is
removed. This is to prevent another person from using the same Web browser
to log in and have access to the previous user's session data. If you want
to put anything into the session that will be available to the user
immediately after logging out, do that *after* calling
:func:`django.contrib.auth.logout()`.
.. _topics-auth-signals:
Login and logout signals
------------------------
.. versionadded:: 1.3
The auth framework uses two :doc:`signals </topics/signals>` that can be used
for notification when a user logs in or out.
.. data:: django.contrib.auth.signals.user_logged_in
Sent when a user logs in successfully.
Arguments sent with this signal:
``sender``
As above: the class of the user that just logged in.
``request``
The current :class:`~django.http.HttpRequest` instance.
``user``
The user instance that just logged in.
.. data:: django.contrib.auth.signals.user_logged_out
Sent when the logout method is called.
``sender``
As above: the class of the user that just logged out or ``None``
if the user was not authenticated.
``request``
The current :class:`~django.http.HttpRequest` instance.
``user``
The user instance that just logged out or ``None`` if the
user was not authenticated.
Limiting access to logged-in users
----------------------------------
The raw way
~~~~~~~~~~~
The simple, raw way to limit access to pages is to check
:meth:`request.user.is_authenticated()
<django.contrib.auth.models.User.is_authenticated()>` and either redirect to a
login page::
from django.http import HttpResponseRedirect
def my_view(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/?next=%s' % request.path)
# ...
...or display an error message::
def my_view(request):
if not request.user.is_authenticated():
return render_to_response('myapp/login_error.html')
# ...
The login_required decorator
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. function:: decorators.login_required([redirect_field_name=REDIRECT_FIELD_NAME, login_url=None])
As a shortcut, you can use the convenient
:func:`~django.contrib.auth.decorators.login_required` decorator::
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
...
:func:`~django.contrib.auth.decorators.login_required` does the following:
* If the user isn't logged in, redirect to
:setting:`settings.LOGIN_URL <LOGIN_URL>`, passing the current absolute
path in the query string. Example: ``/accounts/login/?next=/polls/3/``.
* If the user is logged in, execute the view normally. The view code is
free to assume the user is logged in.
By default, the path that the user should be redirected to upon
successful authentication is stored in a query string parameter called
``"next"``. If you would prefer to use a different name for this parameter,
:func:`~django.contrib.auth.decorators.login_required` takes an
optional ``redirect_field_name`` parameter::
from django.contrib.auth.decorators import login_required
@login_required(redirect_field_name='my_redirect_field')
def my_view(request):
...
Note that if you provide a value to ``redirect_field_name``, you will most
likely need to customize your login template as well, since the template
context variable which stores the redirect path will use the value of
``redirect_field_name`` as its key rather than ``"next"`` (the default).
.. versionadded:: 1.3
:func:`~django.contrib.auth.decorators.login_required` also takes an
optional ``login_url`` parameter. Example::
from django.contrib.auth.decorators import login_required
@login_required(login_url='/accounts/login/')
def my_view(request):
...
Note that if you don't specify the ``login_url`` parameter, you'll need to map
the appropriate Django view to :setting:`settings.LOGIN_URL <LOGIN_URL>`. For
example, using the defaults, add the following line to your URLconf::
(r'^accounts/login/$', 'django.contrib.auth.views.login'),
.. versionchanged:: 1.5
As of version 1.5 :setting:`settings.LOGIN_URL <LOGIN_URL>` now also accepts
view function names and :ref:`named URL patterns <naming-url-patterns>`.
This allows you to freely remap your login view within your URLconf
without having to update the setting.
.. function:: views.login(request, [template_name, redirect_field_name, authentication_form])