Flashing appropriate 200 message upon logout, laravel - php

Using laravel 5.2, I'm hitting a logout listener at the time of logging out that logs the user out of their cognito instance.
This seems to be successful but I"m having a hard time getting a working message to flash on logout, specifically, I want the 200 message response from the auth call below
I have handled the JSON for errors at the endpoint call, but if the part of my try block is successful then I get a 200 response with message "User logged out successfully".
How should I properly flash the 200 message on the sign in screen/redirect after logging out?
try {
$authService = new AuthService();
$authLogout = $authService->logout($logoutToken);
}catch (\Exception $e) {
$response = json_decode($e->getResponse()->getBody()->getContents());
$message = $response->message;
return Redirect::back()->withErrors($message);
}

Add to a session
session(['key' => 'value']);
Retrieve from the session
$value = session('key');

if you use the rest api, you can wrtite this in your logout fonction
public function logout (Request $request)
{
$token = $request->user()->token();
$token->revoke();
$response = 'You have been succesfully logged out!';
return response(["message"=>$response], 200);
}

Related

Google Events API returning 401 error unauthorized_client

I have created an application in laravel to sync my users calendar in my database with incremental sync every thing working perfect when i am running it in my browser.
but its returning 401 unauthorized_client in my cron 100% same code implemented in both files.
$client = $this->getGoogleClient();
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}
$gCalService = new Google_Service_Calendar($client);
$optArr = array();
$calendarId = 'primary';
$pageToken = NULL;
$responceEvents = array();
$synced = $emailSync->getGoogleSynced();
if($synced != null)
$optArr['syncToken'] = $synced->sync_token;
do {
if ($pageToken) {
$optArr['pageToken'] = $pageToken;
}
try {
$results = $gCalService->events->listEvents($calendarId,$optArr);
}
catch (Google_Service_Exception $e) {
$msg = $e->getMessage();
return $msg;
}
if ($results->getItems()) {
$responceEvents = array_merge($responceEvents, $results->getItems());
$pageToken = $results->getNextPageToken();
}
} while ($pageToken);
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
returning below error
Array
(
[error] => unauthorized_client
[error_description] => Unauthorized
)
debugged code line by line $client->getRefreshToken() also contain value which i am passing here $client->setAccessToken($accessToken); exactly same code working fine in my browser file and not working in my cron.
401 unauthorized_client
Means that your code has not been authorized. If you want to access private user data you will need to be logged in. Your code needs an access token in order to access the Google api.
What you should be doing is authorizing your code once using Oauth2 in a browser save the refresh token someplace and have the cron job read the refresh token and request a new access token before it runs.
Assuming that you own the account you are trying to insert into you may also want to consider using a service account.
Refresh token
If you are storing the refresh token in the database you must assign it to your client first before running your code here i am doing that with a refresh token stored in a session variable.
$client->refreshToken($_SESSION['refresh_token']);

Socialite - after successful login unable to log into Laravel app

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

Laravel | LinkedIn Login - '401 Unauthorized'

I'm getting another error with my LinkedIn application to be able to login on my website, so I get redirected to the right url, I click on 'Authorize' once I'm on the LinkedIn login page, and I get redirected to a link like this:
http://localhost:8000/login/linkedin/callback?code=XXXXXXXXXXXXXXXXXXXXX...
With the following error:
Client error: POST https://www.linkedin.com/oauth/v2/accessToken resulted in a 401 Unauthorized response: {"error":"invalid_client","error_description":"Client authentication failed"}
I don't understand why because I did a Twitter application to login on my website that works with the same controller, and it's perfectly working.. Here is my SocialAuthController:
public function redirectToProvider($driver)
{
if( ! $this->isProviderAllowed($driver) ) {
return $this->sendFailedResponse("{$driver} is not currently supported");
}
try {
return Socialite::driver($driver)->redirect();
} catch (Exception $e) {
// You should show something simple fail message
return $this->sendFailedResponse($e->getMessage());
}
}
public function handleProviderCallback( $driver )
{
try {
$user = Socialite::driver($driver)->user();
} catch (Exception $e) {
return $this->sendFailedResponse($e->getMessage());
}
// check for email in returned user
return empty( $user->email )
? $this->sendFailedResponse("No email id returned from {$driver} provider.")
: $this->loginOrCreateAccount($user, $driver);
}
My routes:
Route::get('login/{driver}', 'Auth\SocialAuthController#redirectToProvider')->name('social.oauth');
Route::get('login/{driver}/callback', 'Auth\SocialAuthController#handleProviderCallback')->name('social.callback');
I checked multiple time that all the data between the services.php and the LinkedIn application matchs exactly.. I can't figure this out.
You need to add
'x-li-src' => 'msdk'
Into headers array in file vendor/laravel/socialite/src/Two/LinkedInProvider.php
Please check this link for more information Android LinkedIn SDK produces unusable access tokens

