Question

I recently coded up a 'friend' capability with my website. The way it works is if a user wants to 'friend' another user, sending a request creates a user_connection record with the original user set at the user_id and the requested user set as the contact_id. If the other user accepts the request, then another user_connection record will be made, with the user_id and contact_id reversed. If both user_connections exist, then the two users are considered friends. This currently gives each user access to any buildings shared between the two users.

I was wondering if there was some way I could enforce my user_connection model to make sure that whoever is creating the record gets set as the user_id. Otherwise it seems that someone could spoof the user_connection create request to make themself a contact of whomever they want, and then could spoof building shares using the same methodology. Are there any built in methods to prevent this?

My first thought was to have an initializer that always set the user_id to the current_user's id, but it appears that current_user is outside of the context of the model.

Était-ce utile?

La solution

Don't allow user_id to be provided as a parameter, using strong params.

So, you could create the relation like that:

@friendship = current_user.friendships.new(contact_id: other_user.id)

Also make sure you provide the correct condition for current_user.

That's it... user_id is implied but never provided.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top