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
}
}
Related
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 ..
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.
I am currently new to Laravel. This is my fist time building with this framework. I 'm trying to create a login. It was easy by running the php artisan make:auth command however i'm trying to determine if the user that was login is regular user or admin?
$table->boolean('is_admin')->nullable();
I've tried to add that to my user model to determine if user is admin or not and try to modify my LoginController by adding this code.
public function determineTypeLogin(Request $request)
{
$user = auth()->user()->is_admin;
if ($user == 1) {
return "admin";
}
return "not admin";
}
however no luck.. Please help
Please check this
public function determineTypeLogin(Request $request)
{
$user = Auth::user()->is_admin;
if ($user == 1) {
return "admin";
}
return "not admin";
}
I think no need to check $user == 1 it return only tru or false so you can dirctly check like
public function determineTypeLogin(Request $request)
{
$user = Auth::user()->is_admin;
if ($user) {
return "admin";
}
return "not admin";
}
My laravel application is a social media site. Here's the route for visiting another laravel user's profile
Route::get('/dashboard/{id}', [
'uses' => 'UserController#getProfile',
'as' => 'profile.index',
'middleware' => 'auth'
]);
It works just fine. However, I've discovered a bug that when I input the Auth user's ID into the route, I get taken to the same page where I can then add myself as a friend, I do not want this to happen. I would rather get taken back to the home screen if I'm visiting my own profile.
Here's the controller:
public function getProfile($id)
{
if(Auth::user() === $id)
redirect('dashboard');
$user = User::where('id', $id)->first();
$posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
$photos = Photo::paginate(6);
return view('profile.index',compact('user','posts', 'photos'));
}
I've tried to get it to redirect to 'dashboard' instead of 'profile.index' if it's the Auth user's page instead of pulling up just like a regular non-auth profile, but can't seem to get it to work. Any ideas on how to fix this small bug?
You get user instance by Auth::user() not only the user ID. You are comparing instance with the numeric value. It will not work. You have to use Auth::id() or Auth::user()->id in order to get ID of the logged in user. The following code will work in your case.
public function getProfile($id)
{
if(Auth::id() == $id)
{
redirect('dashboard');
}
else
{
$user = User::where('id', $id)->first();
$posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
$photos = Photo::paginate(6);
return view('profile.index',compact('user','posts', 'photos'));
}
}
Let me know if it helps!
You try to compare the current user object to the request id, try this code:
public function getProfile($id)
{
if(Auth::id() === $id) {
redirect('dashboard');
}
$user = User::where('id', $id)->first();
$posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
$photos = Photo::paginate(6)
return view('profile.index',compact('user','posts', 'photos'));
}
I am using laravel 4 and here is my AdminController file :
class AdminController extends BaseController {
protected $layout = "admin.layout";
public function __construct() {
// security for the forms and access
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('auth.admin' , array('except' =>array('getIndex','postSignin')));
// using this one to display user value if login and is admin
if (Auth::check() && Auth::user()->isAdmin()){
$this->user = Auth::getUser();
View::share('user', $this->user);
}
}
// main admin page
public function getIndex(){
$this->layout->content = View::make('admin.login');
}
// get the dashboard page
public function getDashboard() {
$this->layout->content = View::make('admin.dashboard');
}
// missing pages all redirect to dashboard if user is logged in.
public function missingMethod($parameters = array()){
if (Auth::check() && Auth::user()->isAdmin())
$this->getDashboard();
else
$this->getIndex();
}
Here is my filters.php file :
Route::filter('auth.admin', function()
{
if(!Auth::check() && !(Auth::user()->isAdmin())){
return Redirect::guest('admin');
}
});
in my routes.php file I am doing this:
Route::controller('admin', 'AdminController');
here is what I want if you could help me :_
1) . I want to clean up my code where there is not that much checking for if user is logged and isAdmin.
2). right now if you are logged in and you go to "admin/" , it will show you the login page ? how could I fix it in an effective way.
3). also if you are not logged in and you go to "admin/dashboard" it will show you dashboard content ? how to fix
Thank you in advance for all your help :)
You can use route groups and use a single filter to validate them
Check the docs
http://laravel.com/docs/routing#route-groups
Add this in your routes.php file:
Route::group(array('before' => 'auth.admin'), function() {
Route::controller('admin', 'AdminController');
})
Declare filter in filters.php file:
Route::filter('auth.admin', function(){
// Assumed you have a '/login' url
if (Auth::guest() || (Auth::check() && !Auth::user()->isAdmin())) {
return Redirect::guest('login');
}
});
Also make sure you have the user()->isAdmin() method in your User model that you are using and it checks whether the user is an admin or not and returns a Boolean value, TRUE if the user is an admin otherwise FALSE.