the last days I was wondering how is it done? How can you authenticate/authorize that the user is allowed to request the data via AJAX.
For now I am using SESSIONS for auth.But this is only a minor protection.
Let´s say I have some function called addUserToGroup($user_id,$group_id), which is called via
EXAMPLE: www.mysite.com/addUserToGroup/1/2 ( user_id = 1 , group_id = 2 )
How can I check if this user is really allowed to join group_id=2? Everyone could just POST data to my server...
One solution I found is using jcryption (public/private key method). But I think,there must be an easier way to somehow check if user_id = 1 is allowed to join group_id = 2.
Thanks in advance!
I believe your question is about authorization, not authentication. If I'm right, then presumably you already know who the user is (authentication, perhaps using a cookie or something).
Now, you have to come up with a way of determining what they are allowed to do (authorization).
Authorization logic is really a key design decision. As such, it's non-trivial and depends heavily on the shape of your data model and architecture of your application.
If you can consistently determine whether this should be allowed by applying rules to the data, such as in Quentin's response above (where living in Region 2 is enough to make it such that the User may join Group 2), then it's usually simplest to put this logic in your entity model. In that case, I'd either create a method on User to check whether they can join the group...
function canJoinGroup($group) {
//if(all is well), then:
return true
}
Or create a method to join them which throws an error if disallowed:
function joinGroup($group) {
//if(all is well), then:
return true;
//otherwise:
throw new Exception("User ". $this->id ." cannot join group " . $group->id);
}
You could also add a function to Group which delegates to this new User function:
function addUser($user) {
$user->joinGroup($this);
}
OTOH, If the decisions about who can do what are based on more granular permissions, or based on information an administrator or user needs to be able to change at runtime, then you will have to get a lot fancier. A commonly-used, versatile, and flexible approach is called Role-Based Access Control (aka RBAC).
This can get extremely sophisticated, but the core concept, applied to your case, is that you have a User, and Entity (the Group) and an Operation (join). You need to determine whether User 1 is allowed to do the Operation called 'join' with Group 2 as an argument.
In order to do this, you will have to keep a set of rules somewhere, and then do two things:
I won't get into the low-level details of this use case. Suffice it to say that, if what you're trying to accomplish today will eventually need to grow into a fairly sophisticated permissions system, you'd do well to study up on RBAC.