[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