I created a policy for authorization, so I faced with this problem.
I have seen these solutions, but my problem didn't solve yet:
Solution 1
Solution 2
Solution 3
Here are the Codes:
Function used in ArticalesController Class:
public function show(Articale $articale)
{
$this->authorize('view', $articale);
return view('articales.show',compact('articale'));
}
ArticalePolicy Class:
<?php
namespace App\Policies;
use App\User;
use App\Articale;
use Illuminate\Auth\Access\HandlesAuthorization;
class ArticalePolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the articale.
*
* #param \App\User $user
* #param \App\Articale $articale
* #return mixed
*/
public function view(User $user, Articale $articale)
{
return $user->id == $articale->user_id;
}
AuthServiceProvider Class:
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
Articale::class => ArticalePolicy::class,
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
Try with your model name as like this replace it with your AuthServiceProvider
replace
Articale::class => ArticalePolicy::class,
with
'App\Articale' => 'App\Policies\ArticalePolicy',
Related
I am trying to implement policies in my project. All tries have proven unsuccessful despite following documentation to the letter. And also read numerous posts on SO about it and other media. I did as described in docs, but nonetheless it doesn't work. What gives?
In AuthServiceProvider:
<?php
namespace App\Providers;
use App\User;
use App\Job;
use App\Policies\JobPolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
'App\Job' => 'App\Policies\JobPolicy',
//Job::class => JobPolicy::class,
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
In policy:
<?php
namespace App\Policies;
use App\Job;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class JobPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view any jobs.
*
* #param \App\User $user
* #return mixed
*/
public function viewAny(User $user,Job $job)
{
//return (($user->isAdmin() || $user->isModerator() || $user->isUser()) && $user->status==1);
//return ($user->isMod());
return true;
}
In controller:
public function index()
{
$this->authorize('viewAny', User::class, Job::class);
return view("jobs.index");
}
My User model:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Role;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',"role_id"
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function role(){
return $this->belongsTo("App\Role", "role_id");
}
public function isMod()
{
$user = User::find(auth()->user()->id);
$role = $user->role()->first()->name;
if($role==="job board moderator"){
return true;
}
else{
return false;
}
}
}
And Job model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Job extends Model
{
protected $fillable = [
"title", "description", "email"
];
public function user(){
return $this->belongsTo("App\User","user_id");
}
}
In policy:
public function viewAny(User $user)
{
return true;
}
In controller:
public function index()
{
$this->authorize('viewAny', Job::class);
return view("jobs.index");
}
The way to call a model policy method changes depending on the number of parameters it has.
No object
/* In policy*/
public function viewAny(User $user)
/* In controller */
$this->authorize('viewAny', Job::class)`
1 object
/* In policy*/
public function view(User $user, Job $job)
/* In controller */
$this->authorize('view', $job)
More than 1 object
/* In policy*/
public function view(User $user, Job $job, AnotherModel $model)
/* In controller */
$this->authorize('view', [$job, $model])
Source: https://laravel.com/docs/5.8/authorization#creating-policies
I have a very basic policy
<?php
namespace App\Policies;
use App\Models\Comment;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class CommentPolicy
{
use HandlesAuthorization;
public function update(User $user, Comment $comment)
{
return true;
}
}
I call it in a view
#can('update', $comment)
Edit
#endcan
I register it
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
App\Models\Comment::class => App\Policies\CommentPolicy::class,
];
Even though it should always show because I've hardcoded true, nothing shows
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
\App\Models\Comment::class => \App\Policies\CommentPolicy::class,
];
I forgot the backslashes at the beginning
I am using laravel 5.4 for creating my project and i used auth controller for login and register what I need is to get the last login time of user and store it in database when i referred that i came about an idea of creating event listeners and i done it..
login event handling in laravel 5
This is in my
EventServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* #var array
*/
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
'Illuminate\Auth\Events\Login' => [
'App\Listeners\AuthLoginListener',
],
];
/**
* Register any events for your application.
*
* #return void
*/
public function boot()
{
parent::boot();
}
}
I defined listener as AuthLoginListner and my
> AuthLoginListner.php
<?php
namespace App\Listeners;
use Carbon\Carbon;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\User;
use Illuminate\Auth\Events\Login;
class AuthLoginListener
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param auth.login $event
* #return void
*/
public function handle(Login $event)
{
return "yes";
}
}
Here i just return one text now what my doubt is how its working and where i get this yes message it doesnot show me any error now have an doubt its working correcty or not if yes where i get this message ..please any one help me out i just confused with this ...
Here is how I achieved it.
I created a new Listenener here App/Listeners/LogSuccessfullLogin.php
namespace App\Listeners;
use Illuminate\Auth\Events\Login;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use \Carbon\Carbon;
class LogSuccessfulLogin
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param Login $event
* #return void
*/
public function handle(Login $event)
{
$event->user->last_login = Carbon::now();
$event->user->save();
}
}
and then in the EventServiceProvider, I observed for the Illuminate\Auth\Events\Login event as such:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* #var array
*/
protected $listen = [
'Illuminate\Auth\Events\Login' => [
'App\Listeners\LogSuccessfulLogin',
]
];
/**
* Register any events for your application.
*
* #return void
*/
public function boot()
{
parent::boot();
//
}
}
So each time a user is logging in, it will save the timestamp in the last_login field in the users table.
Hope this helps!
I use the "jrean/laravel-user-verification" package. When I click on the link with the token I want to redirect in my homepage and be already logged. How can I implement this? Thank you)
Laravel: 5.4
Package Version: 4.1
Solve this problem. Add to my register function (RegisterController) event:
public function register(VerificationRequest $request)
{
...
event(new Registered($user));
...
}
Сreate listener:
<?php
namespace App\Listeners;
use Illuminate\Auth\AuthManager;
use Jrean\UserVerification\Events\UserVerified;
/**
* Class UserVerifiedListener
* #package App\Listeners
*/
class UserVerifiedListener
{
/**
* #var AuthManager
*/
private $auth;
/**
* Create the event listener.
*
* #param AuthManager $auth
*/
public function __construct(AuthManager $auth)
{
$this->auth = $auth;
}
/**
* Handle the event.
*
* #param UserVerified $event
* #return void
*/
public function handle(UserVerified $event)
{
$this->auth->guard()->login($event->user);
}
}
And register it in :
app/Providers/EventServiceProvider.php
<?php
namespace App\Providers;
use App\Listeners\UserVerifiedListener;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Jrean\UserVerification\Events\UserVerified;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* #var array
*/
protected $listen = [
UserVerified::class => [
UserVerifiedListener::class
],
];
/**
* Register any events for your application.
*
* #return void
*/
public function boot()
{
parent::boot();
//
}
public function register()
{
$this->app->bind(UserVerifiedListener::class, function () {
return new UserVerifiedListener(
$this->app->make('auth')
);
});
}
}
I am using Laravel 5.0.* and followed the following answer: login event handling in laravel 5 but I am still not able to see the event firing.
Anyone could help me with this:
This is how my Event Handler Class looks like:
<?php namespace App\Handlers\Events;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
use App\User;
use Illuminate\Support\Facades\Log;
class AuthLoginEventHandler {
/**
* Create the event handler.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param User $user
* #param $remember
* #return void
*/
public function handle(User $user, $remember)
{
//
$user->login_counter = 1;
$user->save();
// $user->increment('login_counter');
Log::error('something wrong happened');
// dd("login fired and handled by class with User instance and remember variable");
}
}
And this is the EventServiceProvider:
<?php namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider {
/**
* The event handler mappings for the application.
*
* #var array
*/
protected $listen = [
'auth.login' => [
'App\Handlers\Events\AuthLoginEventHandler',
],
];
/**
* Register any other events for your application.
*
* #param \Illuminate\Contracts\Events\Dispatcher $events
* #return void
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
//
}
}
Appreciate your help
I use Laravel 5.2. I spent hours trying to figure out why my listener is not responding not knowing that I misspelled the event class name in the $listen array. Basically, if you fire your event like event(new SameEventClass(...)) make sure it is the same name you used in $listen => ['SameEventClass' => ['SameListener']]