ユーザーが OAuth を使用してログインできるようにしたい CakePHP アプリがあります。
最後からユーザー情報を取得しているため、OAuth 会話が正しく機能しているようで、トークンをusers
テーブルに正常に保存できます。
私の質問はばかげているかもしれませんが、与えられたトークンをいつ使用する必要があるかを考えています。ユーザーの ID を Cookie に保存し、サイトに「戻ってくる」たびに DB からトークンを取得し、それを使用して詳細を再確認する必要がありますか?
OAuth を使用しているユーザーのパスワードをまったく取得していないので、これらの人々の Auth をバイパスするか、トークンの 1 つを 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());
}
}
}