kristian nissen kristian nissen - 1 month ago 9
Python Question

Django app with user authentication at project level

How do I handle user authentication inside an app when the authentication of users is handled at project level?

Im building an app where I need an authenticated user object when creating database entries, but I don't want to deal with the whole signup/sign-in logic inside the app, that should be delt with at a project level instead.

The app requires a user being signed in, but when developing I can't figure out where to put this. Can I "fake" an authenticated user inside the settings.py for the project?

Update

I realised that all I had to do, was to log into /admin after adding the @login_required to all my views. Then I'd get the data I needed using request.user and adding models.ForeignKey(User) to the models that needed it

Answer

There is no default way to fake a user, but you can easily implement that yourself.

You can simply create a view that logs in a hardcoded user.

def force_login(request):
    # this check is not really required, but probably a good idea
    if not settings.DEBUG:
        raise ImproperlyConfigured("Don't use the force_login view in production")
    user, created = User.objects.get_or_create(
        username='user',
        defaults={...})  # set whatever defaults you need
    user.backend = settings.AUTHENTICATION_BACKENDS[0]
    login(request, user)
    return HttpResponse('logged in')

Now you just have to add this view to your urls.py. An alternative approach would be to write this as a middleware.

class ForceAuthenticationMiddleware(object):
    """
    Ensures that the request has a logged in user.

    If there is no user, it logs in a default user and return a
    redirect.
    """

    def process_request(self, request):
        if request.user.is_authenticated:
            return
        user, created = User.objects.get_or_create(
            username='user',
            defaults={...})  # set whatever defaults you need
        user.backend = settings.AUTHENTICATION_BACKENDS[0]
        login(request, user)
        return HttpResponseRedirect(request.get_full_path())

Insert that middleware in your settings.MIDDLEWARE_CLASSES after 'django.contrib.auth.middleware.AuthenticationMiddleware',

Comments