Is there any library or tutorial on token authentication compatible for Laravel 5? I'm working on a client mobile application and as far as I know, login is usually made via token auth, but surprisingly there are absolutely no results on the subject. Thanks in advance
$fb = new Facebook\Facebook([
'app_id' => config('services.facebook.app_id'),
'app_secret' => config('services.facebook.app_secret'),
'default_graph_version' => config('services.facebook.api_version'),
]);
try {
$response = $fb->get('/me?fields=id,name,email,gender', $request->input('facebook_access_token'));
} catch (Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
//echo 'Graph returned an error: ' . $e->getMessage();
//exit;
return $this->setStatusCode(403)->respondWithError('Not Authorized!');
} catch (Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
//echo 'Facebook SDK returned an error: ' . $e->getMessage();
//exit;
return $this->setStatusCode(500)->respondWithError('Backend Error!');
}
$facebookUser = $response->getGraphUser();
Related
i m using Magento ver. 1.8.1.0
i got Unable to communicate with the PayPal gateway. error with paypal express checkout or paypal Payments Pro in both case.
i have already Enable SSL verification :- No
Can you explain me about this error.
Thanks
Paypal have recently rolled out some security updates on the sandbox (production will be updated in June) https://devblog.paypal.com/upcoming-security-changes-notice/
Most importantly, TLS 1.0 and 1.1 are no longer accepted by the sandbox, and the Magento Paypal module doesn't use 1.2 by default. We can expect an official patch to fix this shortly, but in the meantime you can work around it by overriding Mage/Paypal/Model/Api/Nvp.php (in your local codepool or with a rewrite) with the following call function:
public function call($methodName, array $request)
{
$request = $this->_addMethodToRequest($methodName, $request);
$eachCallRequest = $this->_prepareEachCallRequest($methodName);
if ($this->getUseCertAuthentication()) {
if ($key = array_search('SIGNATURE', $eachCallRequest)) {
unset($eachCallRequest[$key]);
}
}
$request = $this->_exportToRequest($eachCallRequest, $request);
$debugData = array('url' => $this->getApiEndpoint(), $methodName => $request);
try {
$http = new Varien_Http_Adapter_Curl();
$http->addOption(CURLOPT_SSLVERSION,6);//CURL_SSLVERSION_TLSv1_2
$config = array(
'timeout' => 60,
'verifypeer' => $this->_config->verifyPeer
);
if ($this->getUseProxy()) {
$config['proxy'] = $this->getProxyHost(). ':' . $this->getProxyPort();
}
if ($this->getUseCertAuthentication()) {
$config['ssl_cert'] = $this->getApiCertificate();
}
$http->setConfig($config);
$http->write(
Zend_Http_Client::POST,
$this->getApiEndpoint(),
'1.1',
$this->_headers,
$this->_buildQuery($request)
);
$response = $http->read();
} catch (Exception $e) {
$debugData['http_error'] = array('error' => $e->getMessage(), 'code' => $e->getCode());
$this->_debug($debugData);
throw $e;
}
$response = preg_split('/^\r?$/m', $response, 2);
$response = trim($response[1]);
$response = $this->_deformatNVP($response);
$debugData['response'] = $response;
$this->_debug($debugData);
$response = $this->_postProcessResponse($response);
// handle transport error
if ($http->getErrno()) {
Mage::logException(new Exception(
sprintf('PayPal NVP CURL connection error #%s: %s', $http->getErrno(), $http->getError())
));
$http->close();
Mage::throwException(Mage::helper('paypal')->__('Unable to communicate with the PayPal gateway.'));
}
// cUrl resource must be closed after checking it for errors
$http->close();
if (!$this->_validateResponse($methodName, $response)) {
Mage::logException(new Exception(
Mage::helper('paypal')->__("PayPal response hasn't required fields.")
));
Mage::throwException(Mage::helper('paypal')->__('There was an error processing your order. Please contact us or try again later.'));
}
$this->_callErrors = array();
if ($this->_isCallSuccessful($response)) {
if ($this->_rawResponseNeeded) {
$this->setRawSuccessResponseData($response);
}
return $response;
}
$this->_handleCallErrors($response);
return $response;
}
The important line is $http->addOption(CURLOPT_SSLVERSION,6);//CURL_SSLVERSION_TLSv1_2
I am creating an api using Laravel 4.1. I am having problem with authentication and custom errors. I want to check first if the user is authenticated and then show error message. For example localhost:8080/trips/1 is not a valid a resource; if I go to that url it giving me 404 not found error even though I am not authenticated. My point is to check the authentication first then the errors. I am using laravel http basic authentication. Here is my filter code:
Route::filter('api.auth', function()
{
if (!Request::getUser())
{
App::abort(401, 'A valid API key is required');
}
$user = User::where('api_key', '=', Request::getUser())->first();
if (!$user)
{
App::abort(401);
}
Auth::login($user);
});
Here is my custom errors:
App::error(function(Symfony\Component\HttpKernel\Exception\HttpException $e, $code)
{
$headers = $e->getHeaders();
switch ($code)
{
case 401:
$default_message = 'Invalid API key';
$headers['WWW-Authenticate'] = 'Basic realm="REST API"';
break;
case 403:
$default_message = 'Insufficient privileges to perform this action';
break;
case 404:
$default_message = 'The requested resource was not found';
break;
default:
$default_message = 'An error was encountered';
}
return Response::json(array(
'error' => $e->getMessage() ?: $default_message,
), $code, $headers);
});
Here is my routes:
Route::group(array('before' => 'api.auth'), function()
{
Route::resource('trips', 'TripController', array(
'except' => array('create', 'edit')
));
});
The error code is executing before the filters thats why I am getting 404 error instead of getting 401. Is there any way to execute filter first then the error ?
I got this issue too and the way I worked around it (though I was not a fan at all) was doing the following inside the group(s) that don't contain a route sending requests to a controller's index method:
Route::any('/', function(){});
Granted, this shouldn't be how it works, the filter should trigger no matter what.
I'm just currently trying to switch from CodeIgniter to Laravel.
I have implemented the hybridouth method successful, but it seems to be only working for that route it's specified on.
I've tried searching for tutorials and examples but even they only show the auth is working on 1 route.
How can I give some function along to every route to check if a user is logged in?
Group for which the auth is needed.
Route::group(array('before' => 'auth'), function()
{
// ALL ROUTES WITH AUTH NEEDED
});
This seems to call the normal auth and i'm using the hybridauth
Route::get('social/{action?}', array("as" => "hybridauth", function($action = "")
{
if ($action == "auth") {
try {
Hybrid_Endpoint::process();
}
catch (Exception $e) {
return Redirect::route('hybridauth');
}
return;
}
try {
$socialAuth = new Hybrid_Auth(app_path() . '/config/hybridauth.php');
$provider = $socialAuth->authenticate("facebook");
$userProfile = $provider->getUserProfile();
}
catch(Exception $e) {
return $e->getMessage();
}
echo "<pre>" . print_r( $userProfile, true ) . "</pre><br />";
}));
If you are going to run the request at every route, use a filter
App::before(function($request)
{
//check if user logged in here
});
or create filter and group your routes
Route::group(array('before' => 'auth'), function()
{
});
I am able to use the Event::Override function successfully with the 404 event but not the 500 event. I simply wish the event to redirect to the front page with a flash message, as I am able to do fine with 404 events.
Is there something else I need to do to get the 500 events also redirecting to my front page? see code below in routes.php file:
Event::listen('404', function() {
return Response::error('404');
});
Event::listen('500', function() {
return Response::error('500');
});
Event::override('404', function() {
Session::flash('error', '<strong>Error 404 - Not Found.</strong> The page you are looking for is either <u>invalid</u> or <u>may no longer exist</u>. You are now back at our home page.');
return Redirect::to_route('home');
});
Event::override('500', function() {
Session::flash('error', '<strong>Error 500 - Internal Server Error.</strong> Something went wrong on our servers, apologies for that. Please contact us if this persists.');
return Redirect::to_route('home');
});
any ideas?
I've been able to work around this by updating the 500 error file directly in the \application\views\error folder.
One of my mobile application need a error as json format. I got it's solution from laravel forum . For catching http error
App::error( function(Symfony\Component\HttpKernel\Exception\HttpException $exception) {
$code = $exception->getStatusCode();
// you can define custome message if you need
return Response::json( array(
'message' => $exception->getMessage() ,
'code' => $code ,
) , $code);
});
Catch unhandled like db error, ..
App::error(function(Exception $exception , $code )
{
return Response::json( array(
'message' => $exception->getMessage() ,
'code' => $code ,
), $code );
});
I downloaded the codeigniter extension of HybridAuth here:
https://github.com/andacata/HybridIgniter
I followed instructions on its use. When I try to login via any provider at: www.mydomainname.com/hauth/login/twitter it loads a page saying:
HybridAuth
Open Source Social Sign On PHP Library.
hybridauth.sourceforge.net/
It never works. I have valid API credentials for Twitter and Facebook but both load this page and nothing else happens. Any tips would be greatly appreciated.
UPDATE
My log says:
Hybrid_Provider_Adapter::login( facebook ), redirect the user to login_start URL. -- Array
(
[hauth_return_to] => http://www.sitename.com/hauth/login/facebook
[hauth_token] => 6vjglu8usmsjqsi74cku8o85j3
[hauth_time] => 1335997302
[login_start] => http://sitename.com/hauth/endpoint?hauth.start=facebook&hauth.time=1335997302
[login_done] => http://sitename.com/hauth/endpoint?hauth.done=facebook
)
INFO -- 127.0.0.1 -- 2012-05-03T00:21:42+02:00 -- Enter Hybrid_Auth::redirect( http://sitename.com/hauth/endpoint?hauth.start=facebook&hauth.time=1335997302, PHP )
UPDATE
Here is a link to the controller
https://github.com/andacata/HybridIgniter/blob/master/application/controllers/hauth.php
the above answer didn't help much to me but i figured out the problem.
Add index.php to base_url in config/hybridauthlib.php
'base_url' => '/index.php/hauth/endpoint',
here is my code which work 100% :
class Auth extends MX_Controller {
public function __construct()
{
parent::__construct();
$this->template->set_layout('login');
}
//social login
public function social($provider)
{
try{
$this->load->library('HybridAuthLib');
$this->load->model('auth_model');
$serviceEnabled = $this->hybridauthlib->serviceEnabled($provider);
if ($serviceEnabled)
{
$this->service = $this->hybridauthlib->authenticate($provider);
if ($this->service->isUserConnected())
{
$user_profile = $this->service->getUserProfile();
if($this->auth_model->count_user_by_uid($user_profile->identifier) === 0)
{
$this->session->set_flashdata('message','You Dont have account.. Create one.');
redirect('/users/register','refresh');
}
else
{
$dump_data = $this->auth_model->get_by(array('provider_uid'=>$user_profile->identifier));
$user = $this->ion_auth->user($dump_data->user_id)->row();
$session_data = array(
'identity' => $user->{$this->config->item('identity', 'ion_auth')},
'username' => $user->username,
'email' => $user->email,
'user_id' => $user->id, //everyone likes to overwrite id so we'll use user_id
'old_last_login' => $user->last_login
);
$this->ion_auth->update_last_login($user->id);
$this->ion_auth->clear_login_attempts($this->config->item('identity', 'ion_auth'));
$this->session->set_userdata($session_data);
if ($this->config->item('remember_users', 'ion_auth'))
{
$this->ion_auth->remember_user($user->id);
}
$this->ion_auth->trigger_events(array('post_login', 'post_login_successful'));
$this->ion_auth->set_message('login_successful');
redirect('/','refresh');
}
}
else // Cannot authenticate user
{
$this->session->set_flashdata('message','Cannot authenticate user');
redirect('/users/auth/login/','refresh');
}
}
else // This service is not enabled.
{
$this->session->set_flashdata('message','This providers is not enabled.');
redirect('/users/auth/login/','refresh');
}
}
catch(Exception $e)
{
$error = 'Unexpected error';
switch($e->getCode())
{
case 0 : $error = 'Unspecified error.'; break;
case 1 : $error = 'Hybriauth configuration error.'; break;
case 2 : $error = 'Provider not properly configured.'; break;
case 3 : $error = 'Unknown or disabled provider.'; break;
case 4 : $error = 'Missing provider application credentials.'; break;
case 5 : log_message('debug', 'controllers.HAuth.login: Authentification failed. The user has canceled the authentication or the provider refused the connection.');
//redirect();
if (isset($service))
{
$service->logout();
}
$error = 'User has cancelled the authentication or the provider refused the connection.';
break;
case 6 : $error = 'User profile request failed. Most likely the user is not connected to the provider and he should to authenticate again.';
break;
case 7 : $error = 'User not connected to the provider.';
break;
}
if (isset($this->service))
{
$this->service->logout();
}
log_message('error', 'controllers.HAuth.login: '.$error);
$this->session->set_flashdata('message', $error);
redirect('/users/auth/login/', 'refresh');
}
}
public function endpoint()
{
log_message('debug', 'controllers.HAuth.endpoint called.');
log_message('info', 'controllers.HAuth.endpoint: $_REQUEST: '.print_r($_REQUEST, TRUE));
if ($_SERVER['REQUEST_METHOD'] === 'GET')
{
log_message('debug', 'controllers.HAuth.endpoint: the request method is GET, copying REQUEST array into GET array.');
$_GET = $_REQUEST;
}
log_message('debug', 'controllers.HAuth.endpoint: loading the original HybridAuth endpoint script.');
require_once ADDONPATH.'/users/third_party/hybridauth/index.php'; //ADDONPATH is my modules path
}
}
i hope that you can find it useful.
am using the ion_auth for the main login system.
the auth_model is a small model which check if the user has enabled this provider with name or not, since i want the user to have the same data even if he use another social network to login with ..