我正在尝试将 facebook 连接到我的 cakephp 应用程序。我正在使用 Nick 的 Facebook 插件。
我想这样实现它
我做了什么 - 我已按照尼克的指示来实现它,当我单击“登录”时 - 它会连接到我的应用程序。但我不明白如何创建与 Facebook Connect Id 关联的用户名和密码。并将其用于 FB 代币。
这是我正在使用的 Facebook 登录方法(稍作编辑和注释):
public function facebook($authorize = null) {
App::import('Lib', 'Facebook.FB');
$Fb = new FB();
$session = $Fb->getSession();
// not logged into Facebook and not a callback either,
// sending user over to Facebook to log in
if (!$session && !$authorize) {
$params = array(
'req_perms' => /* the permissions you require */,
'next' => Router::url(array('action' => 'facebook', 'authorize'), true),
'cancel_url' => Router::url(array('action' => 'login'), true)
);
$this->redirect($Fb->getLoginUrl($params));
}
// user is coming back from Facebook login,
// assume we have a valid Facebook session
$userInfo = $Fb->api('/me');
if (!$userInfo) {
// nope, login failed or something went wrong, aborting
$this->Session->setFlash('Facebook login failed');
$this->redirect(array('action' => 'login'));
}
$user = array(
'User' => array(
'firstname' => $userInfo['first_name'],
'lastname' => $userInfo['last_name'],
'username' => trim(parse_url($userInfo['link'], PHP_URL_PATH), '/'),
'email' => $userInfo['email'],
'email_validated' => $userInfo['verified']
),
'Oauth' => array(
'provider' => 'facebook',
'provider_uid' => $userInfo['id']
)
);
$this->oauthLogin($user);
}
这为我提供了一个数组,其中包含我可以从 Facebook 获取的所有用户详细信息并调用
::oauthLogin
,它要么使用给定信息登录用户,要么要求用户填写缺失的详细信息和/或在中创建新的用户记录数据库。您从 Facebook API 获得的最重要的部分是 $userInfo['id']
和/或电子邮件地址,您可以使用其中任何一个来识别数据库中的用户。如果您使用 AuthComponent,您可以使用 $this->Auth->login($user_id)
“手动”登录用户,其中 $user_id
是您自己的数据库中的用户 ID。
private function oauthLogin($data) {
$this->User->create();
// do we already know about these credentials?
$oauth = $this->User->Oauth->find('first', array('conditions' => $data['Oauth']));
if ($oauth) {
// yes we do, let's try to log this user in
if (empty($oauth['User']['id']) || !$this->Auth->login($oauth['User']['id'])) {
$this->Session->setFlash('Login failed');
}
$this->redirect('/');
}
// no we don't, let's see if we know this email address already
if (!empty($data['User']['email'])) {
$user = $this->User->find('first', array('conditions' => array('email' => $data['User']['email'])));
if ($user) {
// yes we do! let's store all data in the session
// and ask the user to associate his accounts
$data['User'] = array_merge($data['User'], $user['User']);
$data['Oauth']['user_id'] = $user['User']['id'];
$this->Session->write('Oauth.associate_accounts', $data);
$this->redirect(array('action' => 'oauth_associate_accounts'));
}
}
// no, this is a new user, let's ask him to register
$this->Session->write('Oauth.register', $data);
$this->redirect(array('action' => 'oauth_register'));
}
别再犹豫了。这是一篇优秀的文章,它将全程指导您(不包括任何现成的插件):
将 Facebook Connect 与 CakePHP 的 Auth 组件集成
只需遵循其中描述的方法即可。
干杯, 我^e