django-stubs icon indicating copy to clipboard operation
django-stubs copied to clipboard

`user_passes_test` should take in `AUTH_USER_MODEL`

Open ljodal opened this issue 2 years ago • 6 comments

Starting with #1038 user_passes_test is typed to accept AbstractBaseUser | AnonymousUser. While technically correct it would be great if the mypy plugin could update this to be the actual model defined in settings. For example we have code like this that now complains:

@user_passes_test(lambda u: u.is_superuser)
def my_view():
    ...

ljodal avatar Jul 13 '22 08:07 ljodal

Nice idea. One thing to note: it should replace with AUTH_USER_MODEL | AnonymousUser, not with authenticated user only.

sterliakov avatar Jul 13 '22 18:07 sterliakov

Yes, I'm working on a fix for this.

Edit: it might be actually more complicated, as I'm not sure how the mypy api allows overriding the type information of a decorator.

PIG208 avatar Aug 08 '22 19:08 PIG208

A way to solve this might be changing the way we handle AUTH_USER_MODEL. We can create a stub-only dummy type _AuthUser, and use get_type_analyze_hook() to replace this type with the proper model or fall back to AbstractBaseUser. Then we can use this dummy type in the stub wherever an authenticated user is expected and also remove the old set_auth_user_model_as_type_for_request_user thing.

PIG208 avatar Sep 24 '22 02:09 PIG208

For example we have code like this that now complains ...

with the release of 1.13.0, I imagine more people are likely to find this issue. Is there a sensible way to annotate my code so that django-stubs does not complain?

dimbleby avatar Nov 03 '22 21:11 dimbleby

@PIG208 Are you willing to PR your suggested behavior?

Archmonger avatar Jan 28 '23 11:01 Archmonger

I've also stumbled upon this... I've got this decorator:

def any_permission_required(*args):
    return user_passes_test(lambda u: any(u.has_perm(perm) for perm in args))

and when I try to run mypy I get:

users\urls.py:8: error: Item "AbstractBaseUser" of "AbstractBaseUser | AnonymousUser" has no attribute "has_perm"  [union-attr]

spapas avatar Feb 02 '24 22:02 spapas