Hybrid Auth with Codeigniter - codeigniter

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 ..

Related

Laravel Socialite Google login only with one domain

I have a Google+ login on my app with Laravel Socialite. When the login is done I have a callback to connect the user (I create her in database if necessary).
But I want to restrain the connection to only the company (email like "example#company.com", so only the email with "company.com").
Can I do it with Laravel Socialite ? I can make the verification manually in my callback but if Socialite can do it, it's better.
Thank you
My callback :
public function handleProviderCallback($provider){
$user = Socialite::driver($provider)->user();
if ($user) {
$local_user = User::whereEmail($user->getEmail())->first();
// If we don't have a user create a new user
if (!$local_user) {
$fragment = explode(' ', $user->getName());
$local_user = User::create([
'first_name' => isset($fragment[0]) ? $fragment[0] : '',
'last_name' => isset($fragment[1]) ? $fragment[1] : '',
'email' => $user->getEmail(),
'last_seen' => Carbon::now(),
'password' => ''
]);
$local_user->roles()->attach(Role::whereName('User')->first());
}
auth()->login($local_user);
}
return redirect($this->redirectTo);
}
You have a step by step guide for domain restriction.
In controller you need to specifiy these actions:
public function handleProviderCallback()
{
try {
$user = Socialite::driver('google')->user();
} catch (\Exception $e) {
return redirect('/login');
}
// only allow people with #company.com to login
if(explode("#", $user->email)[1] !== 'company.com'){
return redirect()->to('/');
}
// check if they're an existing user
$existingUser = User::where('email', $user->email)->first();
if($existingUser){
// log them in
auth()->login($existingUser, true);
} else {
// create a new user
$newUser = new User;
$newUser->name = $user->name;
$newUser->email = $user->email;
$newUser->google_id = $user->id;
$newUser->avatar = $user->avatar;
$newUser->avatar_original = $user->avatar_original;
$newUser->save();
auth()->login($newUser, true);
}
return redirect()->to('/home');
}
No, you can’t do it in Socialite itself because Socialite is just a mechanism of retrieving tokens from OAuth-compliant servers.
If you only want to accept users with a particular email suffix, then that’s business logic so something you should handle in your callback:
public function handleProviderCallback()
{
$user = Socialite::driver('google')->user();
if (Str::endsWith($user->getEmail(), '#example.com')) {
// Look up user and authenticate them
}
abort(400, 'User does not belong to organization');
}

Unable to communicate with the PayPal error

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

Facebook login using artdarek/oauth-4 returns blank

I am attempting to setup facebook login using the artdarek/oauth-4 package. The redirect just returns a blank page with the following url:
https://www.facebook.com/dialog/oauth?type=web_server&client_id=1423706434575595&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2FcontractorSherpa%2Fpublic%2Ffacebook&response_type=code&scope=email+read_friendlists+user_online_presence
I am using Laravel 4.2.4
Route:
Route::get('/facebook', 'RegistrationController#loginWithFacebook');
RegistrationController:
Public function loginWithFacebook() {
$code = Input::get('code');
// get fb service
$fb = OAuth::consumer('Facebook');
//check for valid code
// if empty provide user data
if ( !empty($code)){
$token = $fb->requestAccessToken($code);
//send a request with it
$result = json_decode( $fb->request('/me'), true);
if (!empty($token)) {
try{
$user = Sentry::findUserByLogin($result['email']);
Sentry::login($user, false);
return Redirect::to('contractors/dashboard');
}
catch (Cartalyst\Sentry\Users\UsersNotFoundException $e)
{
$user = Sentry::register(array(
'activated' => 1,
'email' => $result['email'],
'password' => $result['password'],
'first_name' => $result['firstname'],
'last_name' => $result['lastname'],
));
$group = Sentry::findGroupByName($data['contractor']);
$user->addGroup($usergroup);
Sentry::login($user, false);
return Redirect::to('contractors/dashboard');
}
}
}
else {
//get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to((string)$url);
}
}
In my case, the $code is null, so it the else statement triggers.
I tried dd($url) and got this response:
object(OAuth\Common\Http\Uri\Uri)#368 (10) { ["scheme":"OAuth\Common\Http\Uri\Uri":private]=> string(5) "https" ["userInfo":"OAuth\Common\Http\Uri\Uri":private]=> string(0) "" ["rawUserInfo":"OAuth\Common\Http\Uri\Uri":private]=> string(0) "" ["host":"OAuth\Common\Http\Uri\Uri":private]=> string(16) "www.facebook.com" ["port":"OAuth\Common\Http\Uri\Uri":private]=> int(443) ["path":"OAuth\Common\Http\Uri\Uri":private]=> string(13) "/dialog/oauth" ["query":"OAuth\Common\Http\Uri\Uri":private]=> string(193) "type=web_server&client_id=1423706434575595&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2FcontractorSherpa%2Fpublic%2Ffacebook&response_type=code&scope=email+read_friendlists+user_online_presence" ["fragment":"OAuth\Common\Http\Uri\Uri":private]=> string(0) "" ["explicitPortSpecified":"OAuth\Common\Http\Uri\Uri":private]=> bool(false) ["explicitTrailingHostSlash":"OAuth\Common\Http\Uri\Uri":private]=> bool(false) }
Though I have added a few lines of code to account for Sentry auth, my code is nearly identical to the the example in the readme file of artdarek package.
How do I get the correct url?
The code above is correct, except that I needed to specifically define a a route in
$fb = OAuth::consumer('Facebook');
so that became
$fb = OAuth::consumer( 'Facebook', 'http://www.contractorsherpa.com/facebook/' );
The page you want to reference in that url is the page you are posting to in your route. Don't forget the trailing slash. the $code will be added after the slash, which then triggers the if statement:
if(!empty($code))

