Laravel voyager policy based on user role - php

I can't find out how to determine user role in voyager. I am trying to do some policy check based on user role like this:
public function browse(User $user)
{
$user->role == 'admin';
}
But this returns false (This action is unauthorized.) even for user with role admin.
I am using laravel 5.6 and voyager 1.1.3

There is no role or role_name in users table in voyager. I have to use role_id
public function browse(User $user)
{
if ( $user->role_id == 1 ) {
return true;
} else {
return false;
}
}
Is there any way I can use role name?

Related

Get current logged in user's user role from a laravel controller

In my laravel application I have two user tyoes, admins and general users.
I have implemented function for users to download their certificates.
For that I got following function inside my controller
public function index(string $locale, CertificateUser $certificateUser)
{
$this->authorize('downloadCertificate', [Institute::class, $certificateUser, $institute]);
try {
return Storage::download($certificateUser->certificate_url);
} catch (FileNotFoundException $exception) {
return redirect()->back()->withErrors(__('Certificate could not be found.'));
}
}
now I want to execute this
$this->authorize('downloadCertificate', [Institute::class, $certificateUser, $institute]);
only if the logged in user's user role is an admin...
How can I get the current logged in User's user role from here?
> $user_role = Auth::user()->role;
> if($user_role == 'admin'){
> // You code Here
> $this->authorize('downloadCertificate', [Institute::class, $certificateUser, $institute]); } What's the issue ?
.Also Share you
User Model Here
Other Ways ....
if($user->hasRole->name('Admin'))
$user_roles = Auth::user()->roles()->get();
Now You can loop through $user_roles ..

How to restrict authenticated users to only access their on profile

I am stuck with users profile feature, I want only authenticated users to access their own profile only.
User with id: 1 can only access route /applicants/profile/1, otherwise return 404 Not found?
class ApplicantProfileController extends Controller
{
public function show(Applicant $applicant)
{
return view('applicant.show', compact('applicant'));
}
}
route::group(['prefix' => 'applicants', 'middleware' => 'auth:applicant'], function() {
Route::get('/profile/{applicant}', 'Profiles\ApplicantProfileController#show');
});
You can chech whether the logged user and the parameter user are the same by using the Illuminate/Support/Facades/Auth facade like this:
public function show(Applicant $applicant)
{
if (Auth::id() == $applicant->id) {
return view('applicant.show', compact('applicant'));
}
return abort(404);
}

Cant test if a database boolean is true in Laravel

