Laravel 4 - Artadarek/OAuth-4-laravel issue - laravel-4

Hi i am laravel 4 begginer.
i try to use Artadek/OAuth-4-laravel package
Everything went well untill using the example what i did:
Route:
Route::get('lfb', array(
'as' => 'lfb',
'uses' => 'HomeController#signInWithFacebook'
));
Controller:
class HomeController extends BaseController {
public function signInWithFacebook() {
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode( $fb->request( '/me' ), true );
$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
echo $message. "<br/>";
//Var_dump
//display whole array().
dd($result);
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}
}
And blade :
#extends('layout.main')
#section('content')
Sign in with Facebook
#stop
Last error log from laravel.log:
Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException
open: F:\wamp\www\IbidsLR\bootstrap\compiled.php
{
$routes = $this->get($request->getMethod());
$route = $this->check($routes, $request);
if (!is_null($route)) {
return $route->bind($request);
}
$this->checkForAlternateVerbs($request);
throw new NotFoundHttpException();
}
protected function checkForAlternateVerbs($request)
And i get when press on the button "Whoops,somthing went wrong." and it redirect me to lfb page which i dont have any page called that name i just want to use fb login..
What wrong here?

Goes to your laravel folder, then open app/config/app.php and make sure 'debug' => 'true' and it will help you showing what kinds of error you are having now.
It is working fine with your routes and also signInWithFacebook() function. Make sure that you already created a config file for Artadek/OAuth-4-laravel package, and it will be in app/config/packages.
It is showing lfb page because that is your route -- your function will be working with it.
Please make sure debug is on and check your error again. It is hard to explain with just that 'Whoops, something went wrong.'

Related

Codeigniter 3 login check function not showing correct flashdata messages

