Laravel index policy - php

I using Laravel 5.4 and I am trying to write a policy for my index view. I am trying to use a Method Without a Model, I am receiving the following error:
HttpException in Handler.php line 133:
This action is unauthorized.
Here is my Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\County;
use Session;
use App\Http\Controllers\Controller;
class CountyController 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()
{
$counties = County::orderBy('id', 'desc')->paginate(5);
$this->authorize('index');
return view('county.index', array(
'counties' => $counties
));
}
Here is my AuthServicePovider:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\Role;
use App\County;
use App\Policies\CountyPolicy;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
County::class => CountyPolicy::class,
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('is-Admin', function ($user) {
if($user->roles()->where('name','Admin')->first()){
return true;
}
return false;
});
}
}
Here is my Policy:
<?php
namespace App\Policies;
use App\User;
use App\Role;
use App\County;
use Illuminate\Auth\Access\HandlesAuthorization;
class CountyPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the county.
*
* #param \App\User $user
* #param \App\County $county
* #return mixed
*/
public function index(User $user)
{
$userRoles = $user->getRoleNames();
$acceptedRoles = ['Sudo','Admin'];
$testArr = array_intersect($acceptedRoles, $userRoles);
dd($testArr);
if(!empty($testArr)){
return true;
}
return false;
//
}
/**
* Determine whether the user can view the county.
*
* #param \App\User $user
* #param \App\County $county
* #return mixed
*/
public function view(User $user, County $county)
{
$userRoles = $user->getRoleNames();
$acceptedRoles = ['Sudo','Admin','Client'];
$testArr = array_intersect($acceptedRoles, $userRoles);
if(!empty($testArr)){
return true;
}
return false;
//
}
/**
* Determine whether the user can create counties.
*
* #param \App\User $user
* #return mixed
*/
public function create(User $user)
{
//
}
/**
* Determine whether the user can update the county.
*
* #param \App\User $user
* #param \App\County $county
* #return mixed
*/
public function update(User $user, County $county)
{
//
}
/**
* Determine whether the user can delete the county.
*
* #param \App\User $user
* #param \App\County $county
* #return mixed
*/
public function delete(User $user, County $county)
{
//
}
}
I never get to dd($testArr) in the index policy. Also the view policy is working perfectly.
How do I write a policy for my index view?

keeping everything the same but changing:
$this->authorize('index');
to
$this->authorize('index', County::class);
fixed the problem. Apparently the model class needs to be passed on actions that don't require a model. This is only described under the middleware section of Laravel's docs, not the controller helpers... A little confusing.

Related

Send a email with Laravel Nova Actions

