I have a project it's Backend is built in Laravel 5.2 and Frontend is built in PHP. Please check the folder structure below it's in localhost.
Backend : http://crm.test.dev This is the root folder, laravel5.2 -> public ->index.php
Frontend: http://test.dev This url is point to laravel5.2 -> public -> frontend -> index.php
My purpose is, If a user(admin) is logged in Backend(http://crm.test.dev) and not signed out. The same user is accessing Frontend(http://test.dev") at that time I need to show an alert you are logged in Backend(http://crm.test.dev).
frontend->index.php
require __DIR__.'/../../bootstrap/autoload.php';
$app = require_once __DIR__.'/../../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$isAuthorized = Auth::check();
$user = Auth::user();
echo $user;
Actually issue is from config -> session.php {'domain' => null,}. I updated this line to { 'domain' => '.test.dev', } . Now a user is logged in backend and accessing frontend (subdomain: http://test.dev) "Your are logged in" message shows.
require __DIR__.'/../../bootstrap/autoload.php';
$app = require_once __DIR__.'/../../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$isAuthorized = Auth::check();
$user = Auth::user();
if(Auth::check()) {
echo "Your are logged in";
}
else {
echo "Sorry";
}
I don't have access to the sites you've posted. But you can check if the users logged in with Auth::check() as you already do. Then you can do it e.g. like this:
if(Auth::check()) {
echo "You're locked in";
//do some action
else {
//do normal action
}
Related
I am trying to set up login with Google using Laravel and socialite. I've set everything up to go to the Google login page and redirect me back to the application. However, when I'm redirected I always end up on the "login" page and not the "home" page. After successfully logging in with Google I'm not logged into my Laravel app. What is wrong?
/**
* Obtain the user information from Google.
*
* #return \Illuminate\Http\Response
*/
public function handleProviderCallback()
{
try {
$user = Socialite::driver('google')->user();
} catch (\Exception $e) {
return redirect('/login');
}
// 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');
}
Despite the calls to login a user I am not logged in when redirected back to the app. How can I make sure that after logging in with Google I'm logged in to the Laravel app?
Update
It turns out when the $user variable comes back from Google I am getting a InvalidStateException
The try catch block actually throws an exception. If I dd the exception it looks like:
It turns out what was breaking it for me was in my .env file I had:
SESSION_DOMAIN=http://localhost:8000
Removing this line fixed the issue!
Remove SESSION_DOMAIN from your .env file
I am working on a laravel App. a part of that is written pure php that is a html form and form submission script that stores data to Database.
Suppose form.php page is like :
<?php
require('config.php');
?>
<form action="process.php" method="post">
<input type="text" name="username">
<input type="submit" value="Send">
</form>
And process.php page is :
<?php
require ('config.php');
?>
if (isset($_POST['submit_edu'])) {
$username = trim($_POST['username']);
// other codes to store data to DB
}
Now I want just Authenticated Users in main laravel app can access to those pages and send their info.
To access Auth laravel Object, I added below codes to beginning of config.php file that holds connection settings and required by those two page:
require __DIR__ . '/../../bootstrap/autoload.php';
$app = require_once __DIR__ . '/../../bootstrap/app.php';
$app->make('Illuminate\Contracts\Http\Kernel')->handle(Illuminate\Http\Request::capture());
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
if (!Auth::check()) {
exit('Only authorized Users can access to this page');
}
As you can see if an unAuthorized user want to pages Encounters an error.
Now when an Authenticated user want to open form.php page (in face via GET method) Auth::check() works correctly but when clicks on submit form button and data sent to process.php (via POST method) , it always returns false.
While if I open same process.php via GET method Auth::check() works correctly again.
Means in this case Auth::check() can not work properly.
What is problem in your idea. can anyone help me to solve this problem?
Update :
Even I used EventServiceProvider and authentication events to create a session. first I added this to provider :
'Illuminate\Auth\Events\Login' => [
'App\Listeners\SessionLoginEnable',
],
And in SessionLoginEnable:
public function handle (Login $event)
{
session(['user_is_logged_in' => true]);
}
then I added:
'Illuminate\Auth\Events\Logout' => [
'App\Listeners\SessionLoginDisable',
],
And in that :
public function handle (Logout $event)
{
session(['user_is_logged_in' => false]);
}
And in the other hand to check and user created session first I tried in config.php :
require __DIR__ . '/../../bootstrap/autoload.php';
$app = require_once __DIR__ . '/../../bootstrap/app.php';
$app->make('Illuminate\Contracts\Http\Kernel')->handle(Illuminate\Http\Request::capture());
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$is_logged = session('user_is_logged_in');*
if ( !is_logged ) {
exit('Only authorized Users can access to this page');
}
This solution did not work.
Then I tried this :
session_start();
if ( !isset($_SESSION['user_is_logged_in']) or $_SESSION['user_is_logged_in'] != true) {
exit('Only authorized Users can access to this page');
}
But in this case again, the answer not receive and It seems $_SESSION['user_is_logged_in'] could not be recognized.
Another solution remains?
Could you please help me,
My code is not saving SESSION between requests.
when i Login, it always returns null in session.
Thank you in advance.
$app->get('/session', function($request, $response, $args) {
$session = new \SlimSession\Helper;
$reponse["uid"] = $session->uid;
$reponse["email"] = $session->email;
$reponse["name"] = $session->name;
echo json_encode($reponse);
});
$app->post('/connexion', function ($request, $response, $args) {
$reponse['status'] = "success";
$reponse['message'] = 'Vous ĂȘtes connectĂ©.';
$reponse['name'] = "wassim boukadida";
$reponse['uid'] = "123456";
$reponse['email'] = "test#test.com";
$reponse['createdAt'] = "date_exmple";
//session saving
$session = new \SlimSession\Helper;
$session->uid = "123456";
$session->email = "test#test.com";
$session->name = "wassim boukadida";
echo json_encode($reponse);
});
You need to start the session, bryanjhv/slim-session has already middleware for that, which you just need to add:
$app = new \Slim\App;
// add the middleware
$app->add(new \Slim\Middleware\Session());
// add routes
$app->run();
For settings look at the readme file of bryanjhv/slim-session as this helper is currently in development
I want to check that a user has authorized the following permissions; 'manage_pages', 'publish_pages', 'read_insights', for my app. In short, if they decline one or more permissions, I need to know, as all are required.
Here's my callback method once I get the user's access token. How do I verify they approved all permission requests?
Note: I'm using the SammyK Laravel Facebook SDK package.
public function handleFacebookCallback()
{
try {
$token = Facebook::getAccessTokenFromRedirect();
$user = Facebook::get('/me?fields=permissions', $token)->getGraphUser();
$permissions = $user['permissions']->asArray();
// permissions: 'manage_pages', 'publish_pages', 'read_insights'
if (array_key_exists('publish_pages', $permissions['data'][0]))
{
// permissions exist, proceed
}
else
{
// user denied permission(s), redirect
}
}
....
According to Facebook Graph API you can call user/permissions to get all the permissions that user has granted to application.
$request = new FacebookRequest(
$session,
'GET',
'/me/permissions'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */
foreach($graphObject as $permission) {
if($permission->permission == 'publish_pages' AND $permission->status == 'granted') {
// User has granted publish_pages permission
}
}
You can debug this call here, I've not tested it but it should work.
Not sure if this is the slickest answer or how others would approach this, but here's what I came up with...
try {
$token = Facebook::getAccessTokenFromRedirect();
$request = Facebook::get('/me?fields=permissions', $token);
$user = $request->getGraphUser();
$permissions = $user['permissions'];
// if user denied ANY of the required permissions
foreach ($permissions as $p => $permission)
{
if ($permission['status'] !== 'granted')
{
return redirect()->route('connect.index')->withErrors('Error: We require all permissions in order to connect your Facebook page.');
}
}
}
All I'm trying to do is have the user connect with facebook, grab his information (email, name, profile_pic) and register him automatically on my site.
the problem is when I visit /user/login/fb/ I get redirected to the fb application to grant permission and then it redirects me to
http://local.serv/user/login/fb/callback?code=AQB7Uf7pcZSY89WYUKofY8bOgBY1qCcWA5p6_G-9MVdczN60C0TNOgFIi9LBRwquagZ6VbC6_kjD9-D0ZevKHyNGw88LuRJcuqdq2RbwCKNlC02_4eMtiNAWxX76XHm1CzU0F7nSVQ4KxENoDPFpKIs1oV-wQTkO7YuuGznL9UuzfK-hqTtZAIRBvQ_N_yh03LsdgaZ9-f6z5yc5FGnJ3sJyrC-3DGrjkSzhPpJHHk5tr7LorzqW9TNcaFpB9eE51wdsEHOa5oNEWycwzXjY-7Me1Uod3KVBGpb8tzeYVHArphMc2n45IF1pfAWMZZZ51Dw&state=f25e8641df013970542b7463b8899ccf#=
and give me this error
Facebook \ FacebookSDKException (700)
You must provide or set a default application id.
Here are my routes
Route::get('user/login/fb', function() {
FacebookSession::setDefaultApplication('', '');
$helper = new FacebookRedirectLoginHelper('user/login/fb/callback');
$loginUrl = $helper->getLoginUrl();
return "<a href='$loginUrl'>facebook</a>";
});
Route::get('user/login/fb/callback', function() {
// A FacebookResponse is returned from an executed FacebookRequest
$helper = new FacebookRedirectLoginHelper('user/login/fb/callback');
$session = $helper->getSessionFromRedirect();
$request = new FacebookRequest($session, 'GET', '/me');
try {
$response = $request->execute();
$me = $response->getGraphObject();
} catch (FacebookRequestException $ex) {
echo $ex->getMessage();
} catch (\Exception $ex) {
echo $ex->getMessage();
}
print_r($me);//->getProperty("id"));
$user = new Giftee;
$user->name = $me->getProperty('first_name') . ' ' . $me->getProperty('last_name');
$user->email = $me->getProperty('email');
$user->photo = 'http://graph.facebook.com' . $me->getProperty('id') . '/picture?type=large';
$user->save();
});
PS: if you have a clear tutorial with views and everything on how to integrate fb login with laravel please do share, I've been looking for days, the material is so limited.
Your Facebook API credentials aren't set when you request the user/login/fb/callback, either add the FacebookSession::setDefaultApplication(...) at the beginning of that route as well or use another library that allows you to set these in a global configuration file.
Your route should look like this :
Route::get('user/login/fb/callback', function() {
FacebookSession::setDefaultApplication(); // your API credentials
// here goes the rest of your code
};