>>> fromdjango.contrib.auth.modelsimportUser>>> 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()

The PDKDF2 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 PDKDF2 algorithm:

Create a subclass of django.contrib.auth.hashers.PBKDF2PasswordHasher:

fromdjango.contrib.auth.hashersimportPBKDF2PasswordHasherclassMyPBKDF2PasswordHasher(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.

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
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.

manage.pysyncdb prompts you to create a superuser the
first time you run it after adding 'django.contrib.auth' to your
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 --username or the
--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 /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.

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
OneToOneField named user from your model
to the User model. This will ensure only
one instance of your model can be created for each
User. For example:

fromdjango.contrib.auth.modelsimportUserclassUserProfile(models.Model):# This field is required.user=models.OneToOneField(User)# Other fields hereaccepted_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 AUTH_PROFILE_MODULE with a string consisting of the
following items, separated by a dot:

The name of the application (case sensitive) in which the user
profile model is defined (in other words, the
name which was passed to manage.pystartapp to create
the application).

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
User object will have a method –
get_profile() – which returns the
instance of the user profile model associated with that
User.

The method get_profile()
does not create a profile if one does not exist. You need to register a handler
for the User model’s django.db.models.signals.post_save signal and, in
the handler, if created is True, create the associated user profile:

# in models.pyfromdjango.contrib.auth.modelsimportUserfromdjango.db.models.signalsimportpost_save# definition of UserProfile from above# ...defcreate_user_profile(sender,instance,created,**kwargs):ifcreated:UserProfile.objects.create(user=instance)post_save.connect(create_user_profile,sender=User)

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
requestobjects.

To authenticate a given username and password, use
authenticate(). It takes two keyword
arguments, username and password, and it returns a
User object if the password is valid
for the given username. If the password is invalid,
authenticate() returns None. Example:

fromdjango.contrib.authimportauthenticateuser=authenticate(username='john',password='secret')ifuserisnotNone:ifuser.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."

To log a user in, in a view, use login(). It
takes an HttpRequest object and a
User object.
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.

When you’re manually logging a user in, you must call
authenticate() before you call
login().
authenticate()
sets an attribute on the 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.

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 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.

Creates a hashed password in the format used by this application. It takes
two arguments: hashing algorithm to use and the password in plain-text.
Currently supported algorithms are: 'sha1', 'md5' and 'crypt'
if you have the crypt library installed. If the second argument is
None, an unusable password is returned (a one that will be never
accepted by django.contrib.auth.hashers.check_password()).

fromdjango.contrib.authimportlogoutdeflogout_view(request):logout(request)# Redirect to a success page.

Note that logout() doesn’t throw any errors if
the user wasn’t logged in.

When you call 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
django.contrib.auth.logout().

If the user isn’t logged in, redirect to
settings.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,
login_required() takes an
optional redirect_field_name parameter:

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).

If called via GET, it displays a login form that POSTs to the
same URL. More on this in a bit.

If called via POST, it tries to log the user in. If login is
successful, the view redirects to the URL specified in next. If
next isn’t provided, it redirects to
settings.LOGIN_REDIRECT_URL (which
defaults to /accounts/profile/). If login isn’t successful, it
redisplays the login form.

It’s your responsibility to provide the login form in a template called
registration/login.html by default. This template gets passed four
template context variables:

next: The URL to redirect to after successful login. This may
contain a query string, too.

site: The current Site,
according to the SITE_ID setting. If you don’t have the
site framework installed, this will be set to an instance of
RequestSite, which derives the
site name and domain from the current
HttpRequest.

If you’d prefer not to call the template registration/login.html,
you can pass the template_name parameter via the extra arguments to
the view in your URLconf. For example, this URLconf line would use
myapp/login.html instead:

If you are using alternate authentication (see
Other authentication sources) you can pass a custom authentication form
to the login view via the authentication_form parameter. This form must
accept a request keyword argument in its __init__ method, and
provide a get_user method which returns the authenticated user object
(this method is only ever called after successful form validation).

template_name: The full name of a template to display after
logging the user out. Defaults to
registration/logged_out.html if no argument is supplied.

redirect_field_name: The name of a GET field containing the
URL to redirect to after log out. Overrides next_page if the given
GET parameter is passed.

Template context:

title: The string “Logged out”, localized.

site: The current Site,
according to the SITE_ID setting. If you don’t have the
site framework installed, this will be set to an instance of
RequestSite, which derives the
site name and domain from the current
HttpRequest.

