Policy with route group keeps returning 403 - php

I'm trying to use policy on a route group. I've included the bindings middleware and tried to list the ACTION and MODEL in the CAN middleware.
For some reason it keeps returning 403. Probably I didn't quite understood how the policies work.
I'm trying to enter the before method in the policy but It keeps returning 403. Also it would be lovely if someone explains how exactly should I list custom methods in the middleware.
I also did register my policy in the AuthServiceProvider
protected $policies = [
Service::class => ServicePolicy::class,
];
public function before(CustomAuth0User $user, Service $service)
{
dd($service);
}
Route::group(['prefix' => 'services', 'namespace' => 'Services', 'middleware' => ['bindings', 'can:getCancel, service']], function () {
Route::get('/{service}/cancel', 'ServiceController#getCancel');
Route::post('/{service}/cancel', 'ServiceController#postCancel');
Route::get('/{id}/reassign', 'ServiceController#getReassign');
Route::post('/{id}/reassign', 'ServiceController#postReassign');
Route::get('/{id}/close', 'ServiceController#getClose');
Route::post('/{id}/close', 'ServiceController#postClose');
Route::get('/{id}/history', 'ServiceController#getHistory');
});
Controller
public function getCancel(Service $service)
{
dd($service);
}

Related

How to access model method based on api auth in laravel 5.6?

I have user cars having many to many relation between users and cars. I am using passport and everthing is working properly (Sign-in, Sign-up etc) In my I have a method like below in Users Model
public function cars()
{
return $this->belongsToMany(Car::class, 'users_cars', 'user_id', 'car_id');
}
I also have API auth routes which is working fine
Route::group([
'prefix' => 'auth'
], function () {
Route::post('login', 'AuthController#login');
Route::post('signup', 'AuthController#signup');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
Route::get('car-list','CarController#carList');
});
});
And in CarController I am trying to get user cars based on auth login user_id as like below
public function carList(){
$User = new User();
return new CarResource($User->cars());
}
I am also using API resource for API's
use App\Http\Resources\Car as CarResource;
But it does not working so can someone kindly guide me how to fix the issue. I would appreciate, thank you so much.
In the CarController you are instantiating a new User object. They are never going to have any cars. If you want to get all the cars that the user who is logged in, you will need to do something like the following:
public function carList(){
$User = User::with('cars')->findOrFail(Auth::id());
return new CarResource($User->cars);
}

Error with an api route - Laravel 5.3

I'm trying to access to this route: http://anaketesting.tk/product-service/payment-notification Really is a route for api, but consuming the route, have same error that browser.
My route try 1:
Route::get('/product-service/payment-notification', "ProductServiceController#notification")->name('productService.notification');
My route try 2:
Route::get('/product-service/payment-notification', function(){
return \Response::json([
'CREATED' => true
], 201); #also i tryed return 201 directly...
});
My route try 3:
Route::get('product-service/payment-notification', [
'as' => 'productService.notification',
'uses' => 'ProductServiceController#notification'
]);
My notification méthod
public function notification(Request $request){
$date = Carbon::now();
$date = $date->format('Ymdhis');
file_put_contents(storage_path().'/notification_'.$date.'.json', \Response::json($request));
return \Response::json([
'CREATED' => true
], 201);
}
I have not an storage/logs error with this method, is as was ignored. Please help ;)
see the RouteServiceProvider of Laravel 5.3, it shows that api routes being grouped and prefixed with api by default.
/app/Providers/RouteServiceProvider.php
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* #return void
*/
protected function mapApiRoutes()
{
Route::group([
'middleware' => 'api',
'namespace' => $this->namespace,
'prefix' => 'api',
], function ($router) {
require base_path('routes/api.php');
});
}
So you need to prefix api in your url. for example
to call this route
Route::get('/product-service/payment-notification', "ProductServiceController#notification")->name('productService.notification');
you need to call
http://anaketesting.tk/api/product-service/payment-notification
not
http://anaketesting.tk/product-service/payment-notification
in TRY3, as your system is skipping some logs, there might be two different issues
Your system doesn't have sufficient permission to write data into log files. in order to use this, you have to give permission to your log files.
You can handle these types of exceptions by using CustomException,
go to App/Exceptions/Handler.php
public function render($request, Exception $exception)
{
if($exception instanceof RouteNotFoundException){
abort(404,'Invalid Route Requested');
}else{
return parent::render($request, $exception);
}
}

