sailsCasts

Learning about sails.js one screencast at a time.

Building a Sails Application: Ep24 - Correcting a publishUpdate Event and Adding a Policy to the User Controller's Subscribe Action

| Comments

Transcript

Howdy and welcome back.

I want to clean-up a use case that will unfortunately crash the server. The situation occurs if a user creates an account and then while they are logged-in a different user with admin privileges deletes them from the database. When the deleted user attempts to sign out the following server error occurs: TypeError: Cannot read property ‘name’ of undefined

This is because publishUpdate tries to send the user.name attribute and the user instance no longer exists. This is an easy fix, let’s head over to the session controller. We can wrap the userUpdate(), userPublish(), req.session.destroy(), and res.redirect() methods in an if statement that checks whether a user exists. If the user doesn’t exist then we’ll just redirect to session/new via res.redirect(‘/session/new’);

If the user does exist we’ll let just pass through to our existing logic. So now when we try to do the same use case, the browser is redirected to session/new.

One other change I want to make is to prevent the socket from subscribing to the user model events unless the user is authenticated. To do this, we’ll modify the authenticated policy so that it looks for req.session.User, if it exists, the user is authenticated, and if not, we send a 403. We’ll then use that policy in policies.js within the config folder for the subscription action of the user controller. By doing this, the socket cannot subscribe to /user/subscribe unless the user is authenticated. Let’s check it out.

So now, when the user logs in, the non-authenticated socket does not respond to the event because they are not yet authenticated and therefore not subscribed. Once the other user logs in, however, they receive the original user’s logout event.

Thanks for watching.

Comments