2013-02-26 110 views
4

我有一個CakePHP應用程序,我希望我的用戶能夠使用OAuth登錄到。使用OAuth進行與CakePHP 2.3的身份驗證

我似乎有OAuth會話正常工作,因爲我得到的用戶信息的結束,並可以將標記保存到我的users表罰款。

我的問題可能是一個愚蠢的,但我想解決什麼時候需要使用我給予的令牌。我是否應該將用戶的ID存儲在cookie中,並且每當他們回到我的網站時,都會從數據庫中獲取令牌,然後我們再次檢查他們的詳細信息?

我沒有得到OAuth用戶的任何密碼,所以我應該爲這些人繞過Auth,或者使用其中一個令牌作爲CakePHP的密碼?


這裏是我的UsersController的登錄和oauth2callback部分:

<?php 
class UsersController extends AppController { 

    public function login() { 
     if ($this->request->is('post')) { 
      if ($this->Auth->login()) { 
       $this->redirect($this->Auth->redirect()); 
      } else { 
       $this->Session->setFlash(__('Invalid username or password')); 
      } 
     } else { 
      $client = $this->getGoogleClient(); 
      $authUrl = $client->createAuthUrl(); 
      $this->set(array('GoogleAuthUrl' => $authUrl)); 
     } 
    } 

    public function oauth2callback() { 
     $client = $this->getGoogleClient(); 

     if (isset($this->request->query['code'])) { 
      $client->authenticate($this->request->query['code']); 
      $this->Session->write('token', $client->getAccessToken()); 
      $this->redirect('oauth2callback'); 
      return; 
     } 

     if ($this->Session->read('token')) { 
      $client->setAccessToken($this->Session->read('token')); 
     } 

     $accessToken = $client->getAccessToken(); 
     if ($accessToken) { 
      $oauth2 = new Google_Oauth2Service($client); 
      $user = $oauth2->userinfo->get(); 

      $token = json_decode($accessToken); 
      debug($token); 
      debug($user); 
      // We now have a user from Google. Either log them in, or create a new user 
      $id = $this->User->field('id', array('email' => $user['email'], 'oauth_id' => $user['id'])); 
      if (empty($id)) { 
       $new_user = $this->User->create(); 
       $new_user['User']['username'] = $user['email']; 
       $new_user['User']['email'] = $user['email']; 
       $new_user['User']['oauth_id'] = $user['id']; 
       $new_user['User']['oauth_token'] = $token->access_token; 
       $new_user['User']['oauth_expires'] = time() + $token->expires_in; 
       $new_user['User']['oauth_id_token'] = $token->id_token; 
       $new_user['User']['oauth_refresh_token'] = $token->refresh_token; 
       $new_user['User']['oauth_created'] = $token->created; 
       if ($this->User->save($new_user)) { 
        $new_user['User']['id'] = $this->User->id; 
        debug($new_user); 
        $this->Session->setFlash(__('Registration complete!')); 
        if ($this->Auth->login($new_user)) { 
        // return $this->redirect($this->Auth->redirectUrl()); 
        } 
        //$this->redirect(array('action' => 'index')); 
       } else { 
        $this->Session->setFlash(__('There was a problem with your registration. Please, try again.')); 
       } 

      } 

      // The access token may have been updated lazily. 
      $this->Session->write('token', $client->getAccessToken()); 
     } 
    } 

} 

回答

相關問題