I would like to send a mail from a button on Laravel Nova with an action (which I think is the most appropriate).
I already have a template of the mail saved in the mailable, I have made my resource but I don't know what to put inside since I need to retrieve information from this resource like for example the name, a price or the date when the line was created (in my table related to my resource).
My resource code:
<?php
namespace App\Nova;
use App\Image;
use Gloudemans\Shoppingcart\Cart;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Nova\Fields\Currency;
use Laravel\Nova\Fields\Date;
use Laravel\Nova\Fields\Heading;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Http\Requests\NovaRequest;
use Techouse\IntlDateTime\IntlDateTime;
class Order extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = \App\Order::class;
public static $group = 'Paramètres';
public static function label()
{
return __('Commandes');
}
public static function singularLabel()
{
return __('Commande');
}
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'id';
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'id',
];
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Nom du client', 'name'),
IntlDateTime::make('Passée le', 'created_at')
->locale('fr')
->readonly(),
Currency::make('Prix', 'total')->currency('EUR'),
Text::make('Mode de paiement', 'gateway')
->readonly(),
Text::make('Numéro de téléphone', 'phone'),
Heading::make('Adresse de livraison'),
Text::make('Adresse', 'address')
->hideFromIndex(),
Text::make('Code postal', 'postal_code')
->hideFromIndex(),
Text::make('Ville', 'city')
->hideFromIndex(),
Text::make('Pays', 'country')
->hideFromIndex(),
];
}
/**
* Get the cards available for the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function cards(Request $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function filters(Request $request)
{
return [];
}
/**
* Get the lenses available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function lenses(Request $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function actions(Request $request)
{
return [];
}
}
My mailable code:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class ResendOrder extends Mailable
{
use Queueable, SerializesModels;
/**
* Elements de contact
* #var array
*/
public $contact;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(Array $contact)
{
$this->contact = $contact;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('emails.orderconfirmation')
->subject("Confirmation de commande");
}
}
And finally my Action code:
<?php
namespace App\Nova\Actions;
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 EmailOrderConfirmation extends Action
{
use InteractsWithQueue, Queueable;
/**
* Perform the action on the given models.
*
* #param \Laravel\Nova\Fields\ActionFields $fields
* #param \Illuminate\Support\Collection $models
* #return mixed
*/
public $name = 'Renvoyer le mail de confirmation de commande';
public function handle(ActionFields $fields, Collection $models)
{
return Action::message('Mail envoyé');
}
/**
* Get the fields available on the action.
*
* #return array
*/
public function fields()
{
return [];
}
}
I don't really know where to go and what to use, if you could enlighten me on that I would be very grateful, thank you!
// in EmailOrderConfirmation --nova action
// declare what you are using
// use Illuminate\Support\Facades\Mail;
// use App\Mail\ResendOrder;
public function handle(ActionFields $fields, Collection $models)
{
//loop over the orders that have been selected in nova
foreach ($models as $order) {
$contact = $order->contract; //however you are getting contract data
//assuming you have a $order->user order belongs to user relationship
//send mail to the user, with the order/contract details to create your email
Mail::to($order->user->email)->send(new ResendOrder($contact));
}
//return a message to nova
return Action::message('Mail envoyé');
}
// in Order /Nova resource
// declare what you are using
// use App\Nova\Actions\EmailOrderConfirmation;
public function actions(Request $request)
{
return [new EmailOrderConfirmation];
}

PHPUnit always takes me to login page,. regardless of what I do

