Django の認証方法のカスタマイズ¶
デフォルトでdjangoに付属している認証方法は、極めて一般的なケースには十分ですが、あなたのニーズを満たされないケースがあるかもしれません。あなたのプロジェクトのニーズに合わせて認証方法をカスタマイズするには、提供されている認証システムはどのような点が拡張可能であるか、または交換可能であるかを理解する必要があります。本ドキュメントでは、認証システムをカスタマイズする方法の詳細を提供します。
認証バックエンド を利用すると、ユーザーモデルに保存されたユーザー名とパスワードを用いて異なるサービス間での認証を行う必要が生じた場合に Django 標準よりも高い拡張性を持たせることができます。
あなたはDjango認証システムを通した認証による改良したパーミッション<custom-permission>をあなたのユーザモデルに組み込むことができるでしょう。
あなたは標準の User
モデルを 拡張、もしくは完全にカスタマイズしたモデルを 代わりに用いる 事ができます。
他の認証ソースを利用する¶
もしかしたらあなたは,他の認証元からユーザネームとパスワード,もしくは認証方式のため,別の認証元にhookする必要があるかもしれません。
例えばあなたの会社ですでに全ての従業員のユーザ名とパスワードを記録しているLDAP認証があるとしましょう。もしユーザがLDAP認証とdjangoアプリケーションで異なるアカウントだとしたらネットワーク管理者とユーザで口論になるでしょう。
そこでこのような状況に対応するためにDjangoの認証システムは他の認証システムのリソースと接続できます。あなたはDjangoのデフォルトのデータベーススキーマをオーバーライドするか、他のシステムを連携するためにデフォルトシステムを使うことができます。
Django に含まれている認証バックエンドに関する情報は 認証バックエンドリファレンス を参照してください。
認証バックエンドを指定する¶
内部的に、Django は認証を確認する「認証バックエンド」のリストを保持しています。django.contrib.auth.authenticate()
を誰かがコールすると – どのようにログインするか で記述されているように – Django はその認証バックエンド全てに対して認証を試行します。最初の認証方法が失敗した場合、Django は次の方法、また次の方法といった具合に、全てのバックエンドに対して認証を試行します。
認証バックエンドとして利用するリストは AUTHENTICATION_BACKENDS
に定義されています。この設定値は認証方法を定義している Python クラスを指定する Python パスのリスト型変数でなければなりません。これらのクラスはあなたの環境で有効な Python パスのどこにでも配置可能です。
初期状態では、AUTHENTICATION_BACKENDS
は以下の値として定義されています。:
['django.contrib.auth.backends.ModelBackend']
これは Django のユーザーデータベースを確認してビルトインの権限を照会する基本的な認証バックエンドです。このバックエンドにはログイン試行を制限することでブルートフォース攻撃を防御する仕組みは提供していません。独自に試行制限を実装した認証バックエンドを利用するか、多くのウェブサーバーで提供されている各種防御機構が利用可能です。
AUTHENTICATION_BACKENDS
への順番は処理に影響し、同じユーザー名とパスワードによって複数のバックエンドで有効な認証と判定されれば、Django は最初に有効と判定した時点で処理を終了します。
ある認証バックエンドにおいて PermissionDenied 例外が発生した場合、認証処理は直ちに終了し、Django は続く認証バックエンドに対する認証判定を行いません。
注釈
あるユーザーが一度認証されると、Django はそのユーザーの有効なセッション中はどの認証バックエンドがそのユーザーの認証に利用されたかを保持し、そのセッション有効期限中は認証されたユーザーの情報にアクセスする必要が生じる毎に同じ認証バックエンドを再利用します。これは認証情報がセッション毎に事実上キャッシュされる事を意味しており、従って AUTHENTICATION_BACKENDS
を変更すると、ユーザーに対して異なる方法を用いた再認証を要求する際にはセッション情報を破棄する必要が有ります。これを実現する簡単な一つの方法は Session.objects.all().delete()
をただ利用することです。
認証バックエンドの実装¶
認証バックエンドの実体は get_user(user_id)
および authenticate(**credentials)
という 2 つの必須メソッドとオプションの権限付与に関連した :ref:`認証メソッド <authorization_methods> のセットが実装されているクラスです。
get_user
メソッドは user_id
– ユーザー名、データベース上の ID 等何でも利用できますが、あなたが定義したユーザーオブジェクトの主キーである値 – を取って一つのユーザーオブジェクトを返します。
The authenticate
method takes credentials as keyword arguments. Most of
the time, it’ll just look like this:
class MyBackend(object):
def authenticate(self, username=None, password=None):
# Check the username/password and return a user.
...
But it could also authenticate a token, like so:
class MyBackend(object):
def authenticate(self, token=None):
# Check the token and return a user.
...
Either way, authenticate()
should check the credentials it gets and 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 is tightly coupled to the Django User object. 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:
from django.conf import settings
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User
class SettingsBackend(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 = 'pbkdf2_sha256$30000$Vo0VlMnkR4Bk$qEvtdyZRWTcOsCnI/oQ7fVOu1XAURIZYoOZ3iq8Dr4M='
"""
def authenticate(self, username=None, password=None):
login_valid = (settings.ADMIN_LOGIN == username)
pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
if login_valid and pwd_valid:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# Create a new user. There's no need to set a password
# because only the password from settings.py is checked.
user = User(username=username)
user.is_staff = True
user.is_superuser = True
user.save()
return user
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
Handling authorization in custom backends¶
Custom auth backends can provide their own permissions.
The user model will delegate permission lookup functions
(get_group_permissions()
,
get_all_permissions()
,
has_perm()
, and
has_module_perms()
) to any
authentication backend that implements these functions.
The permissions given to the user will be the superset of all permissions returned by all backends. That is, Django grants a permission to a user that any one backend grants.
If a backend raises a PermissionDenied
exception in has_perm()
or
has_module_perms()
, the authorization
will immediately fail and Django won’t check the backends that follow.
The simple backend above could implement permissions for the magic admin fairly simply:
class SettingsBackend(object):
...
def has_perm(self, user_obj, perm, obj=None):
return user_obj.username == settings.ADMIN_LOGIN
This gives full permissions to the user granted access in the above example.
Notice that in addition to the same arguments given to the associated
django.contrib.auth.models.User
functions, the backend auth functions
all take the user object, which may be an anonymous user, as an argument.
A full authorization implementation can be found in the ModelBackend
class
in django/contrib/auth/backends.py, which is the default backend and queries
the auth_permission
table most of the time. If you wish to provide
custom behavior for only part of the backend API, you can take advantage of
Python inheritance and subclass ModelBackend
instead of implementing the
complete API in a custom backend.
Authorization for anonymous users¶
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 websites 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, the user object passed to an authentication backend
may be an django.contrib.auth.models.AnonymousUser
object, allowing
the backend to specify custom authorization behavior 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.
Authorization for inactive users¶
An inactive user is one that has its
is_active
field set to False
. The
ModelBackend
and
RemoteUserBackend
authentication
backends prohibits these users from authenticating. If a custom user model
doesn’t have an is_active
field,
all users will be allowed to authenticate.
You can use AllowAllUsersModelBackend
or AllowAllUsersRemoteUserBackend
if you
want to allow inactive users to authenticate.
The support for anonymous users in the permission system allows for a scenario where anonymous users have permissions to do something while inactive authenticated users do not.
Do not forget to test for the is_active
attribute of the user in your own
backend permission methods.
In older versions, the ModelBackend
allowed inactive users to authenticate.
Handling object permissions¶
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). An authentication backend will receive the keyword
parameters obj
and user_obj
for each object related authorization
method and can return the object level permission as appropriate.
Custom permissions¶
To create custom permissions for a given model object, use the permissions
model Meta attribute.
This example Task model creates three custom permissions, i.e., actions users can or cannot do with Task instances, specific to your application:
class Task(models.Model):
...
class Meta:
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.py migrate
(the function that creates permissions
is connected to the post_migrate
signal).
Your code is in charge of checking the value of these permissions when a 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:
user.has_perm('app.view_task')
Extending the existing User
model¶
There are two ways to extend the default
User
model without substituting your own
model. If the changes you need are purely behavioral, and don’t require any
change to what is stored in the database, you can create a proxy model based on User
. This
allows for any of the features offered by proxy models including default
ordering, custom managers, or custom model methods.
If you wish to store information related to User
, you can use a
OneToOneField
to a model containing the fields for
additional information. This one-to-one model is often called a profile model,
as it might store non-auth related information about a site user. For example
you might create an Employee model:
from django.contrib.auth.models import User
class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.CharField(max_length=100)
Assuming an existing Employee Fred Smith who has both a User and Employee model, you can access the related information using Django’s standard related model conventions:
>>> u = User.objects.get(username='fsmith')
>>> freds_department = u.employee.department
To add a profile model’s fields to the user page in the admin, define an
InlineModelAdmin
(for this example, we’ll use a
StackedInline
) in your app’s admin.py
and
add it to a UserAdmin
class which is registered with the
User
class:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from my_user_profile_app.models import Employee
# Define an inline admin descriptor for Employee model
# which acts a bit like a singleton
class EmployeeInline(admin.StackedInline):
model = Employee
can_delete = False
verbose_name_plural = 'employee'
# Define a new User admin
class UserAdmin(BaseUserAdmin):
inlines = (EmployeeInline, )
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
These profile models are not special in any way - they are just Django models
that happen to have a one-to-one link with a user model. As such, they aren’t
auto created when a user is created, but
a django.db.models.signals.post_save
could be used to create or update
related models as appropriate.
Using related models results in additional queries or joins to retrieve the related data. Depending on your needs, a custom user model that includes the related fields may be your better option, however, existing relations to the default user model within your project’s apps may justify the extra database load.
Substituting a custom User
model¶
Some kinds of projects may have authentication requirements for which Django’s
built-in User
model is not always
appropriate. For instance, on some sites it makes more sense to use an email
address as your identification token instead of a username.
Django allows you to override the default user model by providing a value for
the AUTH_USER_MODEL
setting that references a custom model:
AUTH_USER_MODEL = 'myapp.MyUser'
This dotted pair describes the name of the Django app (which must be in your
INSTALLED_APPS
), and the name of the Django model that you wish to
use as your user model.
Using a custom user model when starting a project¶
If you’re starting a new project, it’s highly recommended to set up a custom
user model, even if the default User
model
is sufficient for you. This model behaves identically to the default user
model, but you’ll be able to customize it in the future if the need arises:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
pass
Don’t forget to point AUTH_USER_MODEL
to it. Do this before creating
any migrations or running manage.py migrate
for the first time.
Changing to a custom user model mid-project¶
Changing AUTH_USER_MODEL
after you’ve created database tables is
significantly more difficult since it affects foreign keys and many-to-many
relationships, for example.
This change can’t be done automatically and requires manually fixing your schema, moving your data from the old user table, and possibly manually reapplying some migrations. See #25313 for an outline of the steps.
Due to limitations of Django’s dynamic dependency feature for swappable
models, the model referenced by AUTH_USER_MODEL
must be created in
the first migration of its app (usually called 0001_initial
); otherwise,
you’ll have dependency issues.
In addition, you may run into a CircularDependencyError
when running your
migrations as Django won’t be able to automatically break the dependency loop
due to the dynamic dependency. If you see this error, you should break the loop
by moving the models depended on by your user model into a second migration.
(You can try making two normal models that have a ForeignKey
to each other
and seeing how makemigrations
resolves that circular dependency if you want
to see how it’s usually done.)
Reusable apps and AUTH_USER_MODEL
¶
Reusable apps shouldn’t implement a custom user model. A project may use many
apps, and two reusable apps that implemented a custom user model couldn’t be
used together. If you need to store per user information in your app, use
a ForeignKey
or
OneToOneField
to settings.AUTH_USER_MODEL
as described below.
User
モデルを参照する¶
User
を直接参照する場合 (例えば外部キーで参照する場合)、AUTH_USER_MODEL
設定が異なるユーザモデルに変更されたプロジェクトでは正しく動作しません。
-
get_user_model
()[ソース]¶ User
を直接参照する代わりに、django.contrib.auth.get_user_model()
を使ってユーザモデルを参照すべきです。このメソッドは現在アクティブなユーザモデルを返します – 指定されている場合はカスタムのユーザモデル、指定されていない場合はUser
です。ユーザモデルに対して外部キーや多対多の関係を定義するときは、
AUTH_USER_MODEL
設定を使ってカスタムのモデルを指定してください。例えば:from django.conf import settings from django.db import models class Article(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, )
ユーザモデルによって送信されたシグナルと接続するときは、
AUTH_USER_MODEL
設定を使ってカスタムのユーザモデルを指定してください。例えば:from django.conf import settings from django.db.models.signals import post_save def post_save_receiver(sender, instance, created, **kwargs): pass post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL)
一般的に言って、コード内では
AUTH_USER_MODEL
設定を使ってユーザモデルを参照すべきで、これは import のときに実行されます。get_user_model()
は Django が全てのモデルをインポートし終わったときのみ動作します。
Specifying a custom user model¶
Model design considerations
Think carefully before handling information not directly related to authentication in your custom user model.
It may be better to store app-specific user information in a model that has a relation with the user model. That allows each app to specify its own user data requirements without risking conflicts with other apps. On the other hand, queries to retrieve this related information will involve a database join, which may have an effect on performance.
Django expects your custom user model to meet some minimum requirements.
- If you use the default authentication backend, then your model must have a single unique field that can be used for identification purposes. This can be a username, an email address, or any other unique attribute. A non-unique username field is allowed if you use a custom authentication backend that can support it.
- Your model must provide a way to address the user in a “short” and “long” form. The most common interpretation of this would be to use the user’s given name as the “short” identifier, and the user’s full name as the “long” identifier. However, there are no constraints on what these two methods return - if you want, they can return exactly the same value.
The easiest way to construct a compliant custom user model is to inherit from
AbstractBaseUser
.
AbstractBaseUser
provides the core
implementation of a user model, including hashed passwords and tokenized
password resets. You must then provide some key implementation details:
-
class
models.
CustomUser
¶ -
USERNAME_FIELD
¶ A string describing the name of the field on the user model that is used as the unique identifier. This will usually be a username of some kind, but it can also be an email address, or any other unique identifier. The field must be unique (i.e., have
unique=True
set in its definition), unless you use a custom authentication backend that can support non-unique usernames.In the following example, the field
identifier
is used as the identifying field:class MyUser(AbstractBaseUser): identifier = models.CharField(max_length=40, unique=True) ... USERNAME_FIELD = 'identifier'
USERNAME_FIELD
now supportsForeignKey
s. Since there is no way to pass model instances during thecreatesuperuser
prompt, expect the user to enter the value ofto_field
value (theprimary_key
by default) of an existing instance.
-
REQUIRED_FIELDS
¶ A list of the field names that will be prompted for when creating a user via the
createsuperuser
management command. The user will be prompted to supply a value for each of these fields. It must include any field for whichblank
isFalse
or undefined and may include additional fields you want prompted for when a user is created interactively.REQUIRED_FIELDS
has no effect in other parts of Django, like creating a user in the admin.For example, here is the partial definition for a user model that defines two required fields - a date of birth and height:
class MyUser(AbstractBaseUser): ... date_of_birth = models.DateField() height = models.FloatField() ... REQUIRED_FIELDS = ['date_of_birth', 'height']
注釈
REQUIRED_FIELDS
must contain all required fields on your user model, but should not contain theUSERNAME_FIELD
orpassword
as these fields will always be prompted for.REQUIRED_FIELDS
now supportsForeignKey
s. Since there is no way to pass model instances during thecreatesuperuser
prompt, expect the user to enter the value ofto_field
value (theprimary_key
by default) of an existing instance.
-
is_active
¶ A boolean attribute that indicates whether the user is considered “active”. This attribute is provided as an attribute on
AbstractBaseUser
defaulting toTrue
. How you choose to implement it will depend on the details of your chosen auth backends. See the documentation of theis_active attribute on the built-in user model
for details.
-
get_full_name
()¶ A longer formal identifier for the user. A common interpretation would be the full name of the user, but it can be any string that identifies the user.
-
get_short_name
()¶ A short, informal identifier for the user. A common interpretation would be the first name of the user, but it can be any string that identifies the user in an informal way. It may also return the same value as
django.contrib.auth.models.User.get_full_name()
.
Importing
AbstractBaseUser
New in Django 1.9.AbstractBaseUser
andBaseUserManager
are importable fromdjango.contrib.auth.base_user
so that they can be imported without includingdjango.contrib.auth
inINSTALLED_APPS
(this raised a deprecation warning in older versions and is no longer supported in Django 1.9).-
The following attributes and methods are available on any subclass of
AbstractBaseUser
:
-
class
models.
AbstractBaseUser
¶ -
get_username
()¶ Returns the value of the field nominated by
USERNAME_FIELD
.
-
clean
()¶ - New in Django 1.10.
Normalizes the username by calling
normalize_username()
. If you override this method, be sure to callsuper()
to retain the normalization.
-
classmethod
normalize_username
(username)¶ - New in Django 1.10.
Applies NFKC Unicode normalization to usernames so that visually identical characters with different Unicode code points are considered identical.
-
is_authenticated
¶ (
AnonymousUser.is_authenticated
が常にFalse
なのとは対照的に) 常にTrue
の読み取り専用属性です。ユーザが認証済みかどうかを知らせる方法です。これはパーミッションという意味ではなく、ユーザーがアクティブかどうか、また有効なセッションがあるかどうかをチェックするわけでもありません。 通常、request.user
のこの属性をチェックしてAuthenticationMiddleware
(現在ログイン中のユーザを表します) によって格納されているかどうかを調べます。User
のインスタンスの場合、この属性はTrue
となります。Changed in Django 1.10:古いバージョンでは、メソッドでした。メソッドとして使うための後方互換性サポートは、Django 2.0 で廃止されます。
-
is_anonymous
¶ Read-only attribute which is always
False
. This is a way of differentiatingUser
andAnonymousUser
objects. Generally, you should prefer usingis_authenticated
to this attribute.Changed in Django 1.10:古いバージョンでは、メソッドでした。メソッドとして使うための後方互換性サポートは、Django 2.0 で廃止されます。
-
set_password
(raw_password)¶ Sets the user’s password to the given raw string, taking care of the password hashing. Doesn’t save the
AbstractBaseUser
object.When the raw_password is
None
, the password will be set to an unusable password, as ifset_unusable_password()
were used.
-
check_password
(raw_password)¶ 与えられた生の文字列が、ユーザに対して正しいパスワードであれば
True
を返します。 (比較する際にはパスワードハッシュを処理します。)
-
set_unusable_password
()¶ Marks the user as having no password set. This isn’t the same as having a blank string for a password.
check_password()
for this user will never returnTrue
. Doesn’t save theAbstractBaseUser
object.アプリケーションの認証が LDAP ディレクトリなどの既存の外部ソースに対して行われている場合は、これが必要になることがあります。
-
has_usable_password
()¶ Returns
False
ifset_unusable_password()
has been called for this user.
-
get_session_auth_hash
()¶ Returns an HMAC of the password field. Used for Session invalidation on password change.
-
You should also define a custom manager for your user model. If your user model
defines username
, email
, is_staff
, is_active
, is_superuser
,
last_login
, and date_joined
fields the same as Django’s default user,
you can just install Django’s UserManager
;
however, if your user model defines different fields, you’ll need to define a
custom manager that extends BaseUserManager
providing two additional methods:
-
class
models.
CustomUserManager
¶ -
create_user
(*username_field*, password=None, **other_fields)¶ The prototype of
create_user()
should accept the username field, plus all required fields as arguments. For example, if your user model usesemail
as the username field, and hasdate_of_birth
as a required field, thencreate_user
should be defined as:def create_user(self, email, date_of_birth, password=None): # create user here ...
-
create_superuser
(*username_field*, password, **other_fields)¶ The prototype of
create_superuser()
should accept the username field, plus all required fields as arguments. For example, if your user model usesemail
as the username field, and hasdate_of_birth
as a required field, thencreate_superuser
should be defined as:def create_superuser(self, email, date_of_birth, password): # create superuser here ...
Unlike
create_user()
,create_superuser()
must require the caller to provide a password.
-
BaseUserManager
provides the following
utility methods:
-
class
models.
BaseUserManager
¶ -
classmethod
normalize_email
(email)¶ Normalizes email addresses by lowercasing the domain portion of the email address.
-
get_by_natural_key
(username)¶ Retrieves a user instance using the contents of the field nominated by
USERNAME_FIELD
.
-
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
, and1
(lowercase letter i, lowercase letter L, uppercase letter i, and the number one)o
,O
, and0
(lowercase letter o, uppercase letter o, and zero)
-
classmethod
Extending Django’s default User
¶
If you’re entirely happy with Django’s User
model and you just want to add some additional profile information, you could
simply subclass django.contrib.auth.models.AbstractUser
and add your
custom profile fields, although we’d recommend a separate model as described in
the “Model design considerations” note of Specifying a custom user model.
AbstractUser
provides the full implementation of the default
User
as an abstract model.
Custom users and the built-in auth forms¶
Django’s built-in forms and views make certain assumptions about the user model that they are working with.
The following forms are compatible with any subclass of
AbstractBaseUser
:
AuthenticationForm
: Uses the username field specified byUSERNAME_FIELD
.SetPasswordForm
PasswordChangeForm
AdminPasswordChangeForm
The following forms make assumptions about the user model and can be used as-is if those assumptions are met:
PasswordResetForm
: Assumes that the user model has a field namedemail
that can be used to identify the user and a boolean field namedis_active
to prevent password resets for inactive users.
Finally, the following forms are tied to
User
and need to be rewritten or extended
to work with a custom user model:
If your custom user model is a simple subclass of AbstractUser
, then you
can extend these forms in this manner:
from django.contrib.auth.forms import UserCreationForm
from myapp.models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = CustomUser
fields = UserCreationForm.Meta.fields + ('custom_field',)
Custom users and django.contrib.admin
¶
If you want your custom user model to also work with the admin, your user model must define some additional attributes and methods. These methods allow the admin to control access of the user to admin content:
-
class
models.
CustomUser
-
is_staff
¶ Returns
True
if the user is allowed to have access to the admin site.
-
is_active
¶ Returns
True
if the user account is currently active.
-
has_perm(perm, obj=None):
Returns
True
if the user has the named permission. Ifobj
is provided, the permission needs to be checked against a specific object instance.
-
has_module_perms(app_label):
Returns
True
if the user has permission to access models in the given app.
You will also need to register your custom user model with the admin. If
your custom user model extends django.contrib.auth.models.AbstractUser
,
you can use Django’s existing django.contrib.auth.admin.UserAdmin
class. However, if your user model extends
AbstractBaseUser
, you’ll need to define
a custom ModelAdmin
class. It may be possible to subclass the default
django.contrib.auth.admin.UserAdmin
; however, you’ll need to
override any of the definitions that refer to fields on
django.contrib.auth.models.AbstractUser
that aren’t on your
custom user class.
Custom users and permissions¶
To make it easy to include Django’s permission framework into your own user
class, Django provides PermissionsMixin
.
This is an abstract model you can include in the class hierarchy for your user
model, giving you all the methods and database fields necessary to support
Django’s permission model.
PermissionsMixin
provides the following
methods and attributes:
-
class
models.
PermissionsMixin
¶ -
is_superuser
¶ 真偽値です。明示的にアサインすることなく全てのパーミッションを持たせるかどうかを指定します。
-
get_group_permissions
(obj=None)¶ ユーザがグループを通して持つパーミッションの文字列のセットを返します。
obj
が渡されたとき、指定されたオブジェクトに対するグループパーミッションのみを返します。
-
get_all_permissions
(obj=None)¶ ユーザがグループおよびユーザパーミッションを通して持つパーミッションの文字列のセットを返します。
obj
が渡された場合、指定されたオブジェクトに対するパーミッションのみを返します。
-
has_perm
(perm, obj=None)¶ Returns
True
if the user has the specified permission, whereperm
is in the format"<app label>.<permission codename>"
(see permissions). If the user is inactive, this method will always returnFalse
.obj
が渡された場合、このメソッドは指定されたオブジェクトに対してパーミッションのチェックを行い、モデルに対しては行いません。
-
has_perms
(perm_list, obj=None)¶ ユーザが指定されたそれぞれのパーミッションを持っている場合、
True
を返します。各パーミッションは"<app label>.<permission codename>"
形式です。ユーザが非アクティブの場合、このメソッドは常にFalse
を返します。obj
が渡された場合、このメソッドは指定されたオブジェクトに対してパーミッションのチェックを行い、モデルに対しては行いません。
-
has_module_perms
(package_name)¶ ユーザが指定されたパッケージ (Django のアプリケーションラベル)内の全パーミッションを持っている場合、
True
を返します。ユーザが非アクティブの場合、このメソッドは常にFalse
を返します。
-
Custom users and proxy models¶
One limitation of custom user models is that installing a custom user model
will break any proxy model extending User
.
Proxy models must be based on a concrete base class; by defining a custom user
model, you remove the ability of Django to reliably identify the base class.
If your project uses proxy models, you must either modify the proxy to extend
the user model that’s in use in your project, or merge your proxy’s behavior
into your User
subclass.
A full example¶
Here is an example of an admin-compliant custom user app. This user model uses
an email address as the username, and has a required date of birth; it
provides no permission checking, beyond a simple admin
flag on the user
account. This model would be compatible with all the built-in auth forms and
views, except for the user creation forms. This example illustrates how most of
the components work together, but is not intended to be copied directly into
projects for production use.
This code would all live in a models.py
file for a custom
authentication app:
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class MyUserManager(BaseUserManager):
def create_user(self, email, date_of_birth, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
date_of_birth=date_of_birth,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, date_of_birth, password):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
email,
password=password,
date_of_birth=date_of_birth,
)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
date_of_birth = models.DateField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['date_of_birth']
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __str__(self): # __unicode__ on Python 2
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
Then, to register this custom user model with Django’s admin, the following
code would be required in the app’s admin.py
file:
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from customauth.models import MyUser
class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = MyUser
fields = ('email', 'date_of_birth')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = MyUser
fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('email', 'date_of_birth', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('date_of_birth',)}),
('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'date_of_birth', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
# Now register the new UserAdmin...
admin.site.register(MyUser, UserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
Finally, specify the custom model as the default user model for your project
using the AUTH_USER_MODEL
setting in your settings.py
:
AUTH_USER_MODEL = 'customauth.MyUser'