Force user to redirect if he is logged in

Hi guys,
I have a login page and server action “login” which uses Security Provider to log in user based on email and password.
On the client side, I use Dynamic event to redirect user on Success to the Home page.
Pretty standard stuff.

The problem.
If user is logged in and goes to /login page, he still see login form. He can fill it and log in again. Everything works, but this is not the most desired logic.
Should be: if user is logged in and goes to /login page, he is redirected to /home page.

Question. How to do this redirect if user is logged in?
How can it be done on the client side? I call server action only after user is pressing “login” button, but redirect should be done if he is just opening this page.

Thanks!

Hello,
You can do this by creating a server action, which returns the user details as explained here:

Then run it on page load, if the user is logged the server action will return data, otherwise it will be empty.
So, with the browser component redirect if the server action returns any data.

Or you can use PHP code to check if the session is created and redirect. The session is only created after successful login.

Thanks, @Teodor, it helped!

I, tried option with server connect action, but got stuck with redirect.

What I did:

  1. Created Serverconnect action “checkuser” with DB connection, Security Provider and DB Single query returning User.
  2. Added ServerConnect to the clientside fetching this action, and also Dynamic Event On Success, which makes Browser redirect to with conditional route:
    checkUserSC.data.currentUser ? ‘/’ : ‘/login’

When the user is logged in it works fine - redirects to the Home page. BUT, the problem is when the user is not logged in, the second route (’/login’) redirects again and again, because obviously it redirects, calls “checkuser” gets null and redirects again.

I need a solution, when Browser component redirects ONLY if checkUserSC.data.currentUser is not empty, and don’t do anything when checkUserSC.data.currentUser is empty.
Unfortunately, the popular way I found here with the the syntax of route (condition ? option1 : option2 ) means that Browser component works every time just choosing route.

Is there any solution here, @Teodor?

Hey Alex,

Shouldn’t you just have the redirect on the success event of the the checkuser server connect action and remove the checkUserSC.data.currentUser ? ‘/’ : ‘/login’ stuff?

checkuser will execute on page load, if it is successful (meaning a user is logged in) it will redirect. If it is not successful (because the user is not logged in and therefore the server side will return unauthorized instead of success) do nothing. Then have a redirect on the form action where somebody logs in, and redirect on success for that as well.

–Ken