Django の認証方法のカスタマイズ¶
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()
をただ利用することです。
認証バックエンドの実装¶
認証バックエンドは2つの必須メソッド: get_user(user_id)
と authenticate(request, **credentials)
を持ったクラスであり、 また、パーミッションに関連した省略可能な authorization methods を持ちます。
get_user`
メソッドは user_id
-- ユーザー名、データベース上の ID 等、何でも利用できますが、あなたが定義したユーザーオブジェクトの主キーである値 -- を取って一つのユーザーオブジェクト、または``None``を返却します。
authenticate
メソッドは request
引数と、キーワード引数として認証情報を持ちます。多くの場合、次のように表されます:
class MyBackend:
def authenticate(self, request, username=None, password=None):
# Check the username/password and return a user.
...
一方、次のように認証トークンでも表せます:
class MyBackend:
def authenticate(self, request, token=None):
# Check the token and return a user.
...
いずれの場合にせよ、 authenticate()
は与えられた認証情報を確認し、それが有効であれば、認証情報とマッチしたユーザーオブジェクトを返すべきです。それが有効でなければ None
を返すべきです。
request
は HttpRequest
で、 authenticate()
が提供されていない場合 None
となる可能性があります。(バックエンドでこれを通過するため).
Django の admin は Django の User object と強く結合しています。これを扱う最も良い方法は Django の User
オブジェクトを、あなたのバックエンド(例えば、LDAP ディレクトリ、外部の SQL データベースなど)に存在するそれぞれのユーザーに対して作成することです。これを行うためのスクリプトを事前に記述しておくか、ユーザーが初めてログインするときに authenticate
メソッドがこれを行えるようにしておくと良いでしょう。
次に示すのが、 settings.py
で定義されたユーザー名とパスワードの変数に対して認証し、ユーザーの認証が初めてであった場合に Django の User
オブジェクトを作成するバックエンドの例です:
from django.conf import settings
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User
class SettingsBackend:
"""
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, request, 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
カスタムバックエンドによる認可の扱い¶
カスタム認証バックエンドはそれら独自のパーミッションを提供することができます。
ユーザーモデルはパーミッションを取得する関数たち (get_group_permissions()
, get_all_permissions()
, has_perm()
, and has_module_perms()
) の機能を、これらの関数たちを実装した認証バックエンドに委任します。
これによりユーザーに与えられたパーミッションは全てのバックエンドが返すすべてのパーミッションの上位セットになります。つまり、Django はユーザーに、任意のバックエンドが付与するパーミッションを与えます。
もし例外 PermissionDenied
を has_perm()
か has_module_perms()
の中でバックエンドが出した場合、認可は直ちに失敗し、 Django はそこから続くバックエンドを確認しません。
上記のシンプルなバックエンドは、魔法の admin のパーミッションを非常に簡潔に実装することができます:
class SettingsBackend:
...
def has_perm(self, user_obj, perm, obj=None):
return user_obj.username == settings.ADMIN_LOGIN
上記の例では、アクセスしたユーザーに全てのパーミッションを付与します。注意すべき点として、関数 django.contrib.auth.models.User
から関連して得られた同じ引数は、バックエンド認証関数は、匿名のユーザーを表すものも含んでいるかもしれない、全てのユーザーオブジェクトを引数として取る点があります。
認可の実装の完全なものは django/contrib/auth/backends.py の ModelBackend
クラスにあり、これはデフォルトのバックエンドであり、ほとんどの場合 auth_permission
テーブルを照会します。もしバックエンド API の一部だけにカスタムの動作を行わせようとした場合は、カスタムのバックエンド API に完全な API を実装せずとも、Python の継承と ModelBackend
サブクラスを利用できます。
匿名ユーザーに対する認可¶
匿名ユーザーは認証されていないユーザー、すなわち有効な認証の詳述を受けていないユーザーです。しかし、それは彼らが何かを行う権限を持っていないことを意味するとは限りません。一般的な話として、多くのウェブサイトは匿名のユーザーにサイトの大部分を閲覧する権限を与え、多くのユーザーにコメント投稿を許可するなどしています。
Django のパーミッションフレームワークは匿名ユーザーのパーミッションを保持する場所を持ちません。しかし、認証バックエンドに渡されるユーザーオブジェクトの1つ、 django.contrib.auth.models.AnonymousUser
オブジェクトは、バックエンドが匿名ユーザーのためのカスタムの認証の動作を指定することを可能とします。これは、たとえば匿名のアクセスをコントロールするといった設定を必要とせず、認証の課題のすべてを認証バックエンドに任せるような、再利用可能なアプリの作者にとって非常に便利です。
アクティブでないユーザーに対する認証¶
is_active
フィールドが False
となっているユーザーを、アクティブでないユーザーと呼びます。認証バックエンド ModelBackend
と RemoteUserBackend
はこれらのユーザーの認証行為を禁止します。カスタムユーザーモデルが is_active
を持っていない場合、すべてのユーザーの認証行為が許可されます。
もし、アクティブでないユーザーの認証行為を許可したい場合は、AllowAllUsersModelBackend
や AllowAllUsersRemoteUserBackend
を使用することができます。
パーミッションシステムが匿名ユーザーをサポートしている場合、匿名ユーザーがパーミッションを持つ操作であっても、アクティブでないユーザーにはそれができないということが起こりえます。
バックエンドで独自のパーミッションメソッド持つときは、ユーザーの is_active
属性のテストを忘れずに行ってください。
オブジェクトのパーミッションの取扱い¶
Django のパーミッションフレームワークはオブジェクトパーミッション基盤を持っていますが、コアには実装されていません。これにより、オブジェクトパーミッションのチェックは常に False
または空のリスト(実行されたチェックに応じていずれか)が返されます。認証バックエンドは、オブジェクトに関連した認証メソッドごとに obj
and user_obj
のキーワードパラメタを受け取り、必要に応じてオブジェクトレベルのパーミッションを返します。
カスタムのパーミッション¶
モデルオブジェクトに対してカスタムパーミッションを作成したい場合は model Meta attribute の``permissions`` を使用してください。
この例の Task
モデルは、2つのカスタムパーミッションを作成します。すなわち、このアプリケーションにおいて、ユーザーが Task
インスタンスに関係して、できることとできないことを規定します。
class Task(models.Model):
...
class Meta:
permissions = (
("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 (changing the
status of tasks or closing tasks.) Continuing the above example, the following
checks if a user may close tasks:
user.has_perm('app.close_task')
既存の User
モデルを拡張する¶
独自のモデルを使用することなく、デフォルトのモデル User
を拡張する方法が2つあります。振る舞いのみを変更し、データベースに格納されている内容を変更する必要がない場合は User
に基づいて proxy model を作成できます。これにより、デフォルトの並び順、カスタムマネージャ、カスタムモデルメソッドなど、プロキシモデルによって提供される機能を利用可能です。
User
に関連した情報を格納したい場合は、 OneToOneField
を追加する情報のフィールドを持ったモデルに使用することができます。この1対1モデルはサイトユーザーに関する、認証には関連しない情報を格納することがあるため、しばしばプロファイルモデルと呼ばれます。たとえば、次のような Employee モデルを作ります:
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)
User モデルと Employee モデルの両方を持っている既存の従業員 Fred Smith について、Django の標準の関連モデル規則を使用して関連情報にアクセスできます:
>>> u = User.objects.get(username='fsmith')
>>> freds_department = u.employee.department
admin のユーザーページにプロファイルモデルのフィールドを追加する場合は、InlineModelAdmin
(この例では、StackedInline
を使用しています) をあなたの admin.py
に定義し、それを User
クラスで追加した UserAdmin
クラスに追加します。
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)
これらのプロファイルモデルは特殊なものではありませんー単純にユーザーモデルと1体1でリンクされた Django モデルです。したがって、ユーザー作成時に自動的に作成されることはありませんが、django.db.models.signals.post_save
を活用することで関連づけしたモデルを作成、更新することができます。
関連づけされたモデルを使用した場合、関連するデータを検索するための追加のクエリ実行や結合が行われます。あなたの必要性に応じて、関連づけされたフィールドをカスタムユーザーモデルにインクルードすることは適した選択肢となるでしょう。しかしながら、デフォルトのユーザーモデルとプロジェクトのアプリケーションに組み込み済みの連携は追加のデータベース負荷を正当化するでしょう。
カスタムの User
モデルを置き換える¶
Django にビルトインされている User
モデルは、必ずしもプロジェクトが必要とする認証のモデルと合致するわけではありません。たとえば、サイトによってはユーザー名の代わりにメールアドレスを識別トークンとして使用する方が適した場合があります。
Django では、カスタムモデルを参照するように AUTH_USER_MODEL
の値を設定することにより、デフォルトのユーザーモデルをオーバーライドすることができます:
AUTH_USER_MODEL = 'myapp.MyUser'
このドットで区切られたペアは Django app の名前 ( INSTALLED_APPS
に含まれている必要があります) とあなたがユーザーモデルとして使用したい Django モデルの名前です。
プロジェクトの開始時にカスタムのユーザーモデルを使用する¶
新しくプロジェクトを始める場合は、デフォルトの User
で十分である場合でも、カスタムユーザーモデルを作成することを強く推奨します。このモデルはデフォルトのユーザーモデルと同様に動作しますが、必要に応じて将来的にカスタマイズすることができます:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
pass
AUTH_USER_MODEL
に指定することを忘れないでください。任意のマイグレーションの作成、また、最初に実行する manage.py migrate
の前に行ってください。
そして、モデルをアプリの admin.py
に登録してください:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
admin.site.register(User, UserAdmin)
プロジェクト途中からのカスタムユーザーモデルへの変更¶
AUTH_USER_MODEL
をデータベーステーブルの作成後に変更することは、たとえば、外部キーや多対多の関係に影響するため、非常に困難となります。
この変更は自動的には行うことができません。手動でのスキーマ修正、古いユーザーテーブルからのデータ移動、一部のマイグレーションの手動による再適用をする必要があります。ステップの概要は #25313 を参照してください。
スワップ可能なモデルという Django の動的依存性により、 AUTH_USER_MODEL
によって参照されるモデルはアプリの初回のマイグレーションで作成されなければなりません(通常は 0001_initial
と呼ばれます)。そうしない場合、依存関係の問題が発生します。
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.)
再利用可能なアプリと 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
設定を用いてユーザーモデルを参照することです。しかし、Django がモデルをインポートするときにget_user_model()
を呼ぶという方法もあります。こうすると、models.ForeignKey(get_user_model(), ...)
という表記が可能です。If your app is tested with multiple user models, using
@override_settings(AUTH_USER_MODEL=...)
for example, and you cache the result ofget_user_model()
in a module-level variable, you may need to listen to thesetting_changed
signal to clear the cache. For example:from django.apps import apps from django.contrib.auth import get_user_model from django.core.signals import setting_changed from django.dispatch import receiver @receiver(setting_changed) def user_model_swapped(**kwargs): if kwargs['setting'] == 'AUTH_USER_MODEL': apps.clear_cache() from myapp import some_module some_module.UserModel = get_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 は、カスタムのユーザーモデルがいくつかの最低限の要件を満たしていることを期待します。
デフォルトの認証バックエンドを使用している場合、モデルは必ず、認証のために使用できるユニークなフィールドを1つ持たなければなりません。このフィールドとしては、ユーザー名やメールアドレスなど、ユニークな属性ならば使用できます。ユニークでないユーザー名などのフィールドが使用できるのは、そのようなフィールドを扱えるカスタムの認証バックエンドだけです。
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.以下の例では、フィールドを一意に指定するために、
identifier
フィールドが使われています。class MyUser(AbstractBaseUser): identifier = models.CharField(max_length=40, unique=True) ... USERNAME_FIELD = 'identifier'
-
EMAIL_FIELD
¶ ユーザーモデルにあるメールのフィールド名を文字列で記述します。この値は
get_email_field_name()
で返されます。
-
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.
-
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
()¶ Optional. A longer formal identifier for the user such as their full name. If implemented, this appears alongside the username in an object's history in
django.contrib.admin
.
-
get_short_name
()¶ Optional. A short, informal identifier for the user such as their first name. If implemented, this replaces the username in the greeting to the user in the header of
django.contrib.admin
.
Changed in Django 2.0:In older versions, subclasses are required to implement
get_short_name()
andget_full_name()
asAbstractBaseUser
has implementations that raiseNotImplementedError
.AbstractBaseUser
のインポートAbstractBaseUser
とBaseUserManager
はdjango.contrib.auth.base_user
からインポートでき、INSTALLED_APPS
の中にdjango.contrib.auth
をインクルードすることなくインポートできます。-
次の属性とメソッドは AbstractBaseUser
: の任意のサブクラスで利用可能です。
-
class
models.
AbstractBaseUser
¶ -
get_username
()¶ USERNAME_FIELD
で指定されたフィールドの値を返します。
-
clean
()¶ normalize_username()
を呼び出し、username を正規化します。このメソッドをオーバーライドした場合、正規化を保持するためにsuper()
を呼び出すようにしてください。
-
classmethod
get_email_field_name
()¶ EMAIL_FIELD
属性で指定されたメールフィールドの名前を返します。EMAIL_FIELD
の指定が無いとき、デフォルトは'email'
です。
-
classmethod
normalize_username
(username)¶ 視覚的に同一であるが異なる Unicode の符号位置を持つ文字について、それらが同一とみなされるように、username に NFKC Unicode正規化を適用します。
-
is_authenticated
¶ (
AnonymousUser.is_authenticated
が常にFalse
なのとは対照的に) 常にTrue
の読み取り専用属性です。ユーザが認証済みかどうかを知らせる方法です。これはパーミッションという意味ではなく、ユーザーがアクティブかどうか、また有効なセッションがあるかどうかをチェックするわけでもありません。 通常、request.user
のこの属性をチェックしてAuthenticationMiddleware
(現在ログイン中のユーザを表します) によって格納されているかどうかを調べます。User
のインスタンスの場合、この属性はTrue
となります。
-
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.
-
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.
-
AbstractUser
subclasses AbstractBaseUser
:
-
class
models.
AbstractUser
¶ -
clean
()¶ BaseUserManager.normalize_email()
を呼び出し、メールを正規化します。このメソッドをオーバーライドした場合、正規化を保持するために必ずsuper()
を呼び出すようにしてください。
-
Writing a manager for a custom user model¶
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.
-
For a ForeignKey
in USERNAME_FIELD
or
REQUIRED_FIELDS
, these methods receive the value of the
to_field
(the primary_key
by default) of an existing instance.
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 カスタムのユーザーモデルを指定する.
AbstractUser
provides the full implementation of the default
User
as an abstract model.
カスタムのユーザーとビルトインの認証フォーム¶
Django のビルトインの forms と views は、協調して動作するユーザーモデルに対して、いくつかの前提を置いています。
以下のフォームは AbstractBaseUser
のあらゆるサブクラスに互換性があります。
AuthenticationForm
:USERNAME_FIELD
で指定したユーザー名フィールドを使用する。SetPasswordForm
PasswordChangeForm
AdminPasswordChangeForm
以下のフォームは、ユーザーモデルについて以下のようないくつか前提を置いています。これらの前提を満たしている場合、同じユーザーモデルとみなして使用することができます。
PasswordResetForm
: Assumes that the user model has a field that stores the user's email address with the name returned byget_email_field_name()
(email
by default) that can be used to identify the user and a boolean field namedis_active
to prevent password resets for inactive users.
最後に、以下のフォームは、User
と固く結びついているため、カスタムのユーザーモデルとともに使用するには、書き換えや拡張が必要になります。
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',)
カスタムのユーザーと django.contrib.admin
¶
カスタムのユーザーモデルを admin で動作させたい場合、ユーザーモデルにいくつかの追加の属性とメソッドを定義しなければなりません。これらのメソッドを定義することで、admin はユーザーへアクセスを制御して admin のコンテンツに合わせることができます。
-
class
models.
CustomUser
-
is_staff
¶ ユーザーが admin サイトへのアクセス権を持っている時、
True
を返します。
-
is_active
¶ ユーザーアカウントが現在アクティブな時、
True
を返します。
-
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.
カスタムのユーザーとパーミッション¶
Django のパーミッションフレームワークをカスタムのユーザーモデルに簡単に取り入れられるように用意されているのが、Django の PermissionsMixin
です。これはユーザーモデルの階層に取り入れることができる抽象モデルで、Django のパーミッションモデルをサポートするのに必要なすべてのメソッドとデーターベースのフィールドを使えるようにしてくれます。
PermissionsMixin
は、以下のメソッドと属性を提供します。
-
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). IfUser.is_active
andis_superuser
are bothTrue
, this method always returnsTrue
.obj
が渡された場合、このメソッドはモデルに対するパーミッションのチェックを行わず、指定されたオブジェクトに対して行います。
-
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>"
. IfUser.is_active
andis_superuser
are bothTrue
, this method always returnsTrue
.obj
が渡された場合、このメソッドは指定されたオブジェクトに対してパーミッションのチェックを行い、モデルに対しては行いません。
-
has_module_perms
(package_name)¶ Returns
True
if the user has any permissions in the given package (the Django app label). IfUser.is_active
andis_superuser
are bothTrue
, this method always returnsTrue
.
-
カスタムのユーザーと proxy モデル¶
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.
完全な具体例¶
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 __str__(self):
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().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'