How to integrate Google login on a CakePHP REST API - rest

I am building an Android app that is interfaced with a CakePHP 3 web API. Since a RESTful API cannot rely on cookies, I understand that I need JSON web tokens (JWT) to make this happen, and would much prefer to use a google login. I already got the Android side to request a token from Google's API, but now I am lost on how to incorporate this into my API for authentication.
I've searched around for some tutorials, such as this one: http://blog.jainsiddharth21.com/2013/04/29/login-with-google-in-cakephp/, but it relies on session data. I'm building the API in CakePHP 3, so I've looked at some of the plugins, such as ADmad/JwtAuth, so maybe I could extend on this to allow google authentication, but I am not sure how.

Login With Gmail and Specific email address to allowed to login in CakePHP 3.x
Composer to install
"google/apiclient": "^2.0"
Required gmail with login
https://console.developers.google.com/apis/credentials?project=mdpms-187410&organizationId=1095988912954
Create project and create secret key and client id
Project in set name and redirect URL
NOTE:- redirect URL must be .com and .org domain
If you develop in local machine then create follow type of virtual host
example.com and example.org
Virtual host create then
Follow this step:
Set configuration file in app_globle.php
'Google' =>
[
'googleClientID' => '123456.apps.googleusercontent.com',
'googleClientSecret' => 'abcdefghi',
'googleRedirectUrl' => 'http://example.com/oauth2callback'
]
Gmail login route
//Google login
$routes->connect('/account/google-login', ['controller' => 'Account', 'action' => 'googlelogin'], ['_name' => 'account-google-login']);
$routes->connect('/oauth2callback', ['controller' => 'Account', 'action' => 'confirmlogin'], ['_name' => 'account-google-redirect-url']);
Google login action code:
/**
* Gmail login method
*/
public function googlelogin()
{
$client = new Google_Client();
$client->setClientId(Configure::read('Google.googleClientID'));
$client->setClientSecret(Configure::read('Google.googleClientSecret'));
$client->setRedirectUri(Configure::read('Google.googleRedirectUrl'));
$client->se
tScopes([
"https://www.googleapis.com/auth/userinfo.profile",
'https://www.googleapis.com/auth/userinfo.email'
]);
$url = $client->createAuthUrl();
$this->redirect($url);
}
Google redirect url Action
/**
* Gmail auth redirect action
* #return type gmail auth data
*/
public function confirmlogin()
{
$client = new Google_Client();
$client->setClientId(Configure::read('Google.googleClientID'));
$client->setClientSecret(Configure::read('Google.googleClientSecret'));
$client->setRedirectUri(Configure::read('Google.googleRedirectUrl'));
$client->setScopes([
"https://www.googleapis.com/auth/userinfo.profile",
'https://www.googleapis.com/auth/userinfo.email'
]);
$client->setApprovalPrompt('auto');
$usersTable = TableRegistry::get('Users');
if (isset($this->request->query['code'])) {
$client->authenticate($this->request->query['code']);
$this->request->Session()->write('access_token', $client->getAccessToken());
}
if ($this->request->Session()->check('access_token') && ($this->request->Session()->read('access_token'))) {
$client->setAccessToken($this->request->Session()->read('access_token'));
}
if ($client->getAccessToken()) {
$this->request->Session()->write('access_token', $client->getAccessToken());
$oauth2 = new Google_Service_Oauth2($client);
$user = $oauth2->userinfo->get();
try {
if (!empty($user)) {
if ((preg_match("/(#example\.com)$/", $user['email'])) || (preg_match("/(#example\.in)$/", $user['email']))) {
$result = $usersTable->find('all')
->where(['email' => $user['email']])
->first();
if (!empty($result)) {
$this->AccessControl->setUser($result->toArray(), false);
$this->Flash->set(__('You have successfuly logged in.'), ['element' => 'success']);
$this->redirect(['_name' => 'dashboard']);
} else {
$data = [];
$data['email'] = $user['email'];
$data['first_name'] = $user['givenName'];
$data['last_name'] = $user['familyName'];
$data['socialId'] = $user['id'];
$data['role_id'] = Configure::read('Role.loginWithGmailUserRole');
//$data matches my Users table
$entity = $usersTable->newEntity($data);
if ($usersTable->save($entity)) {
$data['id'] = $entity->id;
$this->AccessControl->setUser($data, false);
$this->Flash->set(__('You have successfuly logged in.'), ['element' => 'success']);
$this->redirect(['_name' => 'dashboard']);
} else {
$this->Flash->error(__('Invalid login.'));
//redirect to login action
$this->redirect(['_name' => 'account-login']);
}
}
} else {
$this->Flash->error(__('Your email is invalid for this application.'));
//redirect to login action
$this->redirect(['_name' => 'account-login']);
}
} else {
$this->Flash->error(__('Gmail infos not found.'));
//redirect to login action
return $this->redirect(['_name' => 'account-login']);
}
} catch (\Exception $e) {
$this->Flash->error(__('Gmail error.'));
return $this->redirect(['_name' => 'account-login']);
}
}
}

