I'm new at Laravel, and I'm trying to make Policies that will prevent user that doesn't have id_level 1 which is admin to access InventarisController, but the InventarisPolicy doesn't send variable to InventarisController.
it's my Inventaris Policies
InventarisPolicy.php
<?php
namespace App\Policies;
use App\{User, Level};
use Illuminate\Auth\Access\HandlesAuthorization;
class InventarisPolicy
{
use HandlesAuthorization;
/**
* Create a new policy instance.
*
* #return void
*/
public function __construct()
{
//
}
public function inventaris_add(User $user)
{
$user->id_level == 1;
// dd($user);
// $user->id_level == 2;
}
}
it's my Inventaris Controller
InventarisController.php
<?php
namespace App\Http\Controllers;
use App\{Inventaris, DetailPinjamanView};
// use Illuminate\Http\Controllers\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
// use App\Http\Controllers\Auth\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class InventarisController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
// $viewpinjaman = DetailPinjamanView::all();
$this->authorize('inventaris_add', $user);
$inventaris = Inventaris::all();
return view('index', compact('inventaris'));
}
Related
I'm using Laravel Nova 3 Queued Actions.
I have over 25K records in my table.
I want to Laravel Nova Action create new job only if model has attribute status == 1.
I tried to use continue in foreach loop but it does'nt work.
<?php
namespace App\Nova\Actions;
use App\Http\Services\UserService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Collection;
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Fields\ActionFields;
class UserSynchronization extends Action implements ShouldQueue
{
use InteractsWithQueue, Queueable;
public $name = 'Synchronize User';
public static $chunkCount = 1;
public $withoutActionEvents = true;
public function __construct()
{
$this->connection = 'database';
//$this->queue = 'default';
}
/**
* Perform the action on the given models.
*
* #param \Laravel\Nova\Fields\ActionFields $fields
* #param \Illuminate\Support\Collection $models
* #return mixed
*/
public function handle(ActionFields $fields, Collection $models)
{
foreach ($models as $model) {
if (!$model->status !== 1) {
continue;
}
UserService::synchronize($model);
}
return Action::message('Users have been successfully synchronized');
}
/**
* Get the fields available on the action.
*
* #return array
*/
public function fields()
{
return [];
}
}
Create record in jobs table only if model->status === 1
I created all the policies with command artisan, php artisan make:policy ModelPolicy --model=ModelName, created UserPolicy and ProfilePolicy, the first one works fine, but the second one (ProfilePolicy) is calling UserPolicy.
ProiflePolicy.php
<?php
namespace App\Policies;
use App\Models\Profile;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Auth\Access\Response;
class ProfilePolicy {
use HandlesAuthorization;
// I'm use this to know what policy is being called
protected $template = '[ProfilePolicy] you cannot %s this resource!';
/**
* Determine whether the user can view any models.
*
* #param \App\Models\User $user
* #return mixed
*/
public function viewAny(User $user) {
return in_array( $user->profile->slug, ['administrator'] )
? Response::allow()
: Response::deny( sprintf( $this->template, 'LIST') );
}
...
AuthServiceProvider.php
<?php
namespace App\Providers;
use App\Models\Profile;
use App\Policies\ProfilePolicy;
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\Models\User::class => \App\Policies\UserPolicy::class,
Profile::class => ProfilePolicy::class,
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
ProfileController.php
<?php
namespace App\Http\Controllers\v0;
use App\Models\Profile;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Str;
class ProfilerController extends Controller {
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index( Request $request ) {
$query = Profile::query();
// UserPolicy is being called even commented
\Gate::authorize('viewAny', auth('staff')->user() );
query_page( $query, $request );
query_embed( new Profile, $query, $request );
$query->when( in_array(auth('staff')->user()->profile->slug, ['seller-manager']), function( $query ) {
return $query->whereSlug( 'seller' );
});
$data = $query->limit( $request->limit ?: config('app.limit_per_page') )->get();
return response()->json( responseFormat( false, $data ) );
}
....
API Response:
I have this event to assign role:
<?php
namespace App\Listeners\User;
use App\Events\User\Created;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Http\Request;
use Spatie\Permission\Traits\HasRoles;
class AssignRoles
{
private $request;
/**
* Create the event listener.
*
* #return void
*/
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* Handle the event.
*
* #param Created $event
* #return void
*/
public function handle(Created $event)
{
$event->user;
dd($this->request->get('role'));
// here is the best place to do all the logic about roles that is going to be attached in this user. E.g:
switch($role = $this->request->input('role'))
{
case $role == 'Asesor':
$event->user->assignRole('Asesor');
break;
case $role == 'Comprador':
$event->user->assignRole('Comprador');
break;
default:
$event->user->assignRole('Writer');
}
}
}
but Laravarel doesn't return only "input role", returns always all params in request ¿why?
this is the print message with command dd:
"_token=7WvSpLbPgRrQ570hcXRnUZiGUOUroXiFLFih1dTa&role=Asesor"
I'm new to Laravel and I'm trying to set up an email verification for job_seeker but after I register a new job_seeker I redirect to profile page which must be protected with job_seeker_verified middleware
in normal case I must be redirecting to job_seeker/verify which uses the route named job_seeker_verification.notice with the controller verification_controller and the function that shows the view with verify message but instead I get
forbidden page 403
namespace App\Http\Controllers\job_seeker;
use App\Job_seeker;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class job_seeker_profile_controller extends Controller
{
public function __construct()
{
$this->middleware(['job_seeker_auth', 'job_seeker_verified']);
}
public function show_profile(Job_seeker $job_seeker)
{
return view('profile.job_seeker_profile');
}
}
namespace App\Http\Middleware;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Support\Facades\Auth;
use Closure;
class Ensure_Job_Seeker_Is_Verified
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
$guard == 'job_seeker';
if (
!Auth::guard($guard)->user() || (Auth::guard($guard)->user() instanceof MustVerifyEmail &&
!Auth::guard($guard)->user()->hasVerifiedEmail())
) {
return $request->expectsJson()
? abort(403, 'Your email address is not verified.')
: Redirect::route('job_seeker_verification.notice');
}
return $next($request);
}
}
namespace App\Http\Controllers\job_seeker;
use Illuminate\Http\Request;
use App\Job_seeker;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\VerifiesEmails;
class Verification_Controller extends Controller
{
use VerifiesEmails;
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
protected $redirectTo = 'job_seeker.profile';
public function __construct()
{
$this->middleware('job_seeker_auth');
$this->middleware('signed');
$this->middleware('throttle:6,1')->only('resend');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(Request $request)
{
return $request->user()->hasVerifiedEmail()
? redirect($this->redirectPath())
: view('profile.job_seeker_verify');
}
public function verify(Request $request)
{
if ($request->route('id') != $request->user()->getKey()) {
throw new AuthorizationException;
}
if ($request->user()->hasVerifiedEmail()) {
return redirect($this->redirectPath());
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect($this->redirectPath())->with('job_seeker_verified', true);
}
}
Route::get('job_seeker_email.resend', [
'as'=>'job_seeker_email.verification.resend', 'uses'=>'job_seeker\Job_Seeker_Verication_email#resend'
]);
Route::get('job_seeker/verify', [
'as'=>'job_seeker_verification.notice', 'uses'=>'job_seeker\Verification_Controller#show'
]);
Route::get('job_seeker/verify/{id}', [
'as'=>'job_seeker_verification.verify','uses'=>'job_seeker\Verification_Controller#verify'
]);
Remove
$this->middleware('job_seeker_auth');
From the verification_controller constructor because it's returning 403 before it reaches the show or verify method
An unverified user can't verify themselves if they need to be verified to do so
I'm trying to find out how I could access the logged in users ID in the handle method of the listener.
This is how the listener looks like:
namespace App\Listeners;
use App\Events\ProjectWasDeleted;
class DeleteUserProjectMapping
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param ProjectWasDeleted $event
* #return void
*/
public function handle(ProjectWasDeleted $event)
{
$project = $event->project->toArray();
var_dump($project['id']); // This is working.
}
}
This is how the event:
namespace App\Events;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
class ProjectWasDeleted
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $project;
/**
* Create a new event instance.
*
* #param $project
*/
public function __construct($project)
{
$this->project = $project;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
The user id is necessary as I would like to delete in a pivot table a record that requires the user id & the project id.
You can access current user instance globally with:
auth()->user()
And get ID with:
auth()->id()
Or:
auth()->user()->id