If you don’t want to use the built-in views, but want the convenience of not
having to write forms for this functionality, the authentication system
provides several built-in forms located in django.contrib.auth.forms:

We’re using this particular test as a relatively simple example. However,
if you just want to test whether a permission is available to a user, you
can use the permission_required()
decorator, described later in this document.

user_passes_test() takes a required
argument: a callable that takes a
User object and returns True if
the user is allowed to view the page. Note that
user_passes_test() does not
automatically check that the User is
not anonymous.

It’s a relatively common task to check whether a user has a particular
permission. For that reason, Django provides a shortcut for that case: the
permission_required() decorator.
Using this decorator, the earlier example can be written as:

Django comes with a simple permissions system. It provides a way to assign
permissions to specific users and groups of users.

It’s used by the Django admin site, but you’re welcome to use it in your own
code.

The Django admin site uses permissions as follows:

Access to view the “add” form and add an object is limited to users with
the “add” permission for that type of object.

Access to view the change list, view the “change” form and change an
object is limited to users with the “change” permission for that type of
object.

Access to delete an object is limited to users with the “delete”
permission for that type of object.

Permissions are set globally per type of object, not per specific object
instance. For example, it’s possible to say “Mary may change news stories,” but
it’s not currently possible to say “Mary may change news stories, but only the
ones she created herself” or “Mary may only change news stories that have a
certain status, publication date or ID.” The latter functionality is something
Django developers are currently discussing.

When django.contrib.auth is listed in your INSTALLED_APPS
setting, it will ensure that three default permissions – add, change and
delete – are created for each Django model defined in one of your installed
applications.

These permissions will be created when you run manage.pysyncdb; the first time you run syncdb after adding
django.contrib.auth to INSTALLED_APPS, the default permissions
will be created for all previously-installed models, as well as for any new
models being installed at that time. Afterward, it will create default
permissions for new models each time you run manage.pysyncdb.

Assuming you have an application with an
app_labelfoo and a model named Bar,
to test for basic permissions you should use:

This example Task model creates three custom permissions, i.e., actions users
can or cannot do with Task instances, specific to your application:

classTask(models.Model):...classMeta:permissions=(("view_task","Can see available tasks"),("change_task_status","Can change the status of tasks"),("close_task","Can remove a task by setting its status as closed"),)

The only thing this does is create those extra permissions when you run
manage.pysyncdb. Your code is in charge of checking the
value of these permissions when an user is trying to access the functionality
provided by the application (viewing tasks, changing the status of tasks,
closing tasks.) Continuing the above example, the following checks if a user may
view tasks:

The currently logged-in user and his/her permissions are made available in the
template context when you use
RequestContext.

Technicality

Technically, these variables are only made available in the template context
if you use RequestContextand your
TEMPLATE_CONTEXT_PROCESSORS setting contains
"django.contrib.auth.context_processors.auth", which is default. For
more, see the RequestContext docs.

The currently logged-in user’s permissions are stored in the template variable
{{perms}}. This is an instance of
django.contrib.auth.context_processors.PermWrapper, which is a
template-friendly proxy of permissions.

In the {{perms}} object, single-attribute lookup is a proxy to
User.has_module_perms.
This example would display True if the logged-in user had any permissions
in the foo app:

{{perms.foo}}

Two-level-attribute lookup is a proxy to
User.has_perm. This example
would display True if the logged-in user had the permission
foo.can_vote:

{{perms.foo.can_vote}}

Thus, you can check permissions in template {%if%} statements:

{%ifperms.foo%}<p>You have permission to do something in the foo app.</p>{%ifperms.foo.can_vote%}<p>You can vote!</p>{%endif%}{%ifperms.foo.can_drive%}<p>You can drive!</p>{%endif%}{%else%}<p>You don't have permission to do anything in the foo app.</p>{%endif%}

Groups are a generic way of categorizing users so you can apply permissions, or
some other label, to those users. A user can belong to any number of groups.

A user in a group automatically has the permissions granted to that group. For
example, if the group Siteeditors has the permission
can_edit_home_page, any user in that group will have that permission.

Beyond permissions, groups are a convenient way to categorize users to give
them some label, or extended functionality. For example, you could create a
group 'Specialusers', and you could write code that could, say, give them
access to a members-only portion of your site, or send them members-only email
messages.

The authentication that comes with Django is good enough for most common cases,
but you may have the need to hook into another authentication source – that
is, another source of usernames and passwords or authentication methods.

For example, your company may already have an LDAP setup that stores a username
and password for every employee. It’d be a hassle for both the network
administrator and the users themselves if users had separate accounts in LDAP
and the Django-based applications.