I am creating a login check function. But my two flash data messages are not setting correct.
If user has logged on and then if the session expires it should set this
flash data message Your session token has expired!
And if the user has not logged on and tries to access a controller with out logging on
then it should set this flashdata message You need to login to
access this site!
For some reason it is always showing the second flashdata message.
Question: How am I able to use the two flashdata messages properly.
Controller: Login.php
Function: check
public function check() {
$uri_route = basename($this->router->directory) .'/'. $this->router->fetch_class();
$route = isset($uri_route) ? $uri_route : '';
$ignore = array(
'common/login',
'common/forgotten',
'common/reset'
);
if (!in_array($route, $ignore)) {
// $this->user->is_logged() returns the user id
if ($this->user->is_logged()) {
// $this->session->userdata('is_logged') returns true or false
if (!$this->session->userdata('is_logged')) {
// Redirects if the user is logged on and session has expired!
$this->session->set_flashdata('warning', 'Your session token has expired!');
redirect('admin/common/login');
}
} else {
$this->session->set_flashdata('warning', 'You need to login to access this site!');
redirect('admin/common/login');
}
}
I run function via codeigniter hook that way I do not have to add it on every controller.
$hook['pre_controller'] = array(
'class' => 'Login',
'function' => 'check',
'filename' => 'Login.php',
'filepath' => 'modules/admin/controllers/common'
);
What are you trying to check via the uri() is actually a very bad way of checking, also you should include login checks as a construct function not single.. here is what your function should look like:
function __construct()
{
parent::__construct();
if (!$this->session->userdata('logged_in')) {
// Allow some methods?
$allowed = array(
'some_method_in_this_controller',
'other_method_in_this_controller',
);
if (!in_array($this->router->fetch_method(), $allowed)
{
redirect('login');
}
}
}

Laravel 4 application is giving error while running as a facebook app

I am creating a facebook application in Laravel 4, the problem is it is giving me following error while running as a facebook application
Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException
but the same thing is working fine out of facebook.I followed this tutorial
http://maxoffsky.com/code-blog/integrating-facebook-login-into-laravel-application/
Following is my routes.php
Route::get('home', 'HomeController#showWelcome');
Route::get('/', function() {
$facebook = new Facebook(Config::get('facebook'));
$params = array(
'redirect_uri' => url('/login/fb/callback'),
'scope' => 'email,publish_stream',
);
return Redirect::to($facebook->getLoginUrl($params));
});
Route::get('login/fb/callback', function() {
$code = Input::get('code');
if (strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with Facebook');
$facebook = new Facebook(Config::get('facebook'));
$uid = $facebook->getUser();
if ($uid == 0) return Redirect::to('/')->with('message', 'There was an error');
$me = $facebook->api('/me');
return Redirect::to('home')->with('user', $me);
});
Edit: I have checked chrome console and getting this error
Refused to display 'https://www.facebook.com/dialog/oauth?client_id=327652603940310&redirect_ur…7736c22f906b948d7eddc6a2ad0&sdk=php-sdk-3.2.3&scope=email%2Cpublish_stream' in a frame because it set 'X-Frame-Options' to 'DENY'.
Put this somewhere inside bootstrap/start.php:
$app->forgetMiddleware('Illuminate\Http\FrameGuard');
You can read this post:
http://forumsarchive.laravel.io/viewtopic.php?pid=65620
Try changing your callback to be Route::post not Route::get. If my memory serves me correctly, Facebook places a POST request, not a GET request.
<?php
Route::get('login/fb/callback', function() {
$code = Input::get('code');
if (strlen($code) == 0) {
return Redirect::to('/')->with('message', 'There was an error communicating with Facebook');
}
$facebook = new Facebook(Config::get('facebook'));
$uid = $facebook->getUser();
if ($uid == 0) {
return Redirect::to('/')->with('message', 'There was an error');
}
$me = $facebook->api('/me');
return Redirect::to('home')->with('user', $me);
});
After looking at the link that you sent, the error actually tells you what is wrong.
REQUEST_URI /
REQUEST_METHOD POST
Loading that page is making a POST request to /, and like I suggested above, you'll need to change the route for the index to Route::post.

Display message after logout via Silex SecurityServiceProvider

I am using the SecurityServiceProvider to secure my Silex application and would like to display a message after the user has logged out by navigating to the logout_path route.
The message should be stored in the sessions flash bag so that my template can automatically display it after.
I have tried adding an application middleware, but where not able to hook my code in. The before hook doesn't seem to work, because it happens after security and thus after the security's redirected back to my home page.
The before hook with the Application::EARLY_EVENT seems to be to early because as far as I know does the Security provider destroy the session after logout.
Before I keep trying to find a sort of working but probably dirty solution I would like to ask what the best/cleanest solution for this case would be?
UPDATE: After npms hint for a logout event handler I found this article on Google, which describes how to tackle the problem in Symfony very well.
In Silex things are slightly different though and after reading the source of the SecurityServiceProvider I came up with this solution.
$app['security.authentication.logout_handler._proto'] = $app->protect(function ($name, $options) use ($app) {
return $app->share(function () use ($name, $options, $app) {
return new CustomLogoutSuccessHandler(
$app['security.http_utils'],
isset($options['target_url']) ? $options['target_url'] : '/'
);
});
});
class CustomLogoutSuccessHanler extends DefaultLogoutSuccessHandler {
public function onLogoutSuccess(Request $request)
{
$request->getSession()->getFlashBag()->add('info', "Logout success!");
return $this->httpUtils->createRedirectResponse($request, $this->targetUrl);
}
}
The problem however is, that the flashbag message doesn't exist anymore after the redirect. So it seems that the session is being destroyed after the logout success handler is executed... or am I missing something? Is this even the right way to do it?
UPDATE: Still haven't found a proper solution yet. But this works.
I have added a parameter to the target url of the logout and use it to detect if a logout was made.
$app->register( new SecurityServiceProvider(), array(
'security.firewalls' => array(
'default' => array(
'pattern'=> '/user',
'logout' => array(
'logout_path' => '/user/logout',
'target_url' => '/?logout'
),
)
)
));
I had the same problem and your thoughts leaded me to a solution, thank you!
First define logout in the security.firewall:
$app->register(new Silex\Provider\SecurityServiceProvider(), array(
'security.firewalls' => array(
'general' => array(
'logout' => array(
'logout_path' => '/admin/logout',
'target_url' => '/goodbye'
)
)
),
));
Create a CustomLogoutSuccessHandler which handles the needed GET parameters for the logout, in this case redirect, message and pid:
class CustomLogoutSuccessHandler extends DefaultLogoutSuccessHandler
{
public function onLogoutSuccess(Request $request)
{
// use another target?
$target = $request->query->get('redirect', $this->targetUrl);
$parameter = array();
if (null != ($pid = $request->query->get('pid'))) {
$parameter['pid'] = $pid;
}
if (null != ($message = $request->query->get('message'))) {
$parameter['message'] = $message;
}
$parameter_str = !empty($parameter) ? '?'.http_build_query($parameter) : '';
return $this->httpUtils->createRedirectResponse($request, $target.$parameter_str);
}
}
Register the handler:
$app['security.authentication.logout_handler.general'] = $app->share(function () use ($app) {
return new CustomLogoutSuccessHandler(
$app['security.http_utils'], '/goodbye');
});
The trick to make this working as expected is to use another route to logout:
$app->get('/logout', function() use($app) {
$pid = $app['request']->query->get('pid');
$message = $app['request']->query->get('message');
$redirect = $app['request']->query->get('redirect');
return $app->redirect(FRAMEWORK_URL."/admin/logout?pid=$pid&message=$message&redirect=$redirect");
});
/logout set the needed parameters and execute the regular logout /admin/logout
Now you can use
/logout?redirect=anywhere
to redirect to any other route after logout or
/logout?message=xyz
(encoded) to prompt any messages in the /goodbye dialog.

CodeIgniter 404 Bad request error

I'm working with codeIgniter. I am making a login form which checks the members details with the database.
However when I click to login I get this error message:
The requested URL /waitronmain/login.php/login/validate_credentials was not found on this server.
However this is my login.php file and as you can see validate_credentials() does exist.
class Login extends CI_Controller{
function index()
{
$data['main_content'] = 'login_form';
$this->load->view('includes/template', $data);
}
function validate_credentials()
{
//load model to query db
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query){ //if credentials validated
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this ->session->set_userdata($data);
redirect('site/members_area');
}
else{ //if not validated load login form again.
$this->index();
}
}
}
Any idea what's going wrong? I should be going on to the 'members_area' page as I know the details I am entering are correct.
Any help would be much appreciated.
what is this??
/waitronmain/login.php/login/validate_credentials
login.php should be not in url i think you should do:
/waitronmain/login/validate_credentials
(assuming you removed index.php from urls and you are inside the waitronmain/ root )

Custom Error 500 page not displaying using Event::override - Laravel

I am able to use the Event::Override function successfully with the 404 event but not the 500 event. I simply wish the event to redirect to the front page with a flash message, as I am able to do fine with 404 events.
Is there something else I need to do to get the 500 events also redirecting to my front page? see code below in routes.php file:
Event::listen('404', function() {
return Response::error('404');
});
Event::listen('500', function() {
return Response::error('500');
});
Event::override('404', function() {
Session::flash('error', '<strong>Error 404 - Not Found.</strong> The page you are looking for is either <u>invalid</u> or <u>may no longer exist</u>. You are now back at our home page.');
return Redirect::to_route('home');
});
Event::override('500', function() {
Session::flash('error', '<strong>Error 500 - Internal Server Error.</strong> Something went wrong on our servers, apologies for that. Please contact us if this persists.');
return Redirect::to_route('home');
});
any ideas?
I've been able to work around this by updating the 500 error file directly in the \application\views\error folder.
One of my mobile application need a error as json format. I got it's solution from laravel forum . For catching http error
App::error( function(Symfony\Component\HttpKernel\Exception\HttpException $exception) {
$code = $exception->getStatusCode();
// you can define custome message if you need
return Response::json( array(
'message' => $exception->getMessage() ,
'code' => $code ,
) , $code);
});
Catch unhandled like db error, ..
App::error(function(Exception $exception , $code )
{
return Response::json( array(
'message' => $exception->getMessage() ,
'code' => $code ,
), $code );
});

Resources