I am trying to query our database to see if users can log in based on whether the organisation they belong to have logins enabled.
LoginController.php
protected function redirectTo()
{
$user = Auth::user()->id;
$userOrg = UserOrganization::where('user_id', $user)->first();
$org = Organization::where('id', $userOrg->org_id)->first();
if ($org->allow_org_login == 0) {
return '/login';
} else {
if(Auth::user()->has_changed_temp_password == false)
{
DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
DB::table('users')->where('id', $user)->increment('total_logins');
return '/user/password/change';
} else {
DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
DB::table('users')->where('id', $user)->increment('total_logins');
return '/overview';
}
}
}
trying to log in as a user belonging to an organisation with allow_org_login = 0 should redirect to the '/login' page, but instead it either logs the user in or prompts for a password change for a new user.
What am I doing wrong?
Edit: Debug contents of $org (allow_org_login on the bottom line)
since there is many to many relation between user and organization.
i suppose this relation is defined in User & Organization as in documentation:
https://laravel.com/docs/7.x/eloquent-relationships#many-to-many
considering that:
user may have more than an organization, and if any of the organization allowed log_in the user should login to your system
$user = Auth::user();
$userOranization=$user->organizations()->get();
$allowUserToLogin=false;
if($userOranization->where('allow_org_login',1)->first()!=null)
$allowUserToLogin=true;
and then:
if ($allowUserToLogin == 0) {
return '/login';
} else { ....
for redirectTo() method it will only fire when we using POST method for login.
inside you redirectTo() method your check condition and then you return '/login';
which it will redirectTo login page. but this time you already login then on login it will check if user login then it redirectTo url that we config on LoginController and protected $redirectTo; it will not call redirectTo() method. cuz this time we use redirect using GET method not POST.
if you want to put validate on redirectTo() method you can try below code:
protected function redirectTo()
{
$user = Auth::user()->id;
$userOrg = UserOrganization::where('user_id', $user)->first();
$org = Organization::where('id', $userOrg->org_id)->first();
if ($org->allow_org_login == 0) {
Auth::logout(); // logout user before redirect
return '/login';
} else {
if(Auth::user()->has_changed_temp_password == false)
{
// depend on you choice need to logout or not
DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
DB::table('users')->where('id', $user)->increment('total_logins');
return '/user/password/change';
} else {
// depend on you choice need to logout or not
DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
DB::table('users')->where('id', $user)->increment('total_logins');
return '/overview';
}
}
}
but for my option i will create new middleware for handle this.

user A session gets user B session laravel 5.6

The user A logged in with the role "admin". User B logged in as role "LimitedUser" on same web portal.
User A changes the permissions for use B. Both of them are on same page, i.e "Attach Permission to Role Page". User A disallows user B to access the page, and when User A submits the form, User B refreshes their page and gets the session of User A. This happens only if User A submits the form and User B redirects the page at the same time.
Laravel Version: 5.6
Entrust for Role Management
Session: File Based
Here's the code.
function updatePermissions(Request $request)
{
if (!hasRole('SuperAdmin') && !userCan('attach_permissions')) {
abort('404');
}
$roleId = $request->input('role_id');
$permIds = $request->input('perm');
$role = Role::where('id', '=', $roleId)->first();
if (!$role) {
abort('404');
}
if ($permIds == null) {
$role = Role::findOrFail($roleId);
$role_permissions = $role->perms()->get();
//print_r($role_permissions);exit;
$rolePermIds = array();
foreach ($role_permissions as $permission) {
$rolePermIds[] = $permission->id;
}
$role->perms()->detach($rolePermIds);
} else {
/*$role->perms()->sync(array_keys($permIds));*/
$permissions_new = (array_keys($permIds));
RolePermission::where('role_id', '=', $roleId)->forceDelete();
foreach ($permissions_new as $item) {
$r = new RolePermission();
$r->role_id = $role->id;
$r->permission_id = $item;
$r->save();
}
}
return redirect()->back();
}
there are several ways to solve this, one of them is to do Middleware in Laravel. https://laravel.com/docs/5.7/middleware#defining-middleware
Another way, creating Policies and Gates
https://laravel.com/docs/5.7/authorization#gates
In the your case, middleware can solve.

Prevent authenticated user to view other users profile on Laravel 5

I want to use Laravel 5 AuthServiceProvider to prevent logged in user to view other users profile. I'm using route like this user/1. How can I compare if the logged in user ID is match with the ID in the URL. If not then can't proceed.
Here's the following code I'm trying in my AuthServiceProvider:
$gate->define('view-profile', function($user, $id) {
return Auth::user()->id === $id;
});
However, the above code doesn't work as I can't pass the correct ID from the URL. Can anyone please help?
Here's the code I've in my controller:
if (Gate::denies('view-post', [Auth::user()->id, (int) $id])) {
return abort(403);
} else {
return 'success';
}
Just to let all of you know that I've figured it out myself using Gate::forUser() method. Here's the relevant code which I hope anyone may find helpful:
In AuthServiceProvider:
$gate->define('view-post', function($user, $id) {
return $user->id === (int) $id;
});
In your particular Controller:
$user = Auth::user();
if(Gate::forUser($user)->allows('view-post', $id)) {
return 'true';
}
return abort(403, trans('Sorry, not sorry!'));
If you route user controller with user, then user/1 will route the user controller show function, and in show function you can check your authentication user with id:
Function show ($id)
{
if ( Auth::user()->id == $id) {
//your code here
}
}

Categories