laravel auth and session not persisting

The laravel session and auth I use have some problem in server, but working really fine in localhost . I will show.
Route
Route::get('/signin', 'PageController#signin');
Route::get('/signup', 'PageController#signup');
Route::get('/terms', 'PageController#terms');
Route::resource('/', 'PageController');
Route::controller('user', 'UserController');
PageController
public function index() {
if (Auth::check()) {
return View::make('user.index');
} else {
return View::make('landing');
}
}
UserController
public function postLogin() {
$data = array();
$secured = ['user_email' => $_POST['email'], 'password' => $_POST['password']];
if (Auth::attempt($secured, isset($_POST['remember']))) {
if (Auth::user()->user_status == 1 ) {
return Redirect::to('/');
} else {
$data['success'] = false;
}
} else {
$data['success'] = false;
}
return $data;
}
Auth::check() fails in pagecontoller even after login succeds. But if I change the code to
UserController
public function postLogin() {
$data = array();
$secured = ['user_email' => $_POST['email'], 'password' => $_POST['password']];
if (Auth::attempt($secured, isset($_POST['remember']))) {
if (Auth::user()->user_status == 1 ) {
return Return View::make(user.index);
} else {
$data['success'] = false;
}
} else {
$data['success'] = false;
}
return $data;
}
I get the index page and if I click the link of the home I get the landing page not the index page.
I guess I clarify my problem, I have gone through may solution replied earlier in same manner question nothing working.
I don't think its the server problem because another laravel application is working fine in same server.
Please help.
Your query seems to be incomplete, from what i understand you are able to get the index page after passing the authentication check only once, and that is by using this method:
public function postLogin() {
$data = array();
$secured = ['user_email' => $_POST['email'], 'password' => $_POST['password']];
if (Auth::attempt($secured, isset($_POST['remember']))) {
if (Auth::user()->user_status == 1 ) {
return Return View::make(user.index);
}
else {
$data['success'] = false;
}
}
else {
$data['success'] = false;
}
return $data;
}
try using a different browser to make sure there is no cookie storage restrictions in the client side and check the app/config/session.php file and see if you have configured the HTTPS Only Cookies according to your needs.
and just on an additional note this line "return Return View::make(user.index);" looks vague.

HybridAuth keeps giving "User profile request failed. Most likely the user is not connected to the provider and he should to authenticate again."

I am trying to implement HybridAuth Login for facebook. but it keeps giving me the above error.I tried redirecting the user to the facebook login page again after this error occurs but this results in a loop.
Please help me.This is my code.
public function login($provider)
{
try
{
$this->load->model('home_model');
$this->load->library('HybridAuthLib');
if ($this->hybridauthlib->providerEnabled($provider))
{
$this->service = $this->hybridauthlib->authenticate($provider);
if ($this->service->isUserConnected())
{
$user_profile = $this->service->getUserProfile(); <-- error here
$access_credentials = $this->service->getAccessToken();
redirect("site.com/profile/".$user_profile->identifier,"refresh");
} else { // Cannot authenticate user
show_error('Cannot authenticate user');
}
}
}
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();
}
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($service))
{
$service->logout();
}
show_error($error);
/* redirect("www.facebook.com/dialog/oauth/?
client_id=[APP_ID]
&redirect_uri=site.com/hauth/login/Facebook
&state=1
&scope=publish_stream
","refresh");* <-- when try to use this. It generates a redirect loop from facebook to my site
}
}

Resources