Related

Yii2 AuthClient set return page for Facebook client

I have a form for lead gen, which just get the user information (like name, gender, email) which can be filled out with Facebook. But the problem is, selecting to fill form with FB redirect to index page. How can i set the return page to some other view or action?
public function onAuthSuccess($cliente)
{
// TODO: fb login e retornar dados do perfil para o form
$fb = new Facebook([
'app_id' => MYAPPID,
'app_secret' => MYAPPSECRET
]);
try {
$token = $cliente->getAccessToken()->getToken();
// Returns a `Facebook\FacebookResponse` object
$usuario = $fb->get('/me?fields=email,name,gender,age_range',
$token)->getDecodedBody();
} catch(Exception $e) {
echo 'Error: ' . $e->getMessage();
exit;
}
return ; // actually doesn't matter, it always end redirecting to site/index
}
Auth config:
'auth' => ['class' => yii\authclient\AuthAction::className(),'successCallback' => [$this, 'onAuthSuccess']]
Add successUrl in Auth action config
'successUrl'=>'url'
it is an public property you can override its value in your function also
$this->action->successUrl = "url-with-data";
Note: this is for understanding purpose only, best way to generate dynamic urls would be using urlmanager

Redirect URL callback for facebook is not taking Base Url laravel 5

Hello everyone I'm trying to integrate facebook login using laravel5, In my code i have mentioned my redirect URL so it should go on below mentioned URL but when i'm trying to login with facebook my url is coming like this it's not taking my folder name see the difference in both URLs
http://localhost:8000/facebook/callback?code=xxxxx
Correct Url
http://localhost:8000/facebook/public/facebook/callback/
'facebook' => [
'client_id' => 'xxxxxxxxxxxxxxx',
'client_secret' => 'xxxxxxxxxxxxxxxxxxx',
'redirect' => 'http://localhost:8000/facebook/public/facebook/callback/',
],
This is my routes
Route::get('facebook/callback', 'Auth\AuthController#handleProviderCallback');
My controller
public function handleProviderCallback()
{
try {
$user = Socialite::driver('facebook')->user();
} catch (Exception $e) {
return redirect('facebook');
}
$authUser = $this->findOrCreateUser($user);
Auth::login($authUser, true);
return redirect()->route('home');
}

unable to to open redirected page after facebook authentication

i am using facebook connect under codeigniter.after authentication i want to redirect on success method of my controller
here is my controller:
class Welcome extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('Facebook_model');
}
function index()
{
$fb_data = $this->session->userdata('fb_data');
$data = array(
'fb_data' => $fb_data,
);
$this->load->view('welcome', $data);
}
function topsecret()
{
$fb_data = $this->session->userdata('fb_data');
if((!$fb_data['uid']) or (!$fb_data['me']))
{
redirect('welcome');
}
else
{
$data = array(
'fb_data' => $fb_data,
);
$this->load->view('topsecret', $data);
}
}
function success()
{
$this->load->view('welcome_message');
}
}
my model for facebook api access:
class Facebook_model extends CI_Model {
public function __construct()
{
parent::__construct();
$config = array(
'appId' => '261066574000678',
'secret' => ' 79e11f65449988965362f58e9a4aabd7',
'fileUpload' => true, // Indicates if the CURL based # syntax for file uploads is enabled.
);
$this->load->library('Facebook', $config);
$user = $this->facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
$profile = null;
if($user)
{
try {
// Proceed knowing you have a logged in user who's authenticated.
$profile = $this->facebook->api('/me?fields=id,name,link,email');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
$fb_data = array(
'me' => $profile,
'uid' => $user,
'loginUrl' => $this->facebook->getLoginUrl(
array(
'scope' => 'email,user_birthday,publish_stream', // app permissions
'redirect_uri' => 'https://sanjay.localhost.com/index.php/welcome/success' // URL where you want to redirect your users after a successful login
)
),
'logoutUrl' => $this->facebook->getLogoutUrl(),
);
$this->session->set_userdata('fb_data', $fb_data);
}
}
since i am testing this on localhost host,i also edited my host file and changed my localhost hostname to sanjay.localhost.com.redirect happens but not happens..i think may be because of querystring.when redirects happens redirect uri is
=">https://sanjay.localhost.com/index.php/welcome/success?state=ff5712299510defa&code=AQCaD-FAd1shuW#=
i am not understanding how to handle state and code inside of query string.
please help.
Thank you for contacting me on my blog. First of all, Facebook is discontinued the localhost support. Her is the link https://developers.facebook.com/bugs/128794873890320.
I have not developed any app using codeigniter, I use CakePHP but the auth follow should be same.
1. Create a fb_login function in user controller.
2. This function will follow this logic.
a. Use $facebook->getUser() to get user id.
b. Then use $facebook->api('/me') to be sure.
3.If you get FacebookApiException then send user to login with Facebook. If you use official SDK then the current url will be added to redirect url.
4.the Facebook will redirect your user after sign in. so you will get data using $facebook->getUser(). Save this data in session for further use in you app. then redirect user to you control page or any other page. CakePHP has setFlash() function wich show what ever msg set in the control panel in view. I think Codeignator should have some thing like this. If not you can simply set a msg in session and redirect user. Then unset the msg after showing the msg.
Here is full code
$uid = $facebook->getUser();
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//echo $e->getMessage();
$uid = null;
}
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'publish_stream,offline_access,email'
),''
);
if (!$uid) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
//search using uid on your user table to check if the use is returnign user or new user.
if($new_user ==1)
{
$this->Session->setFlash('please sign up');
//redirect to sign up
}
else
{
$this->Session->setFlash('you are good lad');
//reditect to control panel
}

