laravel 5.1 authserviceprovider define a permission - laravel

Trying to sort out this new AuthServiceProvider in Laravel 5.1.
<?php
namespace App\Providers;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
$gate->define('test-permission', function ($user) {
return true;
});
}
In my blade I try
#if (Gate::allows('test-permission'))
hello world.
#endif
I get no love. If I change it to Gate::denies('test-permission') the hello world renders.
Ultimate I want to pull my permissions from my Entrust data to migrate my permissions to a Laravel 5.1 environment.

Laravel will only call your closure if there's a logged-in user.
If there's no logged-in user, Laravel will always deny everything.
If you are logged in, chances are you haven't properly registered the AuthServiceProvider.

Related

Voyager and Jetstream: Login to Admin Panel leads to Dashboard Page

I just started my first Laravel project and try to combine Jetstream Authentification with Voyager Admin Panel.
First of all, I installed Jetstream on a fresh Laravel installation and it worked so far:
Afterwards, I tried to add Voyager to generate the CRUDs for my website and added a new user with
php artisan voyager:admin your#email.com --create
But whenever I tried to login through the url "../admin", I was redirected to "../dashboard" from Jetstream.
Even if I reentered "../admin" as URL, I was redirected. As long as I was logged in, I cannot enter the Voyager Backend.
So I guess it's some kind of routing / middleware issue, but I cannot find out which issue it is.
Within the web.php Routing file, there's only the basic stuff:
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
});
Not sure if that's relevant, but my IDE recognizes Voyager:: as unknown class, even it works the same way on a different Laravel installation.
But from the look of it, I expected the Route::middleware() to redirect a logged in person which types the url "../dashboard" to the Dashboard view, but nothing more. Removing this Route also didnt help the problem, so I guess I was wrong.
But beside this, only the pure Voyager Routes are left, so I'm not sure where else I can look to solve this problem.
You can add custom responses on app/Http/Responses directory.
just make new responses called LoginResponse
then use this code
<?php
namespace App\Http\Responses;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
class LoginResponse implements LoginResponseContract
{
/**
* #param $request
* #return mixed
*/
public function toResponse($request)
{
$home = auth()->user()->is_admin ? '/admin' : '/dashboard';
return redirect()->intended($home);
}
}
Then, bind your LoginResponse in FortifyServiceProvider
You can use this code
<?php
namespace App\Providers;
// ...
use App\Http\Responses\LoginResponse;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
class FortifyServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
// ...
$this->app->singleton(LoginResponseContract::class, LoginResponse::class);
}
}
i know that it to late but for other users who had the same problem.
first i installed jetstream
int .env file APP_URL=http://localhost:8000
i installed voyager with dummy data
i added manualy in table user_roles this ligne ( the admin )
INSERT INTO `user_roles` (`user_id`, `role_id`) VALUES ('1', '1');
and it work
you can see this video i found in youtube i think it will help you .
https://www.youtube.com/watch?v=UDYZx5uIwmQ

Laravel api routes not working, it's always redirecting

I am having an issue with laravel doing my backend Api.
What I am trying to do is return logged user data with Auth::user();
I wrote the controller, the route for the controller method in api.php but when I try to go to the /api/route I am redirected to Home.
I also tried to remove the __construct() method from the controller, When I do this and try to go to the /api/route, dd($user) is returning null.
My controller:
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Resources\TeacherResource;
use Illuminate\Support\Facades\Auth;
class teacherApiController extends Controller
{
public function __construct(){
$this->middleware('auth');
}
public function information(){
$user = Auth::user();
dd($user);
}
}
Api.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::get('information', 'API\teacherApiController#information');
Anything I am doing wrong?
I am using the laravel authentication for register and login users.
I suppose you are not authenticated before calling this route that's why when the __construct was there it redirected you to the home, that's also why Auth::user() returns you null.
You are probably not authenticated before calling this route.
To manage the authentication you used laravel passport or even used JWT

Laravel sharing data with all views

