Page tab app, redirecting user back to restricted page on authentication - authentication

I can use the following code to redirect a user back to the page my app is installed on using the following code:
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$signed_request = $facebook->getSignedRequest();
$page = $signed_request['page'];
$page_id = $page['id'];
$page_array = $facebook->api("/$page_id");
$page_link = $page_array['page_link'];
$redirect_uri = $page_link . '?sk=app_' . $app_id
$user = $facebook->getUser();
if(!$user) {
$url = $facebook->getLoginUrl(array('redirect_uri' => $redirect_uri));
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
}
This works fine for most pages but if a page has age restrictions (and I cant guarantee all the pages using my app won't) the $facebook->api("/$page_id"); returns false because from what I can gather, I need the users access token in order to get this information which I can't get unless I authenticate them! Is there any way around this paradox or am I going to have to instruct my users not to age restrict their pages?
UPDATE
I realise I can simply redirect to facebook.com/$page_id which will take the user back to the page after authentication and would save me having to make the api request for $page_link but ideally I would like them to be redirected to my apps page tab on that page no matter what the specified default landing tab is.

Related

Login a user to wordpress from external application

Hi I am building a React native app based on my wordpress website so I need to make a registration and login logic to get the user id and user data, thankfully I made the registration logic by creating new user using the rest api, but I need help in making the login thing since I find nothing helpful while searching Google.
I want to post the username or email and the password to authenticate that the user do exist in my site
register_rest_route(
'custom-plugin', '/login/',
array(
'methods' => 'POST',
'callback' => 'login',
)
);
}
function login($request){
$creds = array();
$creds['user_login'] = $request["username"];
$creds['user_password'] = $request["password"];
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) )
echo $user->get_error_message();
return $user;
}
add_action( 'after_setup_theme', 'custom_login' );
Then your API will be created as
http://www.url.com/wp-json/custom-plugin/login
Try it with Postman You will get 200 as a response and user info
body:
{
"username": ""fakmamail#gmail.com",//or the username
"password": "t433434533"
}

Google + sign in with laravel

I have been struggling a lot for G+ sign-in with laravel, I have downloaded the php-sdk using composer. I am also using JavaScript to sign-in, once the once the user signs in I redirect him to a route from JavaScript to /gLogin?email=abc#gmail.com&name=John Doe where I have following code.
$user_profile['email']=Input::get('email');
$user_profile['name']=Input::get('name');
$user_id=DB::table('users') -> where('dyp_user_email', $user_profile['email'])-> pluck('dyp_user_id');
if($user_id)
{
$user_to_be_logged_in=new user();
$user_to_be_logged_in = User::find($user_id);
}
else
{
$password=$token = str_random(16);
$hash=Hash::make($password);
$user_to_be_logged_in = user::create(array('dyp_user_type' => 'IN', 'dyp_name' => $user_profile['name'], 'dyp_user_email' => $user_profile['email'], 'dyp_mobile_number' => '','dyp_password'=> $hash,'dyp_user_status' => 'VF'));
$data = array('name' => $user_to_be_logged_in -> dyp_name, 'password' => $password);
Mail::send('emails.fbUserRegistration', $data, function($message) use ($user_to_be_logged_in) {
$message -> to($user_to_be_logged_in->dyp_user_email, $user_to_be_logged_in->dyp_name) -> subject('Thanks for registering with dreamyourproperty.com');
});
}
Auth::login($user_to_be_logged_in);
There is a serious security problem here, that I am not able to validate the user's session.
I someone manually hits the url /gLoin?email=abc#gmail.com&name=xyz then also my code will authenticate him.
In comparison to G+ signin FB login was pretty simple.Can someone provide me guidance, I am seriously stuck with this part.
They way you want to handle this is /gLogin?access_token=xyz where xyz is the users Google+ access_token. Make a request to people.get authenticated with that access token. That way you have server side validation the current user is validated for the specific Google+ profile.

How to functional test secured pages in Symfony2?

Setup and information to reproduce the problem
Symfony2.2 application
LiipFunctionalTestBundle
DoctrineFixturesBundle
FOSUserBundle
For testing enviroment I use LiipFunctionalTestBundle and generate (from DoctrineFixtures) a fake SQLite database. It's configured correctly - I've been able to succesfully test my non-secured pages.
I've created a simple secured page under /secured/test with this view:
<h2 class="username">{{ app.user.username }}</h2>
I've tried with
http://symfony.com/doc/master/cookbook/testing/http_authentication.html
And I wanted to test this action with this assertion:
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'myUserName'
'PHP_AUTH_PW' => 'password',
));
$crawler = $client->request('GET', '/secured/test');
$count = $crawler
->filter('h2.username:contains("myUserName")')
->count();
$this->assertTrue($count > 0);
The result was Failed asserting that false is true.
I've tried with
http://symfony.com/doc/master/cookbook/testing/simulating_authentication.html
And I wanted to test this action with this assertion:
$this->logIn();
$crawler = $this->client->request('GET', '/secured/test');
$count = $crawler
->filter('h2.username:contains("myUserName")')
->count();
$this->assertTrue($count > 0);
Ofcourse I changed the logIn function to diffrent username.
The result was Failed asserting that false is true.
None of these works. Whats wrong?
I've tried many other methods, but
The solution to the problem was very simple:
In my DoctrineFixtures I've created new users.. but their accounts were not enabled.
Adding this code to fixture solved the problem:
$user->setEnabled(true);
$user->setExpired(false);
$user->setLocked(false);
(becouse my test was trying to log on not enabled account, the response to "submit login form" was redirect to login page)

