gigablah / silex-oauth

Silex provider for lusitanian/oauth.
MIT License
109 stars 24 forks source link

Change the roles #7

Closed italolelis closed 9 years ago

italolelis commented 10 years ago

Hi man,

I have a question, this is not an issue, but I didn't find where to put this doubt.

I'm using google login and every user that logs in the system, is recieving a ROLE_USER role.... Is there a way where I can check if an especific user is trying to login and change his role to ROLE_ADMIN or something?

The other question I have. Is there a way to block a especific google email to login? Like @exemple.com only users with this email can login through google.

Sorry to bother you with this silly questions. Appreciate the help.

harryo commented 9 years ago

I had the same problem, finally solved it by copying the OAuthInMemoryUserProvider, and adapting it. (Would be nicer to extend it, but variables are private.)

In method loadUserByOAuthCredentials() change these lines:

$user = new StubUser($token->getUsername(), '', $token->getEmail(), array('ROLE_USER'), true, true, true, true);

to

$roles = $this->getRolesByEmail($token->getEmail());
$user = new StubUser($token->getUsername(), '', $token->getEmail(), $roles, true, true, true, true);

and add a method like this:

/**
 * Determine the assigned roles from the email address
 * @param  string $email the email address
 * @return array        assigned roles
 */
private function getRolesByEmail($email) {
    $roles = array('ROLE_USER');
    $domain = substr(strrchr($email, "@"), 1);
    if ($domain === '@exemple.com') {
        $roles[] = 'ROLE_MEMBER';
    }
    return $roles;
}

Finally, register the SecurityServiceprovider:

$app->register(new Silex\Provider\SecurityServiceProvider(), array(
    'security.firewalls' => array(
        'default' => array(
            ...
            'users' => new Tools\MyCopiedUserProvider()
        )
    ),
    'security.access_rules' => array(
        array('^/knownusers', 'ROLE_USER'),
        array('^/members', 'ROLE_MEMBER'),
    )
));