Laravel Custom User Roles & Permissions based on routes - laravel

I've created a custom roles manager for Laravel (4.2) based on the named routes e.g.:
users.index, customers.create, vendors.update, orders.store, users.edit, customers.update, etc.
Basically anything registered as a Route::resource(...); within the routes.php file (with a few custom named routes)
I'm checking the permissions with this method:
namespace Acme\Users;
...
class User extends \Eloquent implements UserInterface, RemindableInterface {
...
public function hasPermissions($route)
{
$actions = ['users.index', 'users.create', 'users.edit', 'users.delete']; // fake data
if ( ! in_array($route, $actions))
{
return false;
}
return true;
}
}
Then, within the app/filters.php, I'm checking the current route against the User.
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
// check if the current authenticated User has permissions to access this route
if ( ! Auth::user()->hasPermissions(Route::current()->getName()))
{
return Redirect::route('dashboard.index');
}
});
Everything is working with any route using the GET method, but when it comes to PUT, PATCH, POST DELETE the Route::current()->getName() doesn't return anything.
Is there a better approach? I want everything to happen automatically, and I have a solution to this issue, but it's very involved. Is there a way to get the route name during a PUT, PATCH, POST or DELETE request?
Thank you.

Try to put your verification code inside after filter.
App::after(function($request, $response)
{
if ( ! Auth::user()->hasPermissions(Route::current()->getName()))
{
return Redirect::route('dashboard.index');
}
});

Related

Laravel Fortify modify RegisterViewResponse

I am trying to modify the behavior of Fortify Register route.
I am sending out custom register urls, if this url doesn't match my logic I need to redirect to a custom page, so you can not even enter /register.
But I am only getting a 302 redirect loop for /register.
To do so I created a RegisterViewResponse to override default behavior:
use Laravel\Fortify\Contracts\RegisterViewResponse as RegisterViewResponseContract;
class RegisterViewResponse implements RegisterViewResponseContract
{
public function toResponse($request)
{
$canEnter = true;
if($canEnter){
return redirect()->intended('/register');
} else {
return redirect()->intended("/otherPage");
}
}
}
I also added this to FortifyServiceProvider:
$this->app->singleton(RegisterViewResponse::class,Responses\RegisterViewResponse::class)
Thanks for any help or advice!

How do I move the livewire comonent NavigationMenu.php out of vendor

I have a jetstream laravel app, I have made changed to the NavigationMenu.php file in the vendor directory.
I want to move this to the app/Http/Livewire directory so I can protect my changes and commit to git, but when I do, I am getting a file not found.
I have updated the namespace to, namespace App\Http\Livewire;
I am sure I am missing something stupid but I cannot for the life of me find it.
Any pointers,
Thanks
UPDATE:
I am adding code that will dynamically add tabs and manage some sessions.
Example of the code I have added to NavigationMenu.php is
public function openCustomer(Customer $customer) {
// check customer is owner by auth user business
if(auth()->user()->business_id != $customer->business_id) {
abort(403, "Unauthorised Access");
}
$this->showCustomer = true;
$this->customer = $customer;
session(['customerId' => $customer->id]);
return redirect()->route('customer.show', [$this->customer]);
}
public function closeTab(Request $request, $sessionVariable) {
if($sessionVariable == 'showCustomer') {
$this->showCustomer = false;
$request->session()->forget(['customerId']);
}
}

October CMS - Extending the function of a plugin?

I've created a plugin to extend the User plugin and I now want to extend the update function of its controller.
Actually what I'd like to do is to check some data when an admin
clicks on the Update button then, according to the data, let the admin edit the user form as usual or redirect him to the user list.
I'm trying to do this through a route in my plugin:
Route::get('backend/rainlab/user/users/update/{id}', '\RainLab\User\Controllers\Users#check_update');
in my Plugin.php file
public function boot()
{
\RainLab\User\Controllers\Users::extend( function($controller) {
$controller->addDynamicMethod('check_update', function($recordId = null, $context = null) use ($controller) {
return $controller->asExtension('FormController')->update($recordId, $context);
});
});
}
But I get a blank page. The user form is not displayed.
Can someone helps me ?
This wont work as it will break life-cycle of back-end and direct call method of controller.
As other solution, we can use events :) - backend.page.beforeDisplay
In your plugin's plugin.php file's boot method
public function boot() {
\Event::listen('backend.page.beforeDisplay', function($controller, $action, $params) {
if($controller instanceof \RainLab\User\Controllers\Users) {
// for update action
if($action === 'update') {
// check data ($params) and make decision based on that
// allow user to edit or NOT
if(true) {
// just redirect him to somewhere else
\Flash::error('Please No.');
return \Redirect::to('/backend/rainlab/user/users');
}
// if all good don't return anything and it will work as normal
}
}
});
}
it will do the job based on condition you can allow user to edit OR not (redirect him with message to other action).
if any doubts please comment.

Laravel: What are functions in routes doing?

Can anyone tell why the documentation of Laravel, and others, show functions in routes that return / do something? In what context can you use this?
For example, I try to figure out Molly Connect.
Here is the corresponding code from https://github.com/mollie/laravel-mollie/blob/master/docs/mollie_connect.md
Route::get('login', function () {
return Socialite::with('mollie')
->scopes(['profiles.read']) // Additional permission: profiles.read
->redirect();
});
Route::get('login_callback', function () {
$user = Socialite::with('mollie')->user();
Mollie::api()->setAccessToken($user->token);
return Mollie::api()->profiles()->page(); // Retrieve payment profiles available on the obtained Mollie account
});
Its just a shortcut, to avoid having to create separate controller files and indirectly referencing those functions. Functionally, your example is no different from doing this:
Route::get('login_callback', 'LoginController#callback')
And then, LoginController.php
class LoginController
{
public function callback()
{
$user = Socialite::with('mollie')->user();
Mollie::api()->setAccessToken($user->token);
return Mollie::api()->profiles()->page();
}
}
See here

How to catch any link that came from upload/ in laravel 5?

im new in laravel 5.2, I just want to ask how you can catch a link that came from uploads like: http://sitename.com/uploads/59128.txt? I want to redirect them to login page if they tried to access any of route or link that came from uploads/{any filename}.
Yes you can achieve by protecting your route with auth middleware,
make a small FileController
class FileController extends Controller {
public function __construct()
{
$this->middleware('auth');
}
public function getFile($filename)
{
return response()->download(storage_path($filename), null, [], null);
}
}
and then in routes.php
Route::get('file/{filename}', 'FileController#getFile')->where('filename', '^[^/]+$');
And that's it. Now, your authenticated users can download files from storage folder (but not its subfolders) by calling http://yoursite.com/file/secret.jpg. Add you can use this URL in src attribute of an image tag.
answer's original source!
#xerwudjohn simple you can't.
When this file is in the public folder, everyone can access it whitout being logged in.
One method I tried for some minutes, create a new route:
Route::group(['middleware' => ['web', 'auth']], function () {
Route::get('/download/{id}', 'DownloadController#showFile');
});
create the function showFile in the DonwloadController
public function showFile($id)
{
return redirect('/image/'.$id.'.txt');
}
or use a Model to read uniqueIds out of any table and get the realfile name.
Cheers

Resources