So, to handle situations like this, the Django authentication system lets you
plug in other authentication sources. You can override Django’s default
database-based scheme, or you can use the default system in tandem with other
systems.

Behind the scenes, Django maintains a list of “authentication backends” that it
checks for authentication. When somebody calls
django.contrib.auth.authenticate() – as described in How to log
a user in above – Django tries authenticating across
all of its authentication backends. If the first authentication method fails,
Django tries the second one, and so on, until all backends have been attempted.

The list of authentication backends to use is specified in the
AUTHENTICATION_BACKENDS setting. This should be a tuple of Python
path names that point to Python classes that know how to authenticate. These
classes can be anywhere on your Python path.

The order of AUTHENTICATION_BACKENDS matters, so if the same
username and password is valid in multiple backends, Django will stop
processing at the first positive match.

Примечание

Once a user has authenticated, Django stores which backend was used to
authenticate the user in the user’s session, and re-uses the same backend
for the duration of that session whenever access to the currently
authenticated user is needed. This effectively means that authentication
sources are cached on a per-session basis, so if you change
AUTHENTICATION_BACKENDS, you’ll need to clear out session data if
you need to force users to re-authenticate using different methods. A simple
way to do that is simply to execute Session.objects.all().delete().

Either way, authenticate should check the credentials it gets, and it
should return a User object that matches those credentials, if the
credentials are valid. If they’re not valid, it should return None.

The Django admin system is tightly coupled to the Django User object
described at the beginning of this document. For now, the best way to deal with
this is to create a Django User object for each user that exists for your
backend (e.g., in your LDAP directory, your external SQL database, etc.) You
can either write a script to do this in advance, or your authenticate
method can do it the first time a user logs in.

Here’s an example backend that authenticates against a username and password
variable defined in your settings.py file and creates a Django User
object the first time a user authenticates:

fromdjango.confimportsettingsfromdjango.contrib.auth.modelsimportUser,check_passwordclassSettingsBackend(object):""" Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD. Use the login name, and a hash of the password. For example: ADMIN_LOGIN = 'admin' ADMIN_PASSWORD = 'sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de' """supports_inactive_user=Falsedefauthenticate(self,username=None,password=None):login_valid=(settings.ADMIN_LOGIN==username)pwd_valid=check_password(password,settings.ADMIN_PASSWORD)iflogin_validandpwd_valid:try:user=User.objects.get(username=username)exceptUser.DoesNotExist:# Create a new user. Note that we can set password# to anything, because it won't be checked; the password# from settings.py will.user=User(username=username,password='get from settings.py')user.is_staff=Trueuser.is_superuser=Trueuser.save()returnuserreturnNonedefget_user(self,user_id):try:returnUser.objects.get(pk=user_id)exceptUser.DoesNotExist:returnNone

This gives full permissions to the user granted access in the above example.
Notice that the backend auth functions all take the user object as an argument,
and they also accept the same arguments given to the associated
django.contrib.auth.models.User functions.

A full authorization implementation can be found in
django/contrib/auth/backends.py, which is the default backend and queries
the auth_permission table most of the time.

An anonymous user is one that is not authenticated i.e. they have provided no
valid authentication details. However, that does not necessarily mean they are
not authorized to do anything. At the most basic level, most Web sites
authorize anonymous users to browse most of the site, and many allow anonymous
posting of comments etc.

Django’s permission framework does not have a place to store permissions for
anonymous users. However, it has a foundation that allows custom authentication
backends to specify authorization for anonymous users. This is especially useful
for the authors of re-usable apps, who can delegate all questions of authorization
to the auth backend, rather than needing settings, for example, to control
anonymous access.

An inactive user is a one that is authenticated but has its attribute
is_active set to False. However this does not mean they are not
authorized to do anything. For example they are allowed to activate their
account.

The support for anonymous users in the permission system allows for
anonymous users to have permissions to do something while inactive
authenticated users do not.

To enable this on your own backend, you must set the class attribute
supports_inactive_user to True.

A nonexisting supports_inactive_user attribute will raise a
PendingDeprecationWarning if used in Django 1.3. In Django 1.4, this
warning will be updated to a DeprecationWarning which will be displayed
loudly. Additionally supports_inactive_user will be set to False.
Django 1.5 will assume that every backend supports inactive users being
passed to the authorization methods.

Django’s permission framework has a foundation for object permissions, though
there is no implementation for it in the core. That means that checking for
object permissions will always return False or an empty list (depending on
the check performed).