[SOLVED] Live subscription won't close after user logout

Hi! I am trying to check if an user if active or not through live queries and I hope I’m not using them wrong. When the connection is ‘open’ it works and shows that the user is active, however when the user logs out it still shows that he’s active.I believe that’s when the connection should be ‘closed’ and the user activity should be marked as ‘false’

 const query2 = new Moralis.Query("Contacts")
  query2.equalTo("user", "bobo")
  const result = await query2.first()
  const subscription2 = await query2.subscribe()
  subscription2.on('open',async()=>{
    setUserdata(result)
    result.set("isActive",true)
    result.save()
    console.log("subsctiption contact open")
  })

 subscription2.on('close',async()=>{
    result.set("isActive",false)
    result.save()
    console.log("subscription closed")
  })

Can someone please help me figure out what might be the problem?

Hey how about trying this with cloud functions.
For log in:
beforeLogin
The beforeLogin trigger can be used for blocking an account from logging in (for example, if they are banned), recording a login event for analytics, notifying a user by email if a login occurred at an unusual IP address and more.

Moralis.Cloud.beforeLogin(async request => {
  const { object: user }  = request;
  // Set user active to true here
user.set("isActive",true);
user.save();
});

For Logout:
The afterLogout trigger can be used for clean-up actions after a user logs out. The triggers contain the session object that has been deleted on logout. From this session object, you can determine the user who logged out to perform user-specific tasks.

Moralis.Cloud.afterLogout(async request => {
  const { object: session }  = request;
  const user = session.get('user');
  user.set('isActive', false);
  user.save(null,{useMasterKey:true});
});

Hope this helps :v:

Thank you for your help, I really appreciate it! I did as you suggested but the “beforeLogin” trigger won’t work as the value doesn’t change from false to true.

maybe try to use master key in the save function even in beforeLogin

1 Like

Yes, now it works! Thank you so much for the support!

3 Likes