Problem with authenticating in laravel when using dynamic route configurations - laravel

I use JWT authentication for my laravel api middleware group. Here is my route configuration:
Route::group(['middleware' => ['api']], function() {
Route::post('login', 'AuthController#login');
Route::post('test', 'AuthController#test');
});
This code works well and I can't have unauthorized access to test method of my AuthController class:
class AuthController extends Controller
{
public function __construct()
{
$this->middleware(['jwt.auth'])->except('login');
}
public function login()
{
//...
}
public function test()
{
//...
}
}
but when I change the route config to identify controller's methods name dynamically (as you see in the following code snippet), the authentication does not work anymore and I can access test method without bearer token!
Route::group(['middleware' => ['api']], function() {
Route::post('/{controller}/{method}', function ($controller, $method) {
$controllerClass = 'App\\Http\\Controllers\\'.$controller.'Controller';
if(method_exists($controllerClass, $method))
{
$controller = App::make($controllerClass);
return $controller->callAction($method, array());
}
return abort(404);
});
});
Any idea?

Related

Authorize function is not working with middleware | Laravel

I have an authorization using middleware where Function could only run when authorized
this is my middleware:
class IsAdmin
{
public function handle($request, Closure $next)
{
if (auth()->check() && auth()->user()->is_admin == 1) {
return $next($request);
}
return abort(403, 'Forbidden');
}
}
my Controller:
public function destroy(int $bookId, int $reviewId, Request $request)
{
// #TODO implement
$check_bookReview = BookReview::firstWhere('id', $reviewId)->where('book_id', $bookId);
if ($check_bookReview && isAdmin()) {
BookReview::destroy($reviewId);
return response()->noContent();
} else {
abort(404);
}
}
and my api.php as well my Kernel:
'auth.admin' => \App\Http\Middleware\IsAdmin::class
Route::group(['middleware' => ['auth.admin']], function (){
Route::post('/books', 'BooksController#store');
Route::post('/books/{id}/reviews', 'BooksReviewController#store');
Route::delete('/books/{bookId}/reviews/{reviewId}', 'BooksReviewController#destroy');
});
and i have a User db field where it contains api_token and is_admin like below:
and my Postman still return 403 forbidden while i already gave an authorization by headers:
what should i do here, to fulfill my function?
Looks like your Authenticate middleware is not working, so it likely fails on auth()->check().
Make sure to use the auth middleware from Laravel, you can also use a guard as described here:
https://laravel.com/docs/9.x/authentication#protecting-routes

Unable to redirect after a user registers in Laravel Jetstream

