Force User Login from anvil.server.route

What I’m trying to do:
Make sure my users are authenticated when they access certain routes in my app with the normal anvil login form.

What I’ve tried and what’s not working:
I could just add the login_with_form function to every form I return from the server with the route decorator, but then I wouldn’t be able to secure the data I send back from the route with the form to check that the user has access and would have to make a whole new server call once the page loads to do so, which is a lot less efficient.

I know setting authenticate_users to True would force the user to login, but with the plain html login form.

Hi @duncan_richards12,

The thing to do here is to call anvil.users.get_user() from the @route function. That way, you can tell whether the user is already logged in – if they’re not logged in, you can serve them a Form with preloaded data, and if they’re not you can serve a 302 redirect to the homepage where they can log in. (Or you can serve a form that prompts for login and then opens your target data, or serve the public version of that resource, or whatever you like!)

4 Likes

I see, when I got the None result from the route, I too quickly assumed that it was like the OG http routes. Thanks!