I had some really complicated code, and now I've made it ridiculously simple, and it doesn't work.
Currently it simply takes me back to the page with the login URL echoed out.
Code is here:
<?php
require 'facebook.php';
// Create our application instance
// (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'sd',
'secret' => 'sda',
));
// Get User ID
$user = $facebook->getUser();
if($user) {
echo $user;
} else {
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>'http://www.facebook.com/pages/CharlesTestPage/225802194155435?sk=app_252946408094785','scope'=>'email'));
echo $loginUrl;
}
exit;
?>
Please. I have spent a whole paid work day on this now, and am at the point of crying, not only for myself but for my boss.
Cry.
Edit: OK, the weird thing is, if I have the redirect_uri set to the facebook tab, if it's not authenticated itself, then it constantly redirects in an infinite loop. However, if I remove the redire
This is what's working for me using PHP SDK 3.1.1. Try it and let us know if this works:
include('facebook.php');
session_start();
//facebook application
$config['appid' ] = "YOUR_APP_ID";
$config['secret'] = "YOUR_APP_SECRET";
$config['baseurl'] = "http://example.com/facebookappdirectory";
$config['appbaseurl'] = "http://apps.facebook.com/your-app-name";
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $config['appid'],
'secret' => $config['secret'],
'cookie' => true,
));
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email'
)
);
if ($user) {
try {
//get user basic description
$userInfo = $facebook->api("/$user");
$fb_access_token = $facebook->getAccessToken();
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
error_log('APP ERROR: '.$e);
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
if (isset($_GET['code'])){
header("Location: " . $config['appbaseurl']);
exit;
}
Check for
if(isset($_GET['code'])){
$user = $facebook->getUser();
$access_token = $facebook->getAccessToken();
}
Facebook return userID only after the login and that code.
Related
I already seen some tuts and example about it and I have implemented it somehow.
Method in controller looks like this:
The logic used is just php and I would like to use more a lumen/laravel logic and not just simple vanilla php. Also I have tried and did not worked anhskohbo / no-captcha
public function create(Request $request)
{
try {
$this->validate($request, [
'reference' => 'required|string',
'first_name' => 'required|string|max:50',
'last_name' => 'required|string|max:50',
'birthdate' => 'required|before:today',
'gender' => 'required|string',
'email' => 'required|email|unique:candidates',
'g-recaptcha-response' => 'required',
]);
//Google recaptcha validation
if ($request->has('g-recaptcha-response')) {
$secretAPIkey = env("RECAPTCHA_KEY");
// reCAPTCHA response verification
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretAPIkey.'&response='.$request->input('captcha-response'));
$response = json_decode($verifyResponse);
if ($response->success) {
//Form submission
//Saving data from request in candidates
$candidate = Candidate::create($request->except('cv_path'));
$response = array(
"status" => "alert-success",
"message" => "Your mail have been sent."
);
} else {
$response = array(
"status" => "alert-danger",
"message" => "Robot verification failed, please try again."
);
}
}
} catch(Exception $e) {
return response()->json($e->getMessage());
}
return response()->json(['id' => $candidate->id, $response]);
}
Okey. Google has an package for this:reCAPTCHA PHP client library
just: composer require google/recaptcha "^1.2"
and in your method inside controller:
$recaptcha = new \ReCaptcha\ReCaptcha(config('app.captcha.secret_key'));
$response = $recaptcha->verify($request->input('g-recaptcha-response'), $_SERVER['REMOTE_ADDR']);
if ($response->isSuccess()) {
//Your logic goes here
} else {
$errors = $response->getErrorCodes();
}
config('app.captcha.site_key') means that I got the key from from config/app.php and there from .env file.
If you have not config folder, you should create it, also create app.php file same as in laravel.
I have a problem with Laravel authentication system:
$credentials = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
'active' => 1
);
if(Auth::attempt($credentials)){
echo "fine";
}else{
echo "fail";
}
Auth::attempt()always return false.
Therefore, I tried to authenticate an other way:
$user = User::where('email','=',Input::get('email'))->firstOrFail();
if ($user->active && Hash::check(Input::get('password'), $user->password)){
echo "fine";
}else{
echo "fail";
}
This one works.
Would you know what could possibly make the attempt method not working?
Your code is correct, but I think you have edited User model ( check if you still implement UserInterface and RemindableInterface for exemple)
https://github.com/laravel/laravel/blob/master/app/models/User.php
I need to redirect a user to an error page (view/error/403.phtml) from within the Module.php of a module called Admin when a user is not allowed to access the specific resource. I have been searching for a solution to this, but so far had no success. The best I found was this question, the accepted answer to which doesn't work for me (and I currently cannot add comments to the linked question because I don't have the required reputation level) - the page is displayed as if there is no redirect at all and the user is allowed to access it. I have tried to replace the redirecting code with a simple die; to test if the isAllowed() is working properly, and it correctly shows a blank page, so the problem lies in the redirection itself.
Relevant code in Module.php is:
public function onBootstrap(MvcEvent $e)
{
$this->initAcl($e);
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach('route', array($this, 'checkAcl'));
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
public function checkAcl(MvcEvent $e)
{
// ...
if (!$this->acl->isAllowed($userRole, $controller, $privilege))
{
$response = $e->getResponse();
$response->setHeaders($response->getHeaders()->addHeaderLine('Location', $e->getRequest()->getBaseurl() . '/error/403'));
$response->setStatusCode(403);
$response->sendHeaders();
}
// ...
}
module.config.php
'view_manager' => array(
'display_exceptions' => true,
'exception_template' => 'error/403',
'template_map' => array(
'layout/layout' => __DIR__ . '/../view/layout/admin_layout.phtml',
'error/403' => __DIR__ . '/../view/error/403.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
),
'template_path_stack' => array(
'Admin' => __DIR__ . '/../view',
),
'strategies' => array(
'ViewJsonStrategy',
),
),
If I add the line
throw new \Exception($translator->translate('Access denied'));
after the code for redirection, I do get redirected to URL http://[servername]/error/403, but the contents of the page is, instead of my custom 403.phtml, a styled (with layout) 404 error page, stating that "The requested URL could not be matched by routing."
A better way to achieve what you want is to trigger a dispatch.error event in your checkAcl function rather than trying to do a redirect. You can then handle this event and display the 403 page.
To trigger the event:
if (!$this->acl->isAllowed($userRole, $controller, $privilege))
{
$app = $e->getTarget();
$route = $e->getRouteMatch();
$e->setError('ACL_ACCESS_DENIED') // Pick your own value, would be better to use a const
->setParam('route', $route->getMatchedRouteName());
$app->getEventManager()->trigger('dispatch.error', $e);
}
Then in your onBootstrap add a listener for the dispatch.error event:
use Zend\Mvc\MvcEvent;
...
$eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, <any callable>, -999);
In your callback for dispatch.error event you just attached to:
$error = $event->getError();
if (empty($error) || $error != "ACL_ACCESS_DENIED") {
return;
}
$result = $event->getResult();
if ($result instanceof StdResponse) {
return;
}
$baseModel = new ViewModel();
$baseModel->setTemplate('layout/layout');
$model = new ViewModel();
$model->setTemplate('error/403');
$baseModel->addChild($model);
$baseModel->setTerminal(true);
$event->setViewModel($baseModel);
$response = $event->getResponse();
$response->setStatusCode(403);
$event->setResponse($response);
$event->setResult($baseModel);
return false;
I am having some trouble with authentication using PHP SDK. I have downloaded "facebook.php" and "base_facebook.php" from github.
Below is the code I am useing but cant figure out where I am going wrong (new to all this).
<?php
require 'facebook.php' ;
$fbconfig['appid' ] = xxx;
$fbconfig['secret'] = "xxxx";
$fbconfig['baseurl'] = "xxx";
$params = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'xxx'
);
$loginUrl = $facebook->getLoginUrl($params);
$logoutUrl = $facebook->getLogoutUrl();
if(!$user)
{
echo "<P>You need to log into FB</p>\n";
exit();
}
else
{
echo "<p style=\"margin-bottom:20px;\"><a href=\"{$logoutUrl}\">Logout</p>\n";
}
?>
Any suggestions much appriciated :)
Based on this site, it looks like you need to explicitly construct your own Facebook object:
require_once("facebook.php");
$config = array();
$config[‘appId’] = 'YOUR_APP_ID';
$config[‘secret’] = 'YOUR_APP_SECRET';
$config[‘fileUpload’] = false; // optional
$facebook = new Facebook($config);
I am having trouble using the PHP SDK for authentication. The effect I am trying to get is whene a user visits the site if they are loged in with FB they see "Logout" which loggs them out when clicked but if they are not logged in when they arrive they should see "You need to log in with FB" which loggs them in. The effect I am currently getting is that the site displays the "You need to log in with FB" even if the user is already logged in, whene this is clicked the user is taken to facebook.com with an error message displayed reading "An error occurred. Please try later". Im sure I must be missing something in my code but cant figure out what, I am fairly new to FB development. Please see my code below. Any help much appriciated.
<?php
require_once("facebook.php");
$user = $facebook->getUser();
$config = array();
$config[‘appId’] = xxx;
$config[‘secret’] = '{secret}';
$facebook = new Facebook($config);
$fbparams = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'xxx'
);
session_start();
$loginUrl = $facebook->getLoginUrl($fbparams);
$params = array( 'next' => 'xxx' );
$logoutUrl = $facebook->getLogoutUrl($params);
if(!$user)
{
echo "<P>You need to log into FB</p>\n";
}
else
{
echo "<p style=\"margin-bottom:20px;\"><a href=\"{$logoutUrl} \">Logout</p>\n";
}
?>
Try this out
<?php
require_once("facebook.php");
$user = $facebook->getUser();
$config = array();
$config[‘appId’] = xxx;
$config[‘secret’] = '{secret}';
$facebook = new Facebook($config);
$fbparams = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'xxx'
);
$loginUrl = $facebook->getLoginUrl($fbparams);
$params = array( 'next' => 'xxx' );
$logoutUrl = $facebook->getLogoutUrl($params);
<?php if ($user) { ?>
<p>Logout</p>
<?php } else { ?>
<p>Click here to View Your Stalker of the Day</p>
<?php } ?>
You can not call $facebook before creating the instance, This code should work:
<?php
session_start();
require_once("facebook.php");
$config = array();
$config[‘appId’] = xxx;
$config[‘secret’] = '{secret}';
$facebook = new Facebook($config);
$user = $facebook->getUser();
$fbparams = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'xxx'
);
$loginUrl = $facebook->getLoginUrl($fbparams);
$params = array( 'next' => 'xxx' );
$logoutUrl = $facebook->getLogoutUrl($params);
if(!$user)
{
echo "<P>You need to log into FB</p>\n";
}
else
{
echo "<p style=\"margin-bottom:20px;\"><a href=\"{$logoutUrl} }\">Logout</p>\n";
}
?>
$params = array( 'next' => 'xxx' );
is deprecated SDK, use
$params = array( 'redirect_uri' => 'xxx' );
instead.