I am successfully able to redirect whenever a user logs in. I am using the Login Response method. But when I am trying to do the same thing for the user when a user registers, it shows the URL in the browser, but I need to refresh to view the page to make it load. Something weird thing is happening here.
Following the below approach:
https://talltips.novate.co.uk/laravel/laravel-8-conditional-login-redirects
To understand the problem, please check the gif below. Login Response is working the way I expected, but Register Response is not working; it is behaving weirdly.
Login Response
Register Response
LoginResponse.php
namespace App\Http\Responses;
use Illuminate\Support\Facades\Auth;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
class LoginResponse implements LoginResponseContract
{
public function toResponse($request)
{
if (Auth::user()->hasAnyRoles(['Administrator', 'Employee'])) {
return redirect()->route('backend.dashboard');
}
return redirect()->route('frontend.dashboard');
}
}
RegisterResponse.php
<?php
namespace App\Http\Responses;
use Illuminate\Support\Facades\Auth;
use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract;
class RegisterResponse implements RegisterResponseContract
{
public function toResponse($request)
{
if(Auth::user()->hasAnyRoles(['Administrator', 'Employee'])) {
return redirect()->route('backend.dashboard');
}
return redirect()->route('frontend.dashboard');
}
}
JetstreamServiceProvider.php
public function boot() {
$this - > configurePermissions();
Jetstream::deleteUsersUsing(DeleteUser::class);
// Register New LoginResponse
$this - > app - > singleton(
\Laravel\ Fortify\ Contracts\ LoginResponse::class,
\App\ Http\ Responses\ LoginResponse::class);
// Register New RegisterResponse
$this - > app - > singleton(
\Laravel\ Fortify\ Contracts\ RegisterResponse::class,
\App\ Http\ Responses\ RegisterResponse::class);
}
AuthServiceProvider.php
public function boot() {
$this - > registerPolicies();
Gate::define('access-backend', function($user) {
return $user - > hasAnyRoles(['Administrator', 'Employee']);
});
Gate::define('access-frontend', function($user) {
return $user - > hasRole('Client');
});
}
Web.php
Route::middleware(['auth:sanctum', 'verified'])->group(function () {
\
Route::prefix('backend')->name('backend.')->middleware(['can:access-backend'])->group(function () {
Route::get('/dashboard', \App\Http\Livewire\Backend\Dashboard::class)->name('dashboard');
});
Route::prefix('frontend')->name('frontend.')->middleware(['can:access-frontend'])->group(function () {
Route::get('/dashboard', \App\Http\Livewire\Frontend\Dashboard::class)->name('dashboard');
});
});
Create your own RegisterResponse.php
use Illuminate\Http\JsonResponse;
use Laravel\Fortify\Contracts\RegisterResponse as Response;
class RegisterResponse implements Response
{
public function toResponse($request)
{
return $request->wantsJson()
? new JsonResponse('', 201)
: redirect(config('fortify.user'));
}
and register it in the JetstreamServiceProvider.php file, inside boot method
$this->app->singleton(
\Laravel\Fortify\Contracts\RegisterResponse::class,
\App\Http\Responses\RegisterResponse::class
);

Beginner in Laravel not working my routes inside middleware guest, and middleware auth all routes working well

This is all my routes inside web.php
Route::get('/', function(){
return view('welcome-body');
});
Auth::routes();
Route::get('/dashboard', 'HomeController#index')->name('userdashboard')->middleware('auth');
// Route::post('logout', 'Auth\LoginController#logout')->name('logout');
// Route::get('logout', 'Auth\LoginController#logout');
Route::get('logout','Auth\LoginController#logout');
Route::group(['middleware' => ['guest']], function ()
{
// About dropdown pages route
Route::get('/office-mayor', 'WebController#officemayor_about_page');
Route::get('/organizational-chart', 'WebController#organizationalchartpage');
Route::get('/directory', 'WebController#directorypage');
Route::get('/barangays', 'WebController#barangayspage');
Route::get('/barangays-detail', 'WebController#barangays_detail_page');
Route::get('/history', 'WebController#historypage');
// Stories & News dropdown pages route
Route::get('/stories', 'WebController#storiespage');
Route::get('/stories-detail', 'WebController#storiesdetailspage');
Route::get('/news', 'WebController#newspage');
Route::get('/news-detail', 'WebController#newsdetailspage');
Route::get('/gallery', 'WebController#gallerypage');
Route::get('/videos', 'WebController#videospage');
Route::get('/bids-and-awards', 'WebController#bidsandawardspage');
// Transparency route
Route::get('/transparency', 'WebController#transparencypage');
// Covid-19 update route
Route::get('/covid-updates', 'WebController#covidupdatespage');
});
Route::group(['middleware' => ['auth']], function ()
{
Route::get('authors/table', 'AllSystemController#indexauthorsdata')->name('authors.table');
Route::get('/authors/add', 'AllSystemController#createviewauthors')->name('create.authors');
Route::post('/authors/authorsdata/submit', 'AllSystemController#submitauthors')->name('submit.authors.data');
Route::get('/authors/view/{id}', 'AllSystemController#showviewauthors')->name('view.authors.data');
Route::get('/authors/edit/{id}', 'AllSystemController#editviewauthors')->name('edit.authors');
Route::patch('/authors/{id}', 'AllSystemController#updateauthordata')->name('update.authors.data');
Route::get('stories/table', 'AllSystemController#indexstoriesdata')->name('stories.table');
Route::get('/stories/add', 'AllSystemController#createviewstories')->name('create.stories');
Route::post('/stories/storiesdata/submit', 'AllSystemController#submitstories')->name('submit.stories.data');
Route::get('/stories/view/{id}', 'AllSystemController#showviewstories')->name('view.story.data');
Route::get('/stories/edit/{id}', 'AllSystemController#editviewstories')->name('edit.stories');
Route::patch('/stories/{id}', 'AllSystemController#updatestorydata')->name('update.story.data');
Route::get('activities/table', 'AllSystemController#indexactivitiesdata')->name('activities.table');
Route::get('/activities/add', 'AllSystemController#createviewactivities')->name('create.activities');
Route::post('/activities/activitiesdata/submit', 'AllSystemController#submitactivities')->name('submit.activities.data');
Route::get('/activities/view/{id}', 'AllSystemController#showviewactivities')->name('view.activity.data');
Route::get('/activities/edit/{id}', 'AllSystemController#editviewactivities')->name('edit.activities');
Route::patch('/activities/{id}', 'AllSystemController#updateactivitydata')->name('update.activity.data');
Route::get('blogs/table', 'AllSystemController#indexblogsdata')->name('blogs.table');
Route::get('/blogs/add', 'AllSystemController#createviewblogs')->name('create.blogs');
Route::post('/blogs/blogsdata/submit', 'AllSystemController#submitblogs')->name('submit.blogs.data');
Route::get('/blogs/view/{id}', 'AllSystemController#showviewblogs')->name('view.blog.data');
Route::get('/blogs/edit/{id}', 'AllSystemController#editviewblogs')->name('edit.blogs');
Route::patch('/blogs/{id}', 'AllSystemController#updateblogdata')->name('update.blog.data');
Route::get('news/table', 'AllSystemController#indexnewsdata')->name('news.table');
Route::get('/news/add', 'AllSystemController#createviewnews')->name('create.news');
Route::post('/news/newsdata/submit', 'AllSystemController#submitnews')->name('submit.news.data');
Route::get('/news/view/{id}', 'AllSystemController#showviewnews')->name('view.new.data');
Route::get('/news/edit/{id}', 'AllSystemController#editviewnews')->name('edit.news');
Route::patch('/news/{id}', 'AllSystemController#updatenewdata')->name('update.new.data');
Route::post('/storiesgallery/submit', 'AllSystemController#submitstoriesgallery')->name('add.stories.galleries');
Route::post('/activitiesgallery/submit', 'AllSystemController#submitactivitiesgallery')->name('add.activities.galleries');
Route::post('/blogsgallery/submit', 'AllSystemController#submitblogsgallery')->name('add.blogs.galleries');
Route::post('/newsgallery/submit', 'AllSystemController#submitnewsgallery')->name('add.news.galleries');
Route::get('contact_us', 'AllSystemController#indexcontactus')->name('sending.mail');
Route::post('contact_us/submit', 'AllSystemController#submitcontactus')->name('sending.mail');
});
and this is my Controller WebController
public function __contruct()
{
$this->middleware('guest');
}
// TOP BAR PAGES
public function officemayor_about_page()
{
return view('web-routes.about.office-mayor');
}
public function organizationalchartpage()
{
return view('web-routes.organizational.organizational-chart');
}
public function directorypage()
{
return view('web-routes.about.directory');
}
public function barangayspage()
{
return view('web-routes.about.barangays');
}
public function barangays_detail_page()
{
return view('web-routes.about.barangays-detail');
}
public function historypage()
{
return view('web-routes.about.history');
}
public function storiespage()
{
return view('web-routes.stories.stories');
}
public function storiesdetailspage()
{
return view('web-routes.stories.stories-detail');
}
public function newspage()
{
return view('web-routes.news.news');
}
public function newsdetailspage()
{
return view('web-routes.news.news-detail');
}
public function gallerypage()
{
return view('web-routes.gallery.gallery');
}
public function videospage()
{
return view('web-routes.video.videos');
}
public function bidsandawardspage()
{
return view('web-routes.bids_awards.bids-and-awards');
}
public function officemayorpage()
{
return view('web-routes.office-mayor.office-mayor');
}
public function covidupdatespage()
{
return view('web-routes.covid-updates.covid-updates');
}
public function transparencypage()
{
return view('web-routes.transparency.transparency');
}
if i want to go in the page example /office-mayor its return like this
error:
This page isn’t working right now localhost can't currently handle this request.
HTTP ERROR 500
I already use config:cache, route:cache and dump-autoload but doesn`t work it
How can i fix this...
I think this is happening because you have misspelled constructor it should be like public function __construct() and you don't have to define middleware in your constructor because you have already used it in routes.

Laravel authorization policy not being called

My authorization policy is not being called and I am receiving a 403 error. This is part of an API.
I have tried calling it from the controller by using the 'authorize' helper or via middleware. I have also tried using the auth()->guard('api')->user()->can().
DeckPolicy.php
public function view(User $user, Deck $deck)
{
dd('policy called');
if ($deck->private) {
return false;
}
return true;
}
AuthServiceProvider.php
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
'App\Deck' => 'App\Policies\DeckPolicy'
];
public function boot()
{
$this->registerPolicies();
}
}
DecksController.php
public function show(Deck $deck)
{
$this->authorize('view', $deck);
return new DeckResource($deck);
}
I expect the output to be 'policy called', but all I am receiving is a 403 error page when using Postman.
I would like to understand why the 'authorize()' helper function is not working as expected.

Laravel Route Always Goes to index

In my Laravel application, I store a new user via Ajax to the DB. The app always calls the index method. What's wrong?
When I remove the Route::post('/users', 'Admin\UserController#store'); route there is a 405 error. That's correct. But why doesn't it go to the store method?
Controller
<?php
class UserController extends Controller
{
public function index()
{
return view('admin.user.index');
}
public function create()
{
//
}
public function store(UserCreateRequest $request)
{
$user = User::createFromRequest($request);
return response()->json(["id" => $user->id]);
}
}
Routes
Route::group(['prefix' => 'admin', 'as' => 'admin.', ], function () {
Route::get('/users/{user}', 'Admin\UserController#show')->name('users.show');
Route::post('/users', 'Admin\UserController#store');
Route::put('/users/{id}', 'Admin\UserController#updateFromDatatable');
Route::delete('/users/{id}', 'Admin\UserController#destroy');
Route::get('/users', 'Admin\UserController#index')->name('users.index');

Resources