I do have website of cakephp framwork & integrated with linkedin api. website do have import resume functionality and stores user details(imported from linkedin) in edit profile page.
I have indexController and its action is something like this:-
public function linkedinlogin()
{
if (isset($_GET['oauth_problem']))
{
if (isset($_SESSION['requestToken']))
{
unset($_SESSION['requestToken']);
}
if (isset($_SESSION['oauth_verifier']))
{
unset($_SESSION['oauth_verifier']);
}
if (isset($_SESSION['oauth_access_token']))
{
unset($_SESSION['oauth_access_token']);
}
$this->redirect("registration");
exit;
}
//$this->autoRender = false;
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
$this->set('PageHeading', __('Linkedin Login'));
$config['base_url'] = 'http://upitchnew.inheritxserver.net/index/registration';
if (isset($_SESSION['user_id']))
{
$config['callback_url'] = 'http://upitchnew.inheritxserver.net/index/linkedinlogin?tc_id=' . $_SESSION['user_id'] . '&tc_id1=' . $_SESSION['user_ids'];
}
else
{
$config['callback_url'] = 'http://upitchnew.inheritxserver.net/index/linkedinlogin?tc_id=' . $_REQUEST['tc_id'] . '&tc_id1=' . $_REQUEST['tc_id1'];
}
$config['linkedin_access'] = 'linkedin_access';//LinkdingAccess key
$config['linkedin_secret'] = 'linkedin_secret';//Linkdin Scret key
//=require('../Vendor/linkedin/OAuth.php');
require('../Vendor/linkedin/linkedin.php');
# First step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url']);
if (isset($_REQUEST['oauth_verifier']))
{
$_SESSION['oauth_verifier'] = $_REQUEST['oauth_verifier'];
if (isset($_SESSION['requestToken']))
{
$linkedin->request_token = unserialize($_SESSION['requestToken']);
}
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->getAccessToken($_REQUEST['oauth_verifier']);
$_SESSION['oauth_access_token'] = serialize($linkedin->access_token);
$this->redirect($config['callback_url']);
//header("Location: " . $config['callback_url']);
exit();
}
else
{
if (isset($_SESSION['requestToken']) && $_SESSION['requestToken'] != '')
{
if (isset($_SESSION['oauth_access_token']) && $_SESSION['oauth_access_token'] != '')
{
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->access_token = unserialize($_SESSION['oauth_access_token']);
}
else
{
//$linkedin->debug = true;
$linkedin->getRequestToken();
$_SESSION['requestToken'] = serialize($linkedin->request_token);
$this->redirect($linkedin->generateAuthorizeUrl());
// echo '<script>window.location.href="'.$linkedin->generateAuthorizeUrl().'"</script>';
//header("Location: " . $linkedin->generateAuthorizeUrl());
exit();
}
}
else
{
//$linkedin->debug = true;
$linkedin->getRequestToken();
$_SESSION['requestToken'] = serialize($linkedin->request_token);
$this->redirect($linkedin->generateAuthorizeUrl());
//echo '<script>window.location.href="'.$linkedin->generateAuthorizeUrl().'"</script>';
//header("Location: " . $linkedin->generateAuthorizeUrl());
exit();
}
}
}
This action has called once you click on import resume button, Instead of loading login with linkedin page, a page keeps loading and do not redirect to (linkedin)login page.
generateAuthorizeUrl() has called meanwhile:-
$_SESSION['requestToken'] = serialize($linkedin->request_token);
$this->redirect($linkedin->generateAuthorizeUrl());
generateAuthorizeUrl function is something like this:-
function generateAuthorizeUrl()
{
if (isset($_SESSION['user_id']))
{
$this->user_id = $_SESSION['user_id'];
}
if (isset($_SESSION['user_ids']))
{
$this->user_ids = $_SESSION['user_ids'];
}
$consumer = $this->consumer;
$request_token = $this->request_token;
return $this->authorize_path . "?oauth_token=" . $request_token->key . "&tc_id=" . $this->user_id . "&tc_id1=" . $this->user_ids;
}
Any help would be appreciated.
Man!! sucks! It was firewall issue linkedin is using https://api.linkedin.com/uas/oauth/authorize?oauth_token=auth_token url while processing with importing user details! and that url was blocked via Sophos securities.
So it neither showing any error or anything else just keeps loading..
Issue Resolved.
Related
I am using the github repository code here: https://github.com/hunzinker/CakePHP-Auth-Forgot-Password
I have used the following function in my UsersController.php. I get the error Undefined index: token on the line that has a comment before it. What should I change?
/**
* Allow user to reset password if $token is valid.
* #return
*/
function reset_password_token($reset_password_token = null) {
if (empty($this->data)) {
$this->data = $this->User->findByResetPasswordToken($reset_password_token);
if (!empty($this->data['User']['reset_password_token']) &&
!empty($this->data['User']['token_created_at']) &&
$this->__validToken($this->data['User']['token_created_at'])
) {
$this->data['User']['id'] = null;
$_SESSION['token'] = $reset_password_token;
} else {
$this->Session->setflash(
'The password reset request has either expired or is invalid.'
);
$this->redirect('/users/login');
}
} else {
//ERROR ON THE NEXT LINE HERE UNDEFINED INDEX: TOKEN
if ($this->data['User']['reset_password_token'] != $_SESSION['token']) {
$this->Session->setflash(
'The password reset request has either expired or is invalid.'
);
$this->redirect('/users/login');
}
$user = $this->User->findByResetPasswordToken(
$this->data['User']['reset_password_token']
);
$this->User->id = $user['User']['id'];
if ($this->User->save($this->data, array('validate' => 'only'))) {
$this->data['User']['reset_password_token'] =
$this->data['User']['token_created_at'] = null;
if ($this->User->save($this->data) &&
$this->__sendPasswordChangedEmail($user['User']['id'])
) {
unset($_SESSION['token']);
$this->Session->setflash(
'Your password was changed successfully. Please login to continue.'
);
$this->redirect('/users/login');
}
}
}
}
You need to be sure that $_SESSION contains this index, so you should update it like this in order to be sure it exists:
By this:
if (!isset($_SESSION['token']) || $this->data['User']['reset_password_token'] != $_SESSION['token']) {
$this->Session->setflash(
'The password reset request has either expired or is invalid.'
);
$this->redirect('/users/login');
}
I am trying to use Facebook PHP sdk with cakephp 2.x for login purpose.
And it is working with debug mode 1 or 2 but it is not working with debug mode 0.
It seems session is not working properly in production.
I search about it on the web many times but not get the right solution for me.
I read these two threads in detail but did not cope with the problem.
https://github.com/facebook/php-graph-sdk/issues/473
How do I integrate Facebook SDK login with cakephp 2.x?
I use these two functions in AppController for login.
public function beforeFilter()
{
$this->disableCache();
$this->Facebook = new Facebook(array(
'app_id' => 'appId',
'app_secret' => 'appSecret',
'default_graph_version' => 'v2.7',
));
$this->Auth->allow(['.....']);
}
public function login()
{
if (!session_id()) {
session_start();
}
$this->loadModel("User");
$user_id = $this->Session->read('Auth.User.id');
$fb = $this->Facebook->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions
$callback_url = HTTP_ROOT . 'login';
$fb_login_url = $fb->getLoginUrl($callback_url, $permissions);
$this->set('fb_login_url', $fb_login_url);
if (!empty($user_id)) {
//redirect to profile page if already logged in
$this->redirect(... . );
}
//local login request
if ($this->request->is('post')) {
......
}
// when facebook login is used
elseif ($this->request->query('code')) {
try {
$accessToken = $fb->getAccessToken();
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
$this->Session->setFlash('Graph returned an error: ' . $e->getMessage(), 'error');
$this->redirect($this->referer());
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
$this->Session->setFlash('Facebook SDK returned an error: ' . $e->getMessage(), 'error');
$this->redirect($this->referer());
}
if (!isset($accessToken)) {
if ($fb->getError()) {
header('HTTP/1.0 401 Unauthorized');
$this->Session->setFlash("Error: " . $fb->getError() . "\n", 'error');
$this->Session->setFlash("Error Code: " . $fb->getErrorCode() . "\n", 'error');
$this->Session->setFlash("Error Reason: " . $fb->getErrorReason() . "\n", 'error');
$this->Session->setFlash("Error Description: " . $fb->getErrorDescription() . "\n", 'error');
$this->redirect($this->referer());
} else {
header('HTTP/1.0 400 Bad Request');
$this->Session->setFlash('Bad request', 'error');
$this->redirect($this->referer());
}
}
// Logged in
$oAuth2Client = $this->Facebook->getOAuth2Client();
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
$tokenMetadata->validateAppId('1200125790051089'); // Replace {app-id} with your app id
$tokenMetadata->validateExpiration();
if (!$accessToken->isLongLived()) {
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
$this->Session->setFlash('Error getting long-lived access token: ' . $helper->getMessage() . "</p>\n\n", 'error');
$this->redirect($this->referer());
}
}
$_SESSION['fb_access_token'] = (string) $accessToken;
$fb_access_token = (string) $accessToken;
if (isset($accessToken)) {
try {
// Returns a `Facebook\FacebookResponse` object
$response = $this->Facebook->get('/me?fields=id,first_name,last_name,email', $accessToken);
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
$this->Session->setFlash('Graph returned an error: ' . $e->getMessage(), 'error');
$this->redirect($this->referer());
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
$this->Session->setFlash('Facebook SDK returned an error: ' . $e->getMessage(), 'error');
$this->redirect($this->referer());
}
$fb_user = $response->getGraphUser();
// We will varify if a local user exists first
$local_user = $this->User->find('first', array(
'conditions' => array('facebook_id' => $fb_user['id']),
));
// If exists, we will log them in
if ($local_user) {
$this->Auth->login($local_user['User']);
} else {
// we will create new user with facebook_id and log them in
$data['User'] = array(.........);
// You should change this part to include data validation
$new_user = $this->User->save($data);
$this->Auth->login($new_user['User']);
}
// redirect to profile page here
}
}
}
I've had some issues with the SDK and CakePHP 2.x as well. I wrote a small handler that lets the SDK make use of CakeSession.
You can find it here:
https://github.com/WrDX/FacebookCakeSessionPersistentDataHandler
How to update user information stored in auth session? without logout and login again.
I think this function will do it.. but is it the best-practice?
function update($field, $value){
$this->Session->write($this->Auth->sessionKey . '.' . $field, $value);
}
Yes.
You could grab the current info array, modify it, and then call $this->Auth->login($newUserData);, but this will also renew the session (no user interaction needed, though). Note: Applies to CakePHP 2.0+ only.
I've completed update function to get an array of new values. with keys (field name):
public function update($fields, $values = null) {
if (empty(parent::$_user) && !CakeSession::check(parent::$sessionKey)) {
return false;
}
if (!empty(parent::$_user)) {
$user = parent::$_user;
} else {
$user = CakeSession::read(parent::$sessionKey);
}
if (is_array($fields)) {
if (is_array($values)) {
$data = array_combine($fields, $values);
} else {
$data = $fields;
}
} else {
$data = array($fields => $values);
}
foreach ($data as $field => $value) {
if (isset($user[$field])) {
$user[$field] = $value;
}
}
return $this->login($user);
}
(thanks to tigrang for login function)
I'm developing a REST api for a application, and everething went fine up until now...
I'm building a header with login data, GET and DELETE work fine but when I try to send a PUT or POST request I get 404...
When authorization is off (i.e., I do not check it in cake) everything works fine.
Here's the controller code:
class SitesController extends AppController {
var $uses = array("Site");
var $name = 'Sites';
var $scaffold;
var $components = array('RequestHandler','Security');
function beforeFilter() {
$this->Security->loginOptions = array(
'type'=>'basic'
);
$this->Security->loginUsers = array(
'lukasz'=>'blabla',
'test'=>'test'
);
$this->Security->requireLogin();
}
function index() {
$sites = $this->Site->find('all');
$this->set(compact('sites'));
}
function view($id) {
$site = $this->Site->findById($id);
$this->set(compact('site'));
}
function add() {
if($this->data != null) {
$this->Site->create();
if($this->Site->save($this->data)) {
$message = array('Deleted');
} else {
$message = $this->data;
}
$this->set(compact("message"));
}
}
function edit($id) {
$this->Site->id = $id;
if ($this->Site->save($this->data)) {
$message = array('Saved');
} else {
$message = array('Error');
}
$this->set(compact("message"));
}
function delete($id) {
if($this->Site->delete($id)) {
$message = array('Deleted');
} else {
$message = array('Error');
}
$this->set(compact("message"));
}
}
And here's how I send requests:
http://bin.cakephp.org/view/165115685
http://bin.cakephp.org/view/1477117088
I suspect you're running into the CSRF protection (form spoofing protection) the SecurityComponent applies to all POST and PUT requests. Try turning it off using the $validatePost option.
when uploading an image to the server using cakephp
$this->Model->Behaviors->attach('ImageUpload', Configure::read('photo.files'));
photo uploaded successfully, and the database fields also
but shows following error instead of returning to index page.
Notice (8): Undefined index: class [CORE\cake\libs\model\behaviors\upload.php, line 104]
Notice (8): Undefined index: class [CORE\cake\libs\model\behaviors\upload.php, line 107]
Warning (2): Cannot modify header information - headers already sent by (output started at E:\umoorthy_105act10\projects\dev1base\core\cake\basics.php:111) [CORE\cake\libs\controller\controller.php, line 614]
wat to do?
Cake has already wrote where to look for a problem
Configure::read('photo.files')
do following to check if everything is ok
pr(Configure::read('photo.files'))
public function uploadFilesIphone($folder, $formdata, $replace , $itemId = null) {
// setup dir names absolute and relative echo "<pre>"; print_r($formdata); exit;
$folder_url = WWW_ROOT.$folder;
$rel_url = $folder; //echo
// create the folder if it does not exist
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
// if itemId is set create an item folder
if($itemId) {
// set new absolute folder
$folder_url = WWW_ROOT.$folder.'/'.$itemId;
// set new relative folder
$rel_url = $folder.'/'.$itemId;
// create directory
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
}
// list of permitted file types, this is only images but documents can be added
$permitted = array('image/gif','image/jpeg','image/pjpeg','image/png','application/octet-stream');
// loop through and deal with the files;
$key = array();
$value = array();
foreach($formdata as $key => $value)
{
if($key == is_array($value))
{
$filename = str_replace(".", $replace , $value['name']);
}
// replace spaces with underscores
// assume filetype is false
$typeOK = false;
// check filetype is ok
foreach($permitted as $type)
{
if($key == is_array($value))
{
if($type == $value['type'])
{
$typeOK = true;
break;
}
}
}
// if file type ok upload the file
if($typeOK) {
// switch based on error code
if($key == is_array($value))
{
switch($value['error'])
{
case 0:
// check filename already exists
if(!file_exists($folder_url.'/'.$filename))
{
// create full filename
$full_url = $folder_url.'/'.$filename;
$url = $rel_url.'/'.$filename;
// upload the file
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
else
{
// create unique filename and upload file
// ini_set('date.timezone', 'Europe/London');
$now = date('Y-m-d-His');
$full_url = $folder_url.'/'.$now.$filename;
$url = $rel_url.'/'.$now.$filename;
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
// if upload was successful
if($success)
{
// save the url of the file
$result['urls'][] = $url;
}
else
{
$result['errors'][] = "Error uploaded $filename. Please try again.";
}
break;
case 3:
// an error occured
$result['errors'][] = "Error uploading $filename. Please try again.";
break;
default:
// an error occured
$result['errors'][] = "System error uploading $filename. Contact webmaster.";
break;
}
}
elseif($value['error'] == 4)
{
// no file was selected for upload
$result['nofiles'][] = "No file Selected";
}
else
{
// unacceptable file type
$result['errors'][] = "$filename cannot be uploaded. Acceptable file types: gif, jpg, png.";
}
}
}
return $result;
}