Laravel Refreshing JWT tokens

I have a small Lumen / Laravel app that is just used as an API. I am able to sign in and set JWT tokens but after a period of time they timeout, I was expecting them to refresh each time an Endpoint was hit.
I've been looking at the docs for Tymon's JWT-AUTH but I cannot seem to get it to work.
Below is an example of one of my end points which return an array of all the users in the db. But when the token timesout the endpoint returns the error You don't have previleges to view all users
I'd be very grateful if someone was able to advise me or show me how to make my code refresh a token when someone is hitting an endpoint.
Inside Controller
public function index(Request $request)
{
$user = JWTAuth::parseToken()->authenticate();
if (!$user->isAdmin()) {
return $this->error_respond(['error' => "You don't have previleges to view all users"]);
}
$users = $this->repository->findAllWithPlan();
return $this->respond(['users' => $users]);
}
Inside Routes.php
$app->group(['middleware' => 'jwt.auth'], function ($app) {
/**
* Show All users
*/
$app->get(
'users',
[
'as' => 'user.all',
'middleware' => 'cors',
'uses' => 'App\Http\Controllers\UserController#index'
]
);
});

laravel 5 nested routing issue

New to Laravel 5, and building a little Rest test app. So I'm envisioning 2 different endpoints for a single controller.
/myApp/public/index.php/states/{state}/cities //returns cities in a state
and
/myApp/public/index.php/states/{state}/cities/{city} //will do somethin else
its a little unclear to me how to set up the routes for this. I suppose I could have these endpoints use the same controller method, but it seems like better architecture to just route each to its own method.
So far, I've got 2 things that each individually work, but dont work together:
in routes.php
//route to the first endpoint
Route::resource('states.cities', 'StatesController');
//routes to the second endpoint if first is uncommented,otherwise blank page with no errors in log
Route::resource('states.cities', 'StatesController#cities');
And the relevant part of my controller code:
class StatesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index(Request $request, $state)
{
//works
$cities = States::where('state', '=', $state)->lists('name');
echo json_encode($cities);
}
public function cities(Request $request, $state, $city)
{
echo "second request";
echo $state;
echo $city;
}
......
Any one have any ideas on the proper way to handle this going forward? Cheers!
Try this.
Route::get('states/{state}/cities', [
'as' => 'state.cities',
'uses' => 'StatesController#index'
]);
And second.
Route::get('states/cities/{state}/{city}', [
'as' => 'city.of.state',
'uses' => 'StatesController#cities'
]);
Note: There is no need to use resource route in this case. The resource routes creates the whole array of different routes which you really don't need. Resource controllers

Middleware and beforeFilter auth won't work

I defined a resource route group
Route::group(['prefix' => 'api/v1'], function() {
Route::resource('words', 'WordController');
});
and I created a controller for all that routes. I want to set basic authentication for all requests so I added to the constructor of WordController: $this->beforeFilter('auth.basic'); But there is no effect. I still can get all words without any username and password provided. Does someone know why?
class WordController extends ApiController {
protected $wordTransformer;
function __construct(WordTransformer $wordTransformer)
{
$this->wordTransformer = $wordTransformer;
$this->beforeFilter('auth.basic');
//$this->middleware('auth.basic');
}
public function index()
{
$words = Word::all();
return $this->respond([
'words' => $this->wordTransformer->transformCollection($words->all())
]);
}
}
If you are using laravel 5, you can use middleware that replace filter. Using middleware is becoming the preferred practice and way of thinking about decorating your routes. Why your code not working because auth.basic is a type of middleware not filter.
You can attach the middleware in controller since you are using Route::group.
See the code below how to attach it.
Route::group(['prefix' => 'api/v1', 'middleware' => 'auth.basic'], function() {
Route::resource('words', 'WordController');
});
You can see at the above code use middleware name "auth.basic". How do you know the middleware. Before you can use the middleware, you must register the middleware by define the middleware in /app/Http/Kernel.php. If you open that file you can see the code below.
/**
* The application's route middleware.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
];
You can try something like below. authenticate user during the routing rather then controller.
Route::get('home', array('before' => 'auth', 'do' => function()
{
// your action here
}));
Route::filter('auth',function(){
if(Auth::guest())
return Redirect::to('login');
});

Categories