0

I am writing a custom authentication backend (and a custom user model) to check if a user account is locked or expired. I see that in all the examples of authentication backend return value is either a User object or None. And the only exception generated is User.DoesNotExist.

My question is how should I go about returning different results (e.g. account is locked or expired or max number of login attempts have reached)?

Should I raise custom exceptions or there is another way to do this?

I am using Django 1.5alpha.

EDIT: I need to get multiple statuses to display appropriate message to a user and redirect to an appropriate view.

4

2 に答える 2

1

ドキュメントに記載されているように:

どちらの場合でも、認証は取得した資格情報をチェックし、資格情報が有効な場合は、それらの資格情報に一致するユーザー オブジェクトを返す必要があります。それらが有効でない場合は、None を返す必要があります。

ロックされている、有効期限が切れている、またはログイン試行の最大回数に達したアカウントは「無効」と見なさNoneれるため、これらの条件では返される必要があります。

基本的に、None(何らかの理由で) ログインがアクセスを拒否された場合は常に返されます。

于 2012-11-07T20:12:05.293 に答える
1

誰かが同じ質問をした場合に備えて、私はこれをしました。

class UserNotActivatedError(Exception):
    pass

class UserLockedError(Exception):
    def __init__(self, remaining_mins):
        self.remaining_mins = remaining_mins

# backend
def authenticate(self, email=None, password=None):
    if email is None or password is None:
        return None
    try:
        user = ExtUser.objects.get(email=email)
        user.last_login_attempt_at = timezone.now()
        if not use.is_active:
            raise UserNotActivatedError
        if user.is_locked:
            # Check when it was locked and found the duration
            sec_to_go = user.get_remaining_locktime()
            if sec_to_go:
                raise UserLockedError(sec_to_go)
        if user.check_password(password):
            user.last_login_at = timezone.now() 
            return user
        else:
            return None
    except User.DoesNotExist:
        return None

次に、ログイン フォームでこれらのエラーをキャッチし、適切な検証エラーをビューに渡すことができます。

于 2012-11-23T14:41:43.557 に答える