示例#1
0
 public static function login_or_register($strategy)
 {
     $token = $strategy->callback();
     switch ($strategy->name) {
         case 'oauth':
             $user_hash = $strategy->provider->get_user_info($strategy->consumer, $token);
             break;
         case 'oauth2':
             $user_hash = $strategy->provider->get_user_info($token);
             break;
         case 'openid':
             $user_hash = $strategy->get_user_info($token);
             break;
         default:
             throw new Exception("Unsupported Strategy: {$strategy->name}");
     }
     if (\Auth::check()) {
         list($driver, $user_id) = \Auth::instance()->get_user_id();
         $num_linked = Model_Authentication::count_by_user_id($user_id);
         // Allowed multiple providers, or not authed yet?
         if ($num_linked === 0 or \Config::get('ninjauth.link_multiple_providers') === true) {
             // If there is no uid we can't remember who this is
             if (!isset($user_hash['uid'])) {
                 throw new Exception('No uid in response.');
             }
             // Attach this account to the logged in user
             Model_Authentication::forge(array('user_id' => $user_id, 'provider' => $strategy->provider->name, 'uid' => $user_hash['uid'], 'access_token' => isset($token->access_token) ? $token->access_token : null, 'secret' => isset($token->secret) ? $token->secret : null, 'expires' => isset($token->expires) ? $token->expires : null, 'refresh_token' => isset($token->refresh_token) ? $token->refresh_token : null, 'created_at' => time()))->save();
             // Attachment went ok so we'll redirect
             \Response::redirect(\Config::get('ninjauth.urls.logged_in'));
         } else {
             $auth = Model_Authentication::find_by_user_id($user_id);
             throw new Exception(sprintf('This user is already linked to "%s".', $auth->provider));
         }
     } else {
         if ($authentication = Model_Authentication::find_by_uid($user_hash['uid'])) {
             // Force a login with this username
             if (\Auth::instance()->force_login($authentication->user_id)) {
                 // credentials ok, go right in
                 \Response::redirect(\Config::get('ninjauth.urls.logged_in'));
             }
         } else {
             \Session::set('ninjauth', array('user' => $user_hash, 'authentication' => array('provider' => $strategy->provider->name, 'uid' => $user_hash['uid'], 'access_token' => isset($token->access_token) ? $token->access_token : null, 'secret' => isset($token->secret) ? $token->secret : null, 'expires' => isset($token->expires) ? $token->expires : null, 'refresh_token' => isset($token->refresh_token) ? $token->refresh_token : null)));
             \Response::redirect(\Config::get('ninjauth.urls.registration'));
         }
     }
 }