How do correctly authorise a Facebook App

I am creating a basic Facebook app, and when a user without permission visits the app, they are redirected to the authorisation page. However, the page doesn't display, and I see the following error.
This content cannot be displayed in a frame
Opening it in a new window then shows the authorisation page for my app. Clicking 'Go to App' then takes me to the App, but in it's own window, away from Facebook. Going back to FB and reloding the App page now works.
Stranger yet, when I am logged out and go to my app page, I get a Facebook 404 page (4oh4.php).
I'm guessing that I am doing this wrong somehow, so can anyone see anything obvious wrong with my script? Thanks.
To see what is happening - http://apps.facebook.com/dyne_drewett_news/
<?php
require 'fb/facebook.php';
$fbconfig['appUrl'] = 'my-app-url'; // Create An instance of our Facebook Application.
$facebook = new Facebook(array(
'appId' => 'my-app-ID', // Entered correctly in actual script
'secret' => 'me-app-secret', // Entered correctly in actual script
'cookies' => 'true',
));
// Get the app User ID
$user = $facebook->getUser();
if($user) :
try{ // If the user has been authenticated then proceed
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e){
error_log($e);
$user = null;
}
endif;
// If the user is authenticated then generate the variable for the logout URL
if($user) :
$logoutUrl = $facebook->getLogoutUrl();
?>
<!-- My HTML goes here -->
<?php
else :
$loginUrl = $facebook->getLoginUrl();
header('Location: '.$loginUrl);
endif;
?>
Because you are working in an iframe, you'll have to execute JavaScript redirects. Only that way will you be able to redirect the top most frame -
echo "<script language=javascript>";
echo "top.location.href ='".$url."';";
echo "</script>";
exit();
This is the only way to do complete redirects within a Facebook application. Any other redirect (with PHP for example) will only redirect the user within the iframe...

How to store google api (OAuth 2) permissions?

i'm using the examples provided in the "google-api-php-client"-Library (http://code.google.com/p/google-api-php-client/) to implement user login and authorization on my website with google services.
I didn't make any changes to the examples, except adding my Client-ID, etc..
The authorization itself works fine: Users can login and i can fetch the provided informations.
However, when leaving the page, the whole authorization procedure is called again; users are not remembered and need to grant permissions again, which is some kind of annoying and not typical for google-logins as i know them.
For example: On stackoverflow, i'm logged in with my google account.
Whenever i revisit this site, i'm logged in automaticly, or (if logged out) just have to log in again - i do not have to confirm the general rights again.
Using the examples on my site however, forces the user to allow access whenever the site is visited again.
Did i make any mistakes, when using the examples?
What do i have to do, to avoid the permission request over and over again?
Thanks in advance for any kind of help!
Use this code for first time to retrieve access_code and save it to database:
<?php
require 'google-api-php-client/src/Google_Client.php';
require 'google-api-php-client/src/contrib/Google_DriveService.php';
require 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes(array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'));
$client->setUseObjects(true);
$service = new Google_DriveService($client);
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
const ACCESS_TOKEN=$_SESSION['token'];
//code here to save in database
?>
Once ACCESS_TOKEN is saved in database change code to:
<?php
require 'google-api-php-client/src/Google_Client.php';
require 'google-api-php-client/src/contrib/Google_DriveService.php';
require 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes(array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'));
$client->setUseObjects(true);
$service = new Google_DriveService($client);
//ACCESS_TOKEN is already saved in database, is being saved on first time login.
$_SESSION['access_token'] = ACCESS_TOKEN;
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken())
{
$userinfo = $service->about->get();
echo '<script>console.log('.json_encode($userinfo).');</script>';
$userinfoService = new Google_OAuth2Service($client);
$user = $userinfoService->userinfo->get();
echo '<script>console.log('.json_encode($user).');</script>';
}
?>
That works fine for me.
Based on the kaushal's answer:
<?php
require_once 'globals.php';
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('YOUR_ID');
$client->setClientSecret('YOUR_SECRET');
$client->setRedirectUri('REDIRECT_URI');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$client->setUseObjects(true);
//if no token in the session
if ($_SESSION['google_token'] == '') {
//get stored token from DB
$sToken = $oDb->getOne("SELECT `google_token` FROM `users` WHERE `u_id` = " . (int)$_SESSION['user_id']);
//if no stored token in DB
if ($sToken == '') {
//autentificate user
$client->authenticate();
//get new token
$token = $client->getAccessToken();
//set token in session
$_SESSION['google_token'] = $token;
// set token in DB
$oDb->Query("UPDATE `users` SET `google_token`='$token' WHERE `u_id` = " . (int)$_SESSION['user_id']);
} else {
$_SESSION['google_token'] = $sToken;
}
}
$client->setAccessToken($_SESSION['google_token']);
//do what you wanna do with clients drive here
?>
The Google Drive SDK documentation includes a complete PHP sample application that you can use as a reference to get started:
https://developers.google.com/drive/examples/php
Basically, once the user is logged in and you retrieve access token and refresh token, you store those credentials in a database and reuse them instead of asking the user to authenticate every time.