How to get auth to trigger on a button
Hey @Kappa,
I’m sure you know the answer to this, but I’m working with Wasp and it's pretty easy to require authentication for a page. However, I want my users to be able to access a page (a mechanical engineering calculator), but only require them to log in when they click the "Calculate" button to run the calculation (note i also want to save the inputs so that when they log in they dont lose them). Additionally, I want new users to get 3 free tokens (calculations) before they need to purchase a subscription. Let’s focus on the authentication part for now, but I think Wasp might have a good solution for the token system as well.
1 Reply
Hi @khb. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
To address your specific requirement of triggering authentication on a button click rather than page load in Wasp, you'll need to take a slightly different approach than using the
authRequired
flag for the page. Here's how you can achieve this:
1. First, don't use authRequired: true
for the page containing your calculator. This allows all users to access the page initially.
2. In your React component for the calculator page, use the useAuth()
hook to check the user's authentication status. This hook is provided by Wasp when you set up authentication.
3. Create a wrapper function for your "Calculate" button that checks the authentication status before proceeding with the calculation.
Here's a basic example of how you might implement this:
This approach allows you to:
1. Keep the page accessible to all users
2. Check authentication status when the "Calculate" button is clicked
3. Save the inputs before redirecting to login, so you can restore them later
To restore the inputs after login, you can add logic to your calculator page to check for saved inputs in localStorage
when the component mounts.
Regarding the token system for free calculations, Wasp doesn't have a built-in solution for this specific use case. You would need to implement this yourself, likely by:
1. Adding a tokens
field to your User
entity
2. Creating an action to decrement tokens when a calculation is performed
3. Checking the token count before allowing a calculation
For more details on using authentication in Wasp, you can refer to the Auth Overview documentation.
Remember, this approach requires careful handling of user data and proper security measures. Always validate and sanitize user inputs on the server side, and ensure that sensitive calculations are performed securely.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
Sorry @khb, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist:
Perhaps try again in 15mins?