How to use Codeigniter REST and Response method - codeigniter

I'm new to REST API and CURL and I've been referring to http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/
If I change the error code from 403 to 200 I get the output:
'Error occured'.
If I leave the errror code as 403 I get output:
'Something has gone wrong'.
From doing some reading it seems I'm correct to give an error code of some sort but how do I pass back some more details on the error? How should I be responding?
My API
public function login_put() {
$valid = $this->membership_model->validate_username($this->put('username'));
if($valid !== TRUE){
$this->response(array('status' => 'error', 'msg' => 'error_details'), 403);
}
}
MY CURL tester
function curl_put()
{
$this->load->library('curl');
$this->curl->create('http://localhost/api/login/format/json');
$this->curl->put(array(
'username' => 'my_username'
));
$result = json_decode($this->curl->execute());
if( isset($result->status) && $result->status == 'error' ) {
echo 'Error occured';
} else {
echo 'Something has gone wrong';
}
}

Looks like you're missing a reference in your curl url. If the file where login_put is called login.php, your url should look like:
http://localhost/api/login/login/format/json
First, we have your domain, then the reference to the API. The first login referrs to the controller within the api folder and the second refers to the function name you defined (login_put)

Related

How can I process a Response directly in Laravel?

I'm writing code in my Laravel Controller and I want to trap some exceptions firing a response directly without returning something to the routes.
For example, I wrote a method for returning a 404 response:
public static function respondNotFound( $message = null, $instantResponse = false )
{
$message = $message ? $message : "Not Found";
$statusCode = self::STATUS_NOTFOUND;
return self::makeResponse( array( 'status' => $statusCode, 'message' => $message ), $statusCode );
}
This method calls another one for building an Illuminate Response
protected static function makeResponse( $data, $statusCode = self::STATUS_OK, $instantResponse = false )
{
$response = Illuminate\Support\Facades\Response::json( $data, $statusCode );
$response->setCallback( Input::get( 'callback' ) );
if( $instantResponse ) {
//..... I want to fire my Response here!
}
else {
return $response;
}
}
Referring to the method above, I want to specify that my response must be fired directly rather than being returned outside, avoiding a "waterfall of return".
My solution is to set up some php headers and then kill the script, but I think that it's a bit rough.
Can someone help me?
Thanks in advance.
I'm confused - why dont you just use the App::missing() filter and handle your 404 in there?
In 'app/start/global.php' add:
App::missing(function($exception)
{
if (Request::ajax())
{
return Response::json( ['status' => 'error', 'msg' => 'There was an error. I could not find what you were looking for.'] );
}
elseif ( ! Config::get('app.debug'))
{
return Response::view('errors.404', array(), 404);
}
});
From looking at your code - you seem to be duplicating the response class. I dont understand why you are doing all of that, when you can just do
return Response::view('error', $message, $statuscode);
anywhere in your application...
Edit: you could also do
App::abort(404);
And then catch the abort filter in your app. You can change the 404 to be any HTTP response code you want.

Laravel 4 - Artadarek/OAuth-4-laravel issue

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.'

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.

Laravel giving 404 error even though user not authenticated

I am creating an api using Laravel 4.1. I am having problem with authentication and custom errors. I want to check first if the user is authenticated and then show error message. For example localhost:8080/trips/1 is not a valid a resource; if I go to that url it giving me 404 not found error even though I am not authenticated. My point is to check the authentication first then the errors. I am using laravel http basic authentication. Here is my filter code:
Route::filter('api.auth', function()
{
if (!Request::getUser())
{
App::abort(401, 'A valid API key is required');
}
$user = User::where('api_key', '=', Request::getUser())->first();
if (!$user)
{
App::abort(401);
}
Auth::login($user);
});
Here is my custom errors:
App::error(function(Symfony\Component\HttpKernel\Exception\HttpException $e, $code)
{
$headers = $e->getHeaders();
switch ($code)
{
case 401:
$default_message = 'Invalid API key';
$headers['WWW-Authenticate'] = 'Basic realm="REST API"';
break;
case 403:
$default_message = 'Insufficient privileges to perform this action';
break;
case 404:
$default_message = 'The requested resource was not found';
break;
default:
$default_message = 'An error was encountered';
}
return Response::json(array(
'error' => $e->getMessage() ?: $default_message,
), $code, $headers);
});
Here is my routes:
Route::group(array('before' => 'api.auth'), function()
{
Route::resource('trips', 'TripController', array(
'except' => array('create', 'edit')
));
});
The error code is executing before the filters thats why I am getting 404 error instead of getting 401. Is there any way to execute filter first then the error ?
I got this issue too and the way I worked around it (though I was not a fan at all) was doing the following inside the group(s) that don't contain a route sending requests to a controller's index method:
Route::any('/', function(){});
Granted, this shouldn't be how it works, the filter should trigger no matter what.

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