What is the best practice to tell to fronted app which Laravel routes are allowed for user roles? [closed] - laravel

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 days ago.
Improve this question
I have a back-end application in Laravel 9 and another front-end application in React.
In back-end application there are multiple user roles and permissions created and, for each route in routes/api.php file, is added a middleware to specify the permission.
Note: Multiple roles can be assigned to a permission.
Example:
Route::get('countries', [CountriesController::class, 'index'])->middleware( ['permission:view-countries']);
So In this case only users with roles which are assigned to permission view-countries can access the route /api/countries.
Front-end application has buttons or links and requests to Laravel are made when clicking on them. I need to know if logged in user on front-end have access to those requests before making the requests in order to show or not the buttons or links. I'm thinking to send a list of routes to the front-end, after log in, which are available for that user. Maybe another solution?

there is no standard way of doing what you are asking, this solely rely on your setup, data, and environment. like how many permission you have, how many routes will be part of the conditional buttons etc.
The easier approach you can do is simply grab the user role/permission when fetching the user from initial request, you store that user data somehwere inside your front-end app, then check the data for displaying those buttons or not.
If you want to grab all the routes avaible for permission based middleware, you can use Route::getRoutes() and filter them based on the middleware you pass.
here's an example which you can improve
//Get all permission of current user
$userPermissions = $request->user()->permissions;
// format them like the route middleware
$permissionsMiddleware = collect($userPermissions)->map( fn($item) => 'permission:'.$item )->toArray();
//should look like
// ['permission:permission1', 'permission:permission2', 'permission:view-countries']
//Grab all the Routes by route name
$allRoutes = collect( Route::getRoutes()->getRoutesByName() );
$userAllowedRoutes = $allRoutes
// format the data to only have middleware, path and name
->map( fn($route, $key) => [
'middleware' => $route->gatherMiddleware(),
'path' => $route->uri,
'name' => $key
])
// filter to only return routes that has middleware present on $permissionMiddleware
->filter( fn( $route ) => array_intersect( $permissionMiddleware, $route['middleware'] ) )
//remove the collection key
->values();

Related

How to retrieve User Access Token After Creation in Laravel [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I can generate user access when I log in or Register a User
I want to be able to use the token later in API
I have questions
Is it safe to store user access token in the database after creation
How do I retrieve access token after creation
I tried this
public function showprofile(Request $request)
{
$user = new UserResource(User::find($request->id));
$token = $user->token();
dd($token);
// return response ($user);
}
It returned null, I have checked oauth access token table, the user id I am sending is present.
Thanks.
1) yes, this is no problem. In fact, if you're using Laravel Passport, it will be done automatically. Passport's default migrations will make sure it's stored in a safe way. You can optionally publish the migrations yourself to adjust them if needed:
php artisan vendor:publish --tag=passport-migrations
2) If you've added the HasApiTokens trait to your user model. You'll be able to access the token like this:
$user->token()
Or if you need all tokens $user->tokens(). More info can be found in the passport documentation.
Update
You're trying to access the token on the UserResource. This doesn't contain the token(). Try to access the token before creating the resource like this:
public function showprofile(Request $request)
{
$user = User::find($request->id);
$token = $user->token();
$user = new UserResource($user);
dd($token);
// return response ($user);
}
Also, I'd recommend you to use Route Model Binding. This will make your controller much cleaner since you don't need to look up the model yourself, Laravel will do this automatically for you.

Laravel "conditional routing"?

I have an interesting problem I need to solve and looking for best way to approach it.
Have a laravel 5.4 app that is fronted by a few public static pages. App is a golf performance tracking app. User enters data and the app does some analysis and shows graphs etc.
Problem is that if a new user signs up they have no data and they need to enter a score for the app to "work"
User signs up, verifies email, etc. so they now have authorized access to the app.
What I want to do is check if the user has any scores in the db (fine I can do that easily) then if they have at least one score entered send them to the app. Fine.
If they have no scores I want to send them to a view that explains that they need to have to enter a score and present the form to do so.
Question is:
where is the best place to check if the user has no scores and then send them to the view to enter the score and not allow them to access any of the app views.
Looking for the best way to do this? Is it create the condition and check the db in the routes/web.php? Is there a better way to accomplish it? and if so what do I do with the routes that sit in:
Route::group(['middleware' => ['web','auth']], function () {
Create a custom middleware and check if the user has score and redirect to any route or display any view you want. Something like this.
public function handle($request, Closure $next)
{
$user = $request->user();
if ($user && ($user->score == 0)) {
return redirect()->route('instruction');
}
return $next($request);
}
Apply this new middleware to all the routes which shouldn't be accessed by users with no scores. Also make sure you use this middleware after auth and not before.

Laravel: Automatically add parameter to urls

I have an application in which you can create a service and a service can have its own partial view.
So I created a route group with {service} prefix:
Route::group(['prefix' => '{service}', ... ], ... ).
// http://.../my-service/my-url
However, in order to know in which service the user is I need to add the service in every single route I have in my application. So I have done a middleware that shares $service to every view:
view()->share(['service' => $service])
But I don't know how to add $service prefix to every route without explicitly adding it. I would like doing something like
route()->prefix(['service' => $service])
and then every route have the prefix $service:
url("myurl") // -> url("$service/my-url") or
route('my-route')
Any idea?
EDIT:
Finally I decided to create a ServiceType model, create a middleware with a parameter and set to my route groups. Then in view I offer the user to switch between services of the same type.
Not is what I was looking but it's OK for now.
Question is still open if anyone knows the answer.
Put all your routes you want prefixed in a group and then add the prefix
Laravel docs on route prefixes

how to restrict form submission from certain url - Laravel

if i want to block form submission from the following url, how can i do that?
http://laravel.dev/iframe/123
This url will generate dynamically and we will not use any javascript(only user's created JS will be there) on that page to block form submission.
I need to protect routes which are accepting inputs. For example:
Register user (usersController#store)
or other routes which are accepting forms.
is their any way , i can filter certain routes to prevent form submission in Laravel?
how to tell laravel to ignore forms submission from certain urls?
This may be what you're looking for:
$referer = Request::header('referer');
$restrictedList = Config::get('app.restricted'); // obviously change this to pull from your source
if(in_array($referer, $restrictedList))
App::abort(403, 'Unauthorized');

Separate controller for home/index site in cakephp? Best Practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I´m starting to developing with cake php. I have designed a DB model and baked my mvc´s.
Now i want a index / home site. This site should be an overview of possible actions which a user can do.
Should I use an app_controller for that or route to an existing controller even if that controller has nothing to do with a home site, or should I use a separate controller with no model just for displaying the overview and edit the route of / to point at this new Home Controller?
Whats the best practice for that?
Your question is a little vague to me. I am going to assume that by "site" you mean "page".
If by "overview of possible actions which a user can do" you mean a static page with links, then use the provided PagesController, and create a view at app/views/pages/home.ctp.
If by "overview of possible actions which a user can do" you mean a dynamic page with links and data, then create a controller action to feed the page the correct data.
Where that controller action goes should depend on where the data comes from.
If it lists the latest posts, create a PostsController::home() action.
If it needs data from the User model in order to determine what to display, then create a UsersController::home() action.
Finally, if you are mixing data from many models with no clear winner, or you are actually creating a home "site" instead of a "page", create a HomeController or DashboardController.
Read this post by teknoid for a nice succinct way of loading in arbitrary models when needed.

Resources