Zend Gmail Oauth: How to get authenticated user profile?

I am using Zend Gmail Oauth 1.0 for implementing login with Gmail feature.
After successful authentication, how can I get authenticated user's profile, specifically user's unique gmail id? Here is the code:
$THREE_LEGGED_SCOPES = array('https://mail.google.com/',
'https://www.google.com/m8/feeds');
$options = array(
'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
'version' => '1.0',
'consumerKey' => $THREE_LEGGED_CONSUMER_KEY,
'consumerSecret' => $THREE_LEGGED_CONSUMER_SECRET_HMAC,
'callbackUrl' => getCurrentUrl(),
'requestTokenUrl' => 'https://www.google.com/accounts/OAuthGetRequestToken',
'userAuthorizationUrl' => 'https://www.google.com/accounts/OAuthAuthorizeToken',
'accessTokenUrl' => 'https://www.google.com/accounts/OAuthGetAccessToken'
);
if ($THREE_LEGGED_SIGNATURE_METHOD == 'RSA-SHA1') {
$options['signatureMethod'] = 'RSA-SHA1';
$options['consumerSecret'] = new Zend_Crypt_Rsa_Key_Private(
file_get_contents(realpath($THREE_LEGGED_RSA_PRIVATE_KEY)));
} else {
$options['signatureMethod'] = 'HMAC-SHA1';
$options['consumerSecret'] = $THREE_LEGGED_CONSUMER_SECRET_HMAC;
}
$consumer = new Zend_Oauth_Consumer($options);
/**
* When using HMAC-SHA1, you need to persist the request token in some way.
* This is because you'll need the request token's token secret when upgrading
* to an access token later on. The example below saves the token object
* as a session variable.
*/
if (!isset($_SESSION['ACCESS_TOKEN'])) {
if (!isset($_SESSION['REQUEST_TOKEN'])) {
// Get Request Token and redirect to Google
$_SESSION['REQUEST_TOKEN'] = serialize($consumer->getRequestToken(array('scope' => implode(' ', $THREE_LEGGED_SCOPES))));
$consumer->redirect();
} else {
// Have Request Token already, Get Access Token
$_SESSION['ACCESS_TOKEN'] = serialize($consumer->getAccessToken($_GET, unserialize($_SESSION['REQUEST_TOKEN'])));
header('Location: ' . getCurrentUrl(false));
exit;
}
} else {
// Retrieve mail using Access Token
$accessToken = unserialize($_SESSION['ACCESS_TOKEN']);
}
near as I can tell you can't.
Gmail doesn't have an api just a read only feed.
However if you want that feed the scope url is:
https://mail.google.com/mail/feed/atom/
There are some api's for working with gmail accounts in the context of Google Apps.

How to handle Facebook's signed_request for iFrame Canvas applications?