Facebook login in javascript with php confirmation

I was looking some questions very similar to mine, but still lost in space here. I got no problems with JS part. I do the login and got my token. Now I need to send http request to a php that will perform queries in the database. How can I trust in a client request? I think I must have a confirmation of the user in server-side. So I taken the php SDK:
EDIT: This is the updated code, it's now working. The $fbToken in obtained by JavaScript and passed to php by Ajax request. Not using FacebookSession yet, baby steps...
$Login = ($_SESSION["Login"])? $_SESSION["Login"] : (object)array("ativo"=>FALSE, "metodo"=>"", "id"=>-1, "nome"=>"", "tipo"=>"", "publico"=>"", "nLogin"=>0, "captcha"=>"") ;
//
$fbPhpUser = FALSE;
require $Amb->phpBib.'Facebook/autoload.php';
//use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
//FacebookSession::setDefaultApplication('{myAppCode}', '{myAppSecret}');
$fb = new Facebook\Facebook([
'app_id' => '{myAppCode}',
'app_secret' => '{myAppSecret}',
'default_graph_version' => 'v2.3',
]);
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=id,name', $fbToken);
$fpPhpUser = $response->getGraphUser();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
fim("fbGraph", 'Erro Facebook Graph: ' . $e->getMessage());
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
fim("fbSDK", 'Erro Facebook SDK: ' . $e->getMessage());
exit;
}
if($fpPhpUser){
$Login->ativo = true;
$Login->metodo = "fb";
$_SESSION["Login"] = $Login;
}
The idea is to get a confirmation that the user is logged and Facebook has authorized my app, so '{access-token}' will be sent by post http request from client browser altogether with the rest of data (e.g.: user register form to be modified on my website database). $Login->ativo==TRUE means I can safely perform database queries. (the user can also login by my own website login system, but I wish he do by Facebook for an integration)
Not sure if will work and a bit tired of to try… Is this the right approach?
You only need the Javascript SDK to accomplish this. Your authorization is obtained through the statusChangeCallback function:
if (response.status === 'connected') {
//Logged into FB and app...
} else if (response.status === 'not_authorized') {
//Have NEVER logged into the app before.... you will see permissions page...
} else {
//NOT logged into FB... so not sure if logged into app...
}
Once you are connected, pass the access token via AJAX to your server and do whatever you want with it.
https://developers.facebook.com/docs/facebook-login/web#checklogin

Check if already logged to facebook with PHP SDK 4.0

I want to check if already logged in to facebook when navigating to index.php so I would automatically redirect to homepage.
However, my code will only check after clicking on the loggin link.
Facebook\FacebookSession::setDefaultApplication(Globals::FB_APP_ID, Globals::FB_APP_SECRET);
$helper = new Facebook\FacebookRedirectLoginHelper("myurl");
try {
$session = $helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
} catch (Exception $ex) {
// When validation fails or other local issues
}
// see if we have a session
if (isset($session)) {
// graph api request for user data
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
header("location:home.php");
} else {
// show login url
echo 'Login';
}
I checked some other thread about Facebook PHP SDK but there is not much about sdk 4.0. And nothing that worked for me..
I tought I could add a token in the session, however it wouldn't work if I would already be logged in to facebook before my first visit... It would also cause problem if I would logout from facebook without logout from my website.
Since I found this question to be frequently asked without answer, I decided to share what I did with the community.
The $session variable in my code contains an access token which can be used for re-instanciating the session anywhere else simply doing a new FacebookSession('token').
Considering that, when logging in for the first time, I retrieve the token from the $sessionand store it in $_SESSION. Then, I created a simple util function which first check if the $_SESSIONvariable is set, then try to instanciate a new FacebookSession using the stored token. If the stoken is invalid, the session won't instanciate then I can detect it in my util function and return wether the user is actually logged in or not.
Note that an access token is invalidated when facebook user logout.
Login url + token storage :
FacebookSession::setDefaultApplication(Globals::FB_APP_ID, Globals::FB_APP_SECRET);
$helper = new Facebook\FacebookRedirectLoginHelper("http://localhost/PoubellesDeMerde/PoubellesDeMerde/index.php");
try {
$session = $helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
} catch (Exception $ex) {
// When validation fails or other local issues
}
// see if we have a session
if (isset($session)) {
// graph api request for user data
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$_SESSION['token'] = $session->getToken();
} else {
// show login url
echo 'Login';
}
Util function :
public static function isLoggedIn()
{
$id=0;
if(isset($_SESSION['token']))
{
$session = new FacebookSession($_SESSION['token']);
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graphObject = $response->getGraphObject();
$id = $graphObject->getProperty("id");
}
return $id!=0;
}

Categories