policy doesn't working in laravel in module - laravel-8

this is my Auth Service Provider :
<?php
namespace App\Providers;
use App\Models\Profile;
use App\Policies\ProfilePolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use RequestManager\Http\Models\RequestState;
use RequestManager\Policies\RequestStatePolicy;
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
Profile::class=>ProfilePolicy::class,
RequestState::class=>RequestStatePolicy::class,
];
public function boot()
{
$this->registerPolicies();
}
}
this is my policy array :
array:2 [
"App\Models\Profile" => "App\Policies\ProfilePolicy"
"RequestManager\Http\Models\RequestState" => "RequestManager\Policies\RequestStatePolicy"
]
I have a policy that is in its own module folder with this structure :
this is my controller :
public function showDepartmentRequests($id)//id = department id
{
$request=RequestState::where('department_id',$id)->get();
dd(\Gate::forUser(User::find(2))->allows('view',$request));
}
and this is my policy :
<?php
namespace RequestManager\Policies;
use RequestManager\Http\Models\RequestState;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class RequestStatePolicy
{
use HandlesAuthorization;
public function view(User $user, RequestState $requestState)
{
dd("test view policy");
}
}
Nothing is printed when I call the gate!
Is this error because I have to register a policy within a specific auth service Provider
other than the app\AuthServiceProvider?

Related

Target class 'Uploadcare' does not exist

Executed:
composer require uploadcare/uploadcare-php
I can find the library in vendor/uploadcare.
Then added to config/app.php:
'providers' => [
App\Providers\UploadcareServiceProvider::class,
]
and
'aliases' => Facade::defaultAliases()->merge([
'Uploadcare' => App\Facades\Uploadcare::class,
])->toArray(),
Then in App/Facades folder, created this file:
<?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class Uploadcare extends Facade {
protected static function getFacadeAccessor(){
return 'uploadcare';
}
}
This file is successfully referenced in config/app.php according to Visual Studio code.
Then in App/Providers I created UploadcareServiceProvider.php file:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Uploadcare\UploadcareConfiguration;
use Uploadcare\Interfaces\ConfigurationInterface;
class UploadcareServiceProvider extends ServiceProvider
{
public function boot()
{
$this->mergeConfigFrom(__DIR__.'/../../config/uploadcare.php', 'uploadcare');
}
public function register()
{
$this->app->bind(ConfigurationInterface::class, function ($app) {
return new UploadcareConfiguration();
});
$this->app->bind(Uploadcare\Api::class, function ($app) {
$config = $app->make(ConfigurationInterface::class);
return new Uploadcare\Api($config);
});
}
}
This file is successfully referenced in config/app.php according to Visual Studio code, it loads config/uploadcare.php which I have with the following (I redacted my public and private key):
<?php
return [
'public_key' => env('my-public-key'),
'private_key' => env('my-private-key'),
];
Then I created a controller to see whether I can successfully load a list of files form Uploadcare:
<?php
namespace App\Http\Controllers;
use Uploadcare\Api;
use App\Facades\Uploadcare;
use App\Uploadcare\UploadcareConfiguration;
use Uploadcare\Interfaces\ConfigurationInterface;
class UploadcareController extends Controller
{
public function index()
{
$api = Uploadcare::Api(config('uploadcare.public_key'), config('uploadcare.public_secret'));
$files = $api->files()->all();
return $files;
}
}
I call the controller using this route:
Route::get('/uploadcare', [UploadcareController::class, 'index']);
When visiting example.com/uploadcare I get the following error:
Target class [uploadcare] does not exist.
When I change the code in the controller to the following, I get the same error:
$files = Uploadcare::File()->getFileList();
When I hover Uploadcare in Visual Studio it successfully references the Facade.

notification system in Laravel 8

