お気づきのように、これはパスワード ハッシャーだけでは実行できません。パスワード ハッシャーには、ユーザーに関する情報はなく、パスワードとハッシュのみが含まれます。あなたには2つの選択肢があると思います。
まず、おそらく最善の方法は、カスタム認証バックエンドを作成することです。認証バックエンド レベルでは、ユーザー名と未加工のパスワードにアクセスできます。このようになります
# settings.py
AUTHENTICATION_BACKENDS=(
'myapp.backends.LegacyBackend',
'django.contrib.auth.backends.ModelBackend',
)
# myapp.backends
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.utils.encoding import force_bytes
import hashlib
class LegacyBackend(ModelBackend):
# We only need to override the authenticate method
def authenticate(self, username=None, password=None, **kwargs):
# most of this is copied directly from ModelBackend's authenticate method
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
user = UserModel._default_manager.get_by_natural_key(username)
# This is the normal route that hands off to the password hasher pipeline
# but we will sidestep it entirely and verify the password here
#
# if user.check_password(password):
# return user
pwhash = hashlib.md5(force_bytes(password)).hexdigest()
hash = hashlib.md5(force_bytes(pwhash+"salt"+username)).hexdigest()
if hash == user.password:
# update the user's password if you want, so you can phase out this backend
user.set_password(password)
user.save(update_fields=["password"])
return user
except UserModel.DoesNotExist:
UserModel().set_password(password)
このコードはまだテストしていませんが、宣伝どおりに動作するはずです。さらに、新しいユーザーと競合することはなく、古いユーザーのパスワードは新しいハッシュ アルゴリズムに更新されます (デフォルトは PBKDF2+SHA256 ですか?よくわかりません)。
user.password
2 番目のオプションは、フィールドが のように見えるようにデータベースを変更する 1 回限りのスクリプトを作成することlegacymd5$username+salt$hash
です。その後、カスタム パスワード ハッシュを計画どおりに記述できます。