I'm trying to run a user-related query to fetch data to appear in the top bar of my site on every view.
I've created a new BaseController according to the first answer here:
How to pass data to all views in Laravel 5?
and that's working for a simple test (just sharing a typed-out variable), but when I try and use Auth::user()->id in the __construct method of BaseController (which in my other controllers always returns the ID of the currently logged in user), I get Trying to get property 'id' of non-object.
I've tried adding use App\User at the top of BaseController (even though it isn't usually needed) and also tried adding in the bits for Spatie laravel-permission plugin, but neither has any effect.
I tried dd on Auth::user() and just get 'null'. My feeling is that the user details maybe haven't been loaded at this stage, but BaseController extends Controller same as MyWorkingController extends Controller so I'm not sure why Auth::user()->id doesn't work here when it does normally?
Create a Base Controller which has all the information that you want to share too all controllers/pages/views and let your others controllers extend it.
open file AppServiceProvider.php from folder Providers and write below code in boot function
view()->composer('*', function ($view)
{
$view->with('cartItem', $cart );
});
And now go to your view page and write :
{{ $cartItem }}
You cannot access Auth in constructors because middleware has not been run yet. You can use either View composer or give try this way though i haven't tested.
class BaseController extends Controller {
protected $userId;
public function __construct() {
$this->middleware(function ($request, $next) {
$this->userId= Auth::user()->id;
return $next($request);
});
}
}
Write this in AppServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use DB;
use Auth;
use App\Cart;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Schema::defaultStringLength(191);
view()->composer('*', function ($view)
{
view()->composer('*', function($view)
{
if (Auth::check()) {
$cart = Cart::where('user_id', Auth::user()->user_id)->count();
$view->with('cartItem', $cart );
}else {
$view->with('cartItem', 0);
}
});
});
}
}
In you view simply write
{{ $cartItem }}
For anyone interested, I just encountered the same problem and I've solved it with ServiceProvider:
Define your custom ServiceProvider with the command
php artisan make:provider CustomServiceProvider
Add a reference to your service provider in the config\app.php file, specifically in the providers array, adding this item to it:
\App\Providers\CustomServiceProvider::class,
Declare the variables you want to share in your provider's boot() method and share them by using the view()->share method:
public function boot()
{
$shared_variable = "Hello";
view()->share('shared_variable', $shared_variable);
}
You can now reference your variable in your blade files with the standard notation:
{{ $shared_variable }}

Laravel - Notifications Controller can't use method user()

I'm trying to add notification system to my Laravel project. I' watched this video to understand the system : https://www.youtube.com/watch?v=iDDUxqpNgSc
Notification table, model et controller are created. Also, i have created the view with Vue.JS and Pusher. It's work well !
However, in the notification controller, when i try to user Auth::user() method it's return null. I read somewhere it's because the middleware 'auth' is not already load when the controller is.
This is my NotificationsController file :
<?php
namespace App\Http\Controllers;
use App\Notification;
use Illuminate\Http\Request;
use App\Idea;
use App\User;
use Illuminate\Support\Facades\Auth;
class NotificationsController extends Controller
{
public function __construct()
{
}
function get(){
$notification = Auth::user()->unreadNotifications()->get();
return $notification;
}
function read(Request $request){
Auth::user()->unreadNotifications()->find($request->id)->markAsRead();
}
}
Do you have any idea how to solve this ?
Thank's for your time !
The answer was not about the Auth::user (It's accessible). I just baldy defined the notifiable_type in my model. It was App\Idea, it should be App\User

Laravel Policies not stopping delete action

I have just started using Policies within Laravel 5.4 to handle my authorization. I have been following the official documentation and created a PostPolicy.
<?php
namespace App\Policies;
use App\User;
use App\Post;
use Illuminate\Auth\Access\HandlesAuthorization;
class PostPolicy
{
use HandlesAuthorization;
public function delete(User $user, Post $post)
{
return false;
//return $user->id === $post->user_id;
}
}
My goal is to stop the ability to delete a post using Policies.
I am currently still able to delete and cannot find a way to implement these Policy rules.
You need to authorize actions. For example, you could do that:
if ($user->can('delete', $post)) {
Or in controller:
$this->authorize('delete', $post);
https://laravel.com/docs/5.5/authorization#authorizing-actions-using-policies

Resources