So I am having a bit of an interesting problem. I am trying to build a forum for my website. I am trying to create a test that ensures registered users can submit new forum threads. Now, regardless of what I do, the test always ends up at the login paghe, even though I am logged in.
Here is something interesting, however, when I attempt to dd() the thread immediately after creation, Laravel seems to "skip over" the dd command and I end up with the "Thread title not found on the login page" error. I can dd() the $request object and that prints out fine, however, it seems after creating a new Thread model does Laravel skip over the dd($thread) command and I end up getting the login page once again.
I am pulling my hair out. Why is this happening?
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;
use App\Thread;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class CreateThreadsTest extends TestCase
{
use DatabaseMigrations;
function test_an_authenticated_user_can_create_new_forum_threads() {
$this->be(factory('App\User')->create());
$thread = factory('App\Thread')->make();
$this->post('forum/threads', $thread->toArray());
// you are missing this line
$this->get($thread->path())->assertSee($thread->title)->assertSee($thread->body);
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Thread;
class ThreadsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$threads = Thread::latest()->get();
return view('threads.index', compact('threads'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$thread = Thread::create([
'user_id' => auth()->id,
'title' => $request->title,
'body' => $request->body
]);
return redirect($thread->path());
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(Thread $thread)
{
return view('threads.show', compact('thread'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Thread extends Model
{
protected $guarded = [];
public function path() {
return "/forum/threads/" . $this->id;
}
public function replies() {
return $this->hasMany(Reply::class);
}
public function creator()
{
return $this->belongsTo(User::class, 'user_id');
}
public function addReply($reply) {
$this->replies()->create($reply);
}
}
When you make a new model using the factory helper, it doesn't have an ID
for example
So $thread->path() will return just "/forum/threads/" which is not what you want
You have to make the request to the location from the response or query the newly created Thread record
public function test_users_can_create_statuses()
{
$this->be(factory('App\User')->create());
$thread = factory('App\Thread')->make();
$response = $this->post('/forum/threads', $thread->toArray());
$this->get($response->headers->get('Location'))
->assertSee($thread->title);
->assertSee($thread->body);
}

Class App\Policies\StatusPolicy does not exist

I setup my classes so I can use Laravel Authorization and use the Policies feature. But I keep getting this error (Class App\Policies\StatusPolicy does not exist) when defining the middleware to my methods. This is what I have:
AuthServiceProvider.php
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\Status' => 'App\Policies\StatusPolicy',
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
StatusController.php
namespace App\Http\Controllers;
use App\Status;
use Illuminate\Http\Request;
class StatusController extends Controller
{
public function __construct()
{
$this->middleware('can:list,App\Status')->only('index');
$this->middleware('can:update,status')->only('edit');
}
// ...
StatusPolicy.php (generated by php artisan make:policy StatusPolicy --model=Status
namespace Policies;
use App\User;
use App\Status;
use Illuminate\Auth\Access\HandlesAuthorization;
class StatusPolicy
{
use HandlesAuthorization;
/**
* Verifica se o usuário tem permissão para listar os status.
*
* #param \App\User $user
* #return bool
*/
public function list(User $user)
{
return true;
}
/**
* Determine whether the user can view the status.
*
* #param \App\User $user
* #param \App\Status $status
* #return mixed
*/
public function view(User $user, Status $status)
{
//
}
/**
* Determine whether the user can create statuses.
*
* #param \App\User $user
* #return mixed
*/
public function create(User $user)
{
//
}
/**
* Determine whether the user can update the status.
*
* #param \App\User $user
* #param \App\Status $status
* #return mixed
*/
public function update(User $user, Status $status)
{
return true;
}
/**
* Determine whether the user can delete the status.
*
* #param \App\User $user
* #param \App\Status $status
* #return mixed
*/
public function delete(User $user, Status $status)
{
//
}
}
I found the problem.
For some reason, the command php artisan make:policy created a file with a wrong namespace. The fix was to change the namespace in the StatusPolicy.php file:
From namespace Policies;
To namespace App\Policies;
change the namespace in your StatusPolicy class to App\Policies;

Middleware For actions into Controller, Laravel 5.1

I have a Controller that have a index method, but also have a multiple levels of users that have access to this method, but single the admin can view all records of the database How can i add a middleware for select the action corresponding to user? I have the next code
<?php
namespace SET\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use SET\Http\Requests;
use SET\Http\Requests\LabRequest;
use SET\Http\Controllers\Controller;
use Illuminate\Routing\Route;
use SET\Lab;
use Validator;
use Auth;
use DB;
class LaboratorioController extends Controller
{
public function __construct(){
$this->beforeFilter('#find', ['only' => ['show','edit','update','destroy']]);
}
public function find(Route $route){
$this->laboratorio = Lab::findOrFail($route->getParameter('laboratorio'));
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$labs = Lab::all();
return view('comp.lab.index',['labs' => $labs]);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return view('comp.lab.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(LabRequest $request)
{ Lab::create($request->all());
Session::flash('message','Laboratorio creado correctamente');
return Redirect::to('/laboratorio');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show()
{
$teams = $this->laboratorio;
return view('comp.lab.show',['lab'=>$this->laboratorio]);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit()
{
return view('comp.lab.edit',['lab'=>$this->laboratorio]);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update(LabRequest $request)
{
$this->laboratorio->update($request->all());
Session::flash('message','El laboratorio se actualizo correctamente');
return Redirect::to('/laboratorio');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy()
{
$this->laboratorio->delete();
Session::flash('message','El laboratorio fue eliminado correctamente');
return Redirect::to('/laboratorio');
}
Thanks :D
Here's a general idea:
$user_group = $user::get_user_group($user_id)
if($user_group->group_id === 'something'){
\\method to return data for group 'something'
}
Get data by groups
$user_data = $user::get_data_by_group_id($group_id)

Wrong instance passed in Laravel DB post request

So I am working on a page in Laravel that generates invite codes upon email submission. I have run into this issue, every time when I enter my email into the form, it is supposed to generate an invite code an input it into my DB then redirect me. Instead I get this error code:
Argument 1 passed to myapp\Repositories\Invite\EloquentInviteRepository::__construct()
must be an instance of Illuminate\Database\Eloquent\Model, instance of
Illuminate\Foundation\Application given, called in /var/www/laravel/bootstrap/compiled.php
on line 4259 and defined
This is my EloquentInviteRepository.php file, apparently line 21 is the line in error:
<?php namespace myapp\Repositories\Invite;
use myapp\Repositories\Crudable;
use Illuminate\Support\MessageBag;
use myapp\Repositories\Repository;
use Illuminate\Database\Eloquent\Model;
use myapp\Repositories\AbstractRepository;
class EloquentInviteRepository extends AbstractRepository implements Repository, Crudable, InviteRepository {
/**
* #var Illuminate\Database\Eloquent\Model
*/
protected $model;
/**
* Construct
*
* #param Illuminate\Database\Eloquent\Model $user
*/
public function __construct(Model $model)
{
parent::__construct(new MessageBag);
$this->model = $model;
}
/**
* Find a valid invite by a code
*
* #param string $code
* #return Illuminate\Database\Eloquent\Model
*/
public function getValidInviteByCode($code)
{
return $this->model->where('code', '=', $code)
->where('claimed_at', '=', null)
->first();
}
/**
* Create
*
* #param array $data
* #return Illuminate\Database\Eloquent\Model
*/
public function create(array $data)
{
$data['code'] = bin2hex(openssl_random_pseudo_bytes(16));
return $this->model->create($data);
}
/**
* Update
*
* #param array $data
* #return Illuminate\Database\Eloquent\Model
*/
public function update(array $data){}
/**
* Delete
*
* #param int $id
* #return boolean
*/
public function delete($id){}
}
In case anyone was curious; the __construct() interface from Illuminate\Database\Eloquent\Model.php:
/**
* Create a new Eloquent model instance.
*
* #param array $attributes
* #return void
*/
public function __construct(array $attributes = array())
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
and Illuminate\Foundation\Application.php:
/**
* Create a new Illuminate application instance.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
public function __construct(Request $request = null)
{
$this->registerBaseBindings($request ?: $this->createNewRequest());
$this->registerBaseServiceProviders();
$this->registerBaseMiddlewares();
}
In case these help in debugging the issue!
As per request I have included my controller element used during the post function, this is the part that seems to activate the repository and prompt the error:
<?php
use myapp\Repositories\Invite\InviteRepository;
class InviteController extends BaseController {
/**
* InviteRepository
*
* #var myapp\Repositories\Invite\InviteRepository
*/
protected $repository;
/**
* Create a new instance of the InviteController
*
* #param myapp\Repositories\Invite\InviteRepository
*/
public function __construct(InviteRepository $repository)
{
$this->repository = $repository;
}
/**
* Create a new invite
*
* #return Response
*/
public function store()
{
$invite = $this->repository->create(Input::all());
}
}
RepositoryServiceProvider.php
<?php namespace myapp\Repositories;
use Illuminate\Support\ServiceProvider;
class RepositoryServiceProvider extends ServiceProvider {
/**
* Register
*/
public function register()
{
$this->registerInviteRepository();
}
/**
* Register the Invite Repository
*
* #return void
*/
public function registerInviteRepository()
{
$this->app->bind('myapp\Repositories\Invite\InviteRepository', function($app)
{
return new EloquentInviteRepository( new Invite );
});
}
}
Any idea's as to what I am missing?
Thanks for the help guys,
You've been a great resource so far!
In the file RepositoryServiceProvider.php, replace this
$this->app->bind('myapp\Repositories\Invite\InviteRepository', function($app)
{
return new EloquentInviteRepository( new Invite );
});
With this:
$this->app->bind('myapp\Repositories\Invite\InviteRepository',
'myapp\Repositories\Invite\EloquentInviteRepository');

Categories