I'm developing an iFrame Canvas application for Facebook using CakePHP, its Auth component, WebTechNick's Facebook plugin and OAuth for canvas pages (I've enabled this in the Facebook Developer app options). I would like users to be able to use the application after adding it to their profile (by requesting email and publish_stream permissions) by visiting http://apps.facebook.com/myapp/ or as a tab in their profile.
Requesting permissions is not the problem. The user is redirected to the permissions request page and then redirected to a callback method which requests an access_token, as per this tutorial.
After this callback the user is redirected back to http://apps.facebook.com/myapp/ which shows their personal index page. This is also where the problems start. As soon as the aforementioned URI is loaded, the browser asks for a form resubmission, this happens every time I reload http://apps.facebook.com/myapp/. This is the case because Facebook wants to pass the (expected) signed_request parameter and I'm wondering what to do with it. It's not an empty variable, so do I need another validation method or redirect, perhaps?
How should I handle the procedure for the signed_request parameter and, more importantly how to get rid of this form resubmission dialog?
Some of my methods, they might be a bit of a mess due to all the experimentation of the past day.
beforeFilter, login and callback methods, in my UserController.php:
function beforeFilter() {
parent::beforeFilter();
if (empty($this->permissions)) {
$this->Auth->allow('login', 'logout', 'callback');
}
}
function login() {
$session = $this->facebook->getSession();
$login_url = 'https://graph.facebook.com/oauth/authorize?client_id=' . FACEBOOK_APP_ID . '&redirect_uri=' . MY_APP_URL . '/users/callback/&type=user_agent&&display=page&scope=' . FACEBOOK_APP_PERMISSIONS;
if($session){
try {
$uid = $facebook_client->getUser();
$me = $facebook_client->api('/me', $params);
print($me);
} catch (FacebookApiException $e) {
error_log($e);
}
} else {
$this->set('authorise', true);
$script = '$(document).ready(function() { facebookRequestPermissions("'.$login_url.'");});';
$this->set('script', $script);
}
}
function callback() {
function callFb($url, $params) {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => http_build_query($params),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_VERBOSE => true
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$params=array('client_id'=>FACEBOOK_APP_ID, 'type'=>'client_cred', 'client_secret'=>FACEBOOK_APP_SECRET);
$url = "https://graph.facebook.com/oauth/access_token";
$access_token = callFb($url, $params);
$access_token = substr($access_token, strpos($access_token, "=")+1, strlen($access_token));
if ($access_token) {
$this->redirect(FACEBOOK_APP_URL);
} else {
echo 'An error has occurred';
}
}
The JavaScript in the login method refers to this jQuery function, the Facebook JavaScript SDK is initialised in $(document).ready():
function facebookRequestPermissions(login_url) {
FB.getLoginStatus(function(response) {
if (response.status !== 'unknown') {
top.location.href=login_url;
}
});
}
The JavaScript function should only fire when a user is logged in, if not, a different landing page is shown.
I use some methods in an overall AppControler:
class AppController extends Controller {
var $components = array('RequestHandler', 'Session', 'Auth', 'Facebook.Connect');
var $helpers = array('Form', 'Time','Html','Javascript', 'Session', 'Facebook.Facebook');
protected $facebook;
protected $permissions;
private $user;
function beforeRender() {
//Save the username if it isn't already present
if ((int)$this->Auth->user('id') != '' && (string)$this->Auth->user('username') == '') {
$data = array('id' => (int)$this->Auth->user('id'), 'username' => (string)$this->user['username']);
$this->loadModel('User');
$this->User->save($data);
}
if (!empty($this->user) && !empty($this->permissions)) {
$this->set('currentUser', $this->Auth->user());
}
}
function beforeFilter() {
$this->Auth->autoRedirect = false;
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'index');
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
App::import('Lib', 'Facebook.FB');
$this->facebook = new FB();
$this->user = $this->facebook->api('/me');
$this->permissions = $this->facebook->api('/me/permissions');
}
}
EDIT:
This only seems an issue with Firefox. Chrome doesn't display the dialog, but instead does a silent refresh after which the signed_request parameter is empty, strangely enough. This isn't the case with Firefox, where the signed_request parameter remains the same after every prompted refresh (unless the iFrame content is cached), which is looping infinitely, it seems.
EDIT 2:
Still struggling with this, but I ended up disabling the OAuth 2.0 for Canvas option in the Facebook Developer application, which has resolved the form resubmission issue. Of course this is not a real solution, because OAuth 2.0 is becoming mandatory for canvas application on Facebook, I believe.
Since I can't test the whole thing I am not sure if this is right, but on the first sight your JavaScript function looks strange to me. It looks like you always redirect to the login url, although the user gave permission.
Refering to Facebook JavaScript SDK, the function should look like this:
function facebookRequestPermissions(login_url) {
FB.getLoginStatus(function(response) {
if (!response.session) {
top.location.href=login_url;
}
});
}
or, if you want to call .status:
if (response.status == 'unknown')
About your question concerning the signed_request: it is used to get some information, look at Authentication - Signed Request to see what exactly. You don't need another validation method.