I am working on a laravel app where i have a user(organizer) who post an event ,and other users can comment on this event .
I am trying to make notifications system in laravel 8 between the organizer and the users when commenting on these event !
but i get this error (Call to a member function notify() on null).
This is my class :
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class NewCommentPosted extends Notification
{
use Queueable;
protected $user;
protected $event;
public function __construct($user, $event)
{
$this->user = $user;
$this->event = $event;
}
public function via($notifiable)
{
return ['database'];
}
public function toArray($notifiable)
{
return [
'user' => $this->user->name,
'eventTitle' => $this->event->title,
'eventId' => $this->event->id
];
}
This is storefunction() in my controller :
namespace App\Http\Controllers;
use App\Models\Event;
use App\Models\Comment;
use App\Notifications\NewCommentPosted;
use Illuminate\Http\Request;
class CommentController extends Controller
{
public function store(Event $event)
{
request()->validate([
'content' => 'required|min:5'
]);
$comment = new Comment();
$comment->content = request('content');
$comment->user_id = auth()->user()->id;
$event->comments()->save($comment);
$event->user->notify(new NewCommentPosted(auth()->user(), $event));
return redirect()->route('events.show', [$event->id, $event->title]);
}
Any help please !!?

Two middleware for only one Function in laravel

I can use only one middleware at a time..inside a constructor..I want to use if else condition inside constructor or two middleware.
I can use only one middleware inside constructor & if else condition also not working
I want only one function work or use according to middleware.I have two seprate table for authentication
Following middleware pointing to diffrent table
$this->middleware('auth:admin') - admins
$this->middleware('auth')- user
Example are follows
If else
class HRJob extends Controller
{
public function __construct()
{
if(Auth::guard('admin'))
{
$this->middleware('auth:admin');
}
else
{
$this->middleware('auth');
}
}
public function userdetails()
{
dd(Auth::user());
}
}
Two middleware
class HRJob extends Controller
{
public function __construct()
{
$this->middleware('auth:admin');
$this->middleware('auth');
}
public function userdetails()
{
dd(Auth::user());
}
}
You can try like this in the controller
class UserController extends Controller
{
/**
* Instantiate a new UserController instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('log', ['only' => [
'fooAction',
'barAction',
]]);
$this->middleware('subscribed', ['except' => [
'fooAction',
'barAction',
]]);
}
}
Also you can use Middleware groups
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
'auth:api',
],
];
More: https://laravel.com/docs/master/middleware

Using Policies in Laravel 5.5.14

I am new in using policies in Laravel. I am learning API Development using Laravel. My codes are as bellows.
TopicPolicy.php
<?php
namespace App\Policies;
use App\User;
use App\Topic;
use Illuminate\Auth\Access\HandlesAuthorization;
class Topicpolicy
{
use HandlesAuthorization;
public function update(User $user, Topic $topic)
{
return $user->ownsTopic($topic);
}
public function destroy(User $user, Topic $topic)
{
return $user->ownsTopic($topic);
}
}
AuthServiceProvider.php
<?php
namespace App\Providers;
use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
}
TopicController.php
<?php
namespace App\Http\Controllers;
use App\Topic;
use App\Post;
use Illuminate\Http\Request;
use App\Http\Requests\StoreTopicRequest;
use App\Transformers\TopicTransformer;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
class TopicController extends Controller
{
public function destroy(Topic $topic) {
$this->authorize('destroy',$topic);
$topic->delete();
return response(null,204);
}
}
I am getting error This action is unauthorized.. I don't know how to use policies. Could anyone guide me to use policies in Laravel 5.5.14 ?
In the AuthServiceProvider class you have to register the policy in the policies aray. Laravel documents is a good place to start
protected $policies = [
\App\Topic::class => \App\Policies\Topicpolicy::class
]
Second obtain a personal token from your app so you can use it to make calls to your api. You use passport and passport comes with ready to use Vue components to help you start.If you want to consume the api inside the same application check here.
I am not sure what you try to accomplice with the HandlesAuthorization trait inside the policy. Laravel has a middleware for this reason for us to use.

AspNet Identity MVC6 Violate the type constraint

I am trying to customize the ASP.NET identity to use integer based keys instead of string. The code compiles but when I run the app, it throws an error for violation of type constraint. Here's how my identity classes look:
public class AppUser: IdentityUser<int, AppUserClaim, AppUserRole, AppUserLogin>
{
public DateTime FirstTrip { get; set; }
}
public class AppRole : IdentityRole<int, AppUserRole, AppRoleClaim>
{
}
public class AppUserClaim : IdentityUserClaim<int>
{
}
public class AppRoleClaim : IdentityRoleClaim<int>
{
}
public class AppUserLogin : IdentityUserLogin<int>
{
}
public class AppUserRole : IdentityUserRole<int>
{
}
public class AppUserToken : IdentityUserToken<int>
{
}
My AppDbContext class:
public class AppDbContext: IdentityDbContext<AppUser,AppRole, int, AppUserClaim, AppUserRole, AppUserLogin, AppRoleClaim, AppUserToken>
{
//other code
}
And here's how I am setting up identity in my startup.cs class:
services.AddIdentity<AppUser, AppRole>(config => //register ASPNET Identity
{
config.User.RequireUniqueEmail = true;
config.Password.RequiredLength = 8;
config.Cookies.ApplicationCookie.LoginPath = "/Auth/Login";
})
.AddEntityFrameworkStores<AppDbContext, int>();
When I run the app, I get following error:
This setup is in line with some suggestions like:
Why does this violate the type constraint?
ASP.NET identity configuration exception and that breaks dotnet.exe run process
What am I missing?
For anyone running into similar problems, here's what I had to do make it work:
1) Implement custom UserStore and RoleStore to account for changed TKey.
2) Register your custom UserStore and RoleStore in the ConfigureServices method in startup.cs. So Instead of the suggested,
services.AddIdentity<AppUser, IdentityRole>()
.AddEntityFrameworkStores<AppDbContext, int>();
use the following,
services.AddIdentity<AppUser, IdentityRole>()
.AddUserStore<AppUserStore<AppDbContext>>()
.AddRoleStore<AppRoleStore<AppRole, AppDbContext>>();
If you are looking for actual implementation of the custom User and Role store, you can check the following link out(at the very bottom look for PR1):
https://github.com/aspnet/Identity/issues/970