I am new to laravel framework any help would appreciate
When i try to execute the below code i get this error
FatalErrorException in SocialController.php line 27: Class 'App\Http\Controllers\Hybrid_Auth' not found in SocialController.php line 27
when i remove the namespace from SocialController.php i get this error saying BaseController not found.
onclick this button
<i class="fa fa-facebook"></i> Facebook
SocialController.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class SocialController extends BaseController
{
//this is the code for facebook Login
public function getFacebookLogin($auth=NULL)
{
if ($auth == 'auth')
{
try
{
Hybrid_Endpoint::process();
}
catch (Exception $e)
{
return Redirect::to('fbauth');
}
return;
}
$oauth = new Hybrid_Auth(app_path(). '/config/fb_auth.php');
$provider = $oauth->authenticate('Facebook');
$profile = $provider->getUserProfile();
return var_dump($profile).'Log Out';
}
public function getLoggedOut()
{
$fauth = new Hybrid_auth(app_path().'/config/fb_auth.php');
$fauth->logoutAllProviders();
return view::make('/');
}
}
fb_auth.php
<?php
return array(
"base_url" => "http://urmk.com/fbauth/auth",
"providers" => array (
"Facebook" => array (
"enabled" => true,
"keys" => array ( "id" => "APP_ID", "secret" => "APP_SECRET" ),
"scope" => "email"
)
)
);
Routes.php
Route::get('fbauth/{auth?}' ,array('as'=>'facebook', 'uses'=>'SocialController#getFacebookLogin'));
Route::get('logout',array('as'=>'logout','uses'=>'SocialController#getLoggedOut'));
You will need to add the namespace to your Hybrid Auth class. At the moment, when you are trying to instantiate the Hybrid_Auth object, it's not finding the class definition.
Here is my setup for Laravel:
app/Providers/AppServiceProvider.php
public function register()
{
$this->app->bind('Hybrid_Auth', function($app) {
return new \Hybrid_Auth(config_path('hybridauth.php'));
});
}
config/hybridauth.php
<?php
return [
'base_url' => env('APP_URL').'/auth/endpoint',
'providers' => [
'Facebook' => [
'enabled' => true,
'display' => 'popup',
'keys' => [
'id' => 'xxxx',
'secret' => 'xxx'
],
'scope' => 'email'
],
]
];
app/Http/routes.php
Route::group(['prefix' => 'auth'], function()
{
Route::get('login', 'AuthenticateController#login');
Route::get('endpoint', 'AuthenticateController#endpoint');
Route::get('logout', 'AuthenticateController#logout');
});
app/Http/Controllers/AuthenticateController.php
public function login(\Hybrid_Auth $auth)
{
$provider = $auth->authenticate('facebook');
$profile = $provider->getUserProfile();
$user = User::where('facebook', '=', $profile->identifier);
if($user->first()) {
return response()->json(['token' => $this->signin($user->first())]);
} else {
$user = new User;
$user->facebook = $profile->identifier;
$user->save();
return response()->json(['token' => $this->signin($user)]);
}
}
public function endpoint() {
\Hybrid_Endpoint::process();
}
public function logout(\Hybrid_Auth $auth) {
$auth->logoutAllProviders();
}
Related
'facebook' => [
'client_id' => 'id',
'client_secret' =>
'fgdfgsdfgrtt45453',
'redirect' => 'http://example.com/callback',
],
In route.php
Route::get('/redirect', 'SocialAuthFacebookController#redirect');
Route::get('/callback', 'SocialAuthFacebookController#callback');
And I have add Services/SocialFacebookAccountService.php directory in App.
SocialFacebookAccountService.php
<?php
namespace App\Services;
use App\SocialFacebookAccount;
use App\User;
use Laravel\Socialite\Contracts\User as ProviderUser;
class SocialFacebookAccountService {
public function createOrGetUser(ProviderUser $providerUser) {
$account = SocialFacebookAccount::whereProvider('facebook')
->whereProviderUserId($providerUser->getId())
->first();
echo 'Account info : ';
if ($account) {
return $account->user;
} else {
$account = new SocialFacebookAccount([
'provider_user_id' => $providerUser->getId(),
'provider' => 'facebook'
]);
$user = User::whereEmail($providerUser->getEmail())->first();
if (!$user) {
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
'password' => md5(rand(1, 10000)),
]);
}
$account->user()->associate($user);
$account->save();
return $user;
}
}
}
Please help, How to get user info in callback.
In your callback method:
public function callback($provider=facebook)
{
if($user = $this->socialite->with($provider)->user()){
dd($user); //user details
}else{
return 'something went wrong';
}
}
I create my own ServiceProvider to send param form ENV when initiation class:
class InstagramServiceProvider extends ServiceProvider
{
protected $defer = true;
public function boot()
{
$this->publishes([
__DIR__.'/../config/config.php' => config_path('instagram.php'),
]);
}
public function register()
{
$this->app->bind('instagram.client', function ($app) {
return new InstagramClient([
'apiKey' => $app['config']->get('instagram.clientId'),
'apiSecret' => $app['config']->get('instagram.clientSecret'),
'apiCallback' => $app['config']->get('instagram.redirectUri'),
'scope' => $app['config']->get('instagram.scope'),
]);
});
}
public function provides()
{
return array('instagram.client');
}
}
And I can't get data from config? What I do wrong?
Laravel has a function built specifically for this job called config(). You can use it as follows:
public function register()
{
$this->app->bind('instagram.client', function ($app) {
return new InstagramClient([
'apiKey' => config('instagram.clientId'),
'apiSecret' => config('instagram.clientSecret'),
'apiCallback' => config('instagram.redirectUri'),
'scope' => config('instagram.scope'),
]);
});
}
Alternatively you could use a bracket notation like so:
$app['config']['instagram']['clientId']
For more information see documentation: https://laravel.com/docs/5.4/configuration#accessing-configuration-values
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Socialite;
use App\User;
use Auth;
class SocialLoginController extends Controller
{
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
public function handleProviderCallback($provider)
{
try{
$user = Socialite::driver($provider)->user();
}catch(Exception $e){
return redirect('auth/{$provider}');
}
// dd($user);
$authUser = $this->findOrCreateUser($user);
Auth::login($authUser, true);
if($authUser->$provider === 'twitter') {
return redirect()->intended('https://twitter.com/');
}
return redirect()->intended('https://www.facebook.com/');
}
Private function findOrCreateUser($providerUser)
{
$authUser = User::where('provider_id', $providerUser->id)->first();
if ($authUser){
return $authUser;
}
return User::create([
'name' => $providerUser->name,
'email' => $providerUser->email,
'provider_id' => $providerUser->id,
'avatar' => $providerUser->avatar,
'avatar_original' => $providerUser->avatar_original,
// 'profileUrl' => $twitterUser->profileUrl
]);
}
}
how do i return user to respective provider?
Here are my routes
Route::get('auth/{provider}', ['as' => 'auth/{provider}', 'uses' => 'SocialLoginController#redirectToProvider']);
Route::get('auth/{provider}/callback',['as' => 'auth/{provider}/callback', 'uses' => 'SocialLoginController#handleProviderCallback']);
Change $authUser->$provider === 'twitter' to the correct test you actually need, I guess it should be $provider === 'twitter'
i try to build a custom POST route for ReST API in cakephp 3, but when i want to connect to the url i got result:
The view for CalculatedpricesController::getCosts() was not found.
My url to connect to ReST like this :
http://localhost/test/api/calculatedprices/getCosts
here's the route code:
Router::scope('/', function (RouteBuilder $routes) {
Router::prefix('api', function ($routes) {
$routes->extensions(['json', 'xml']);
$routes->resources('Calculatedprices', [
'map' => [
'getCosts' => [
'action' => 'getCosts',
'method' => 'POST'
]
]
]);
});
$routes->fallbacks(DashedRoute::class);
});
here's the controller code:
namespace App\Controller\Api;
use App\Controller\Api\AppController;
/**
* Calculatedprices Controller
*
* #property \App\Model\Table\CalculatedpricesTable $Calculatedprices
*/
class CalculatedpricesController extends AppController
{
public function getCosts(){
$originIdCity = $this->request->query('originCity');
$originIdSub = $this->request->query('originSub');
$courierId = $this->request->query('courierId');
$serviceId = $this->request->query('serviceId');
$conditions = array('origin_city_id' => $originIdCity,
'courier_id' => $courierId,
'service_id' => $serviceId
);
if($originIdSub == ''){
$condition = 'origin_subdistrict_id IS NULL';
array_push($conditions,$condition);
} else{
$conditions['origin_subdistrict_id'] = $originIdSub;
}
$calculatedprices = $this->Calculatedprices->find('all', array(
'conditions' => $conditions
));
$this->set([
'calculatedprices' => $calculatedprices,
'_serialize' => ['calculatedprices']
]);
}
}
I'm implementing rbac using yii2. But when i try to get the roles that i previously created i get an empty variable : $authorRole = $auth->getRole('admin');
The rule class, where i put the actual rule logic.
yii/console/controller/UserGroupRule.php
namespace app\rbac;
use Yii;
use yii\rbac\Rule;
/**
* Checks if user group matches
*/
class UserGroupRule extends Rule
{
public $name = 'userGroup';
public function execute($user, $item, $params)
{
if (!Yii::$app->user->isGuest) {
$group = Yii::$app->user->identity->group;
if ($item->name === 'admin') {
return $group == 1;
} elseif ($item->name === 'author') {
return $group == 1 || $group == 2;
}
}
return false;
}
}
Now defining the roles..
yii/console/controller/RbacController.php
namespace console\controllers;
use Yii;
use yii\console\Controller;
class RbacController extends Controller
{
public function actionInit()
{
$auth = Yii::$app->authManager;
$rule = new \app\rbac\UserGroupRule;
$auth->add($rule);
$admin = $auth->createRole('admin');
$admin->ruleName = $rule->name;
$auth->add($admin);
}
}
After this i was able to run ./yii rbac/init to generate the rule files:
console/rbac/items.php
console/rbac/rules.php
This is mostly identical to the documentation
yii/commom/config/main.php
'authManager' => [
'class' => 'yii\rbac\PhpManager',
'defaultRoles' => ['admin', 'author'], // your define roles
],
But in
frontend\models\SignupForm::signup()
I get an empty result when i try to get the admin role :
public function signup()
{
if ($this->validate()) {
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->save(false);
$auth = Yii::$app->authManager;
$authorRole = $auth->getRole('admin');
$auth->assign($authorRole, $user->getId());
return $user;
}
return null;
}
here is the value of $auth :
yii\rbac\PhpManager#1
(
[itemFile] => '/advanced/frontend/rbac/items.php'
[assignmentFile] => '/advanced/frontend/rbac/assignments.php'
[ruleFile] => '/advanced/frontend/rbac/rules.php'
[*:items] => []
[*:children] => []
[*:assignments] => []
[*:rules] => []
[defaultRoles] => [
0 => 'admin'
1 => 'author'
2 => 'admin'
3 => 'author'
]
[yii\base\Component:_events] => []
[yii\base\Component:_behaviors] => null
)
It's probably because you generate the rbac in "console/rbac/items.php and
console/rbac/rules.php" but your rbac PhpManager is looking this files in advanced/frontend
You could move this files or set the correct paths
'authManager' => [
'class' => 'yii\rbac\PhpManager',
'itemFile' => '#common/rbac/items.php',
'assignmentFile' => '#common/rbac/assignments.php',
'ruleFile' => '#common/rbac/rules.php',
'defaultRoles' => ['admin', 'author'], // your define roles
],
The "#common" is yii2 alias all available aliases listed here: http://www.yiiframework.com/wiki/667/yii-2-list-of-path-aliases-available-with-default-basic-and-advanced-app/
This should help, let me know if there will be still an issue