How can I add ask username and password feature to only one of my laravel routes? - laravel

I have created a few forms in laravel. I want to restrict access to one of them only to a specific user.
I want to create a user and password myself.
This is my routes excerpt. This is the route I want to protect from access
Route::get('/tabledata_id_title', 'KedivimController#appearanceiddata');
This is my controller excerpt:
public function appearanceiddata()
{
//$magic = DB::table('prog_title')->select('pr_id', 'pr_title')->get();
$magic = DB::table('prog_title')->select('pr_id', 'pr_title')-> where('pr_index', '=', 1)->get();
return view ('takealook', ['magical' => $magic]);
}

This is a short fix for your problem.
public function appearanceiddata()
{
if (!Auth::guard('web')->check()) //check if someone is logged in
{
//redirect to login page.
}
else {
/*Check if the logged in user is your desired user.
Maybe try matching the logged in id with your desired id.
If you find that a user is logged in but they are not your desired user
then you may redirect them in some other place or show them a message. */
}
//$magic = DB::table('prog_title')->select('pr_id', 'pr_title')->get();
$magic = DB::table('prog_title')->select('pr_id', 'pr_title')-> where('pr_index', '=', 1)->get();
return view ('takealook', ['magical' => $magic]);
}
However, this practice is ok if you have one or two restricted field. But if you have more than that then you should read about middleware.

Related

Auth facade doesn't work without Sanctum api as middleware in Laravel 8

I'm creating an api through which anybody can view a page, however only admin can see all posts, while users are restricted to approved only. This is implemented via is_verified boolean variable where admin is given value of 1 and user the value of 0. I want to create a function like this
public function show(){
if(Auth::check()){
$showAllDetails = Events::all();
echo $showAllDetails;
}else {
$showUserDetails = Events:all()->where('is_verified',1);
echo $showUserDetails;
}
}
However Auth:check only works if I have sanctum api in my route
Route::middleware('auth:sanctum')->group(function () {
Route::get('view', [ViewController::class, 'show']);
});
If I run this code on Hoppscotch, it only shows if the admin is logged in (User don't require login). So a user can't see any post. If I remove the auth:sanctum middleware, only the else part of the code runs and no auth check or any stuff can run .
I need a way to incorporate both in a single function so that I can create a single route instead of creating two routes for different persons. Any way of doing such things?
public function show(){
if(Auth::check()){
$showAllDetails = Events::all();
echo $showAllDetails;
}else {
$showUserDetails = Events::where('is_verified',1)->get();
echo $showUserDetails;
}
}
I guess your else part is incorrect query, change your else part like above

how to restrict user from accessing another user's pages by inputing id in url laravel

I have a web app i'm working on.Users can create patients, which have a unique id. Problem I have is that when another user logs in, he can easily access patients not assigned to him by simply inputing their id in the url. Please how do i solve this? Heres a sample of my route for the
user to view his patient:
Route::get('patients/{patient}/view', 'Portal\PatientController#viewPatient');
and in the Patientcontroller:
public function viewPatient($patient){
$patient = Patient::where('id', $patient)->first();
return view ('portal.patient',compact('patient'));
}
Please what am I doing wrong?
You can use policies for that:
Policies are classes that organize authorization logic around a particular model or resource. For example, if your application is a blog, you may have a Post model and a corresponding PostPolicy to authorize user actions such as creating or updating posts.
Or gates:
Gates are Closures that determine if a user is authorized to perform a given action
I'd use policies, but you also can manually check if a user can view a page with something like:
if (auth()->id() !== $patient) {
return redirect('/')->with('message', 'You can not view this page');
}
You could also keep GET to access to this page without inputing the id. For example, if you want to obtain patients only from the current user logged in :
web.php :
Route::get('patients/view', 'Portal\PatientController#viewPatient');
Patientcontroller :
public function viewPatient(){
$id = auth()->id();
$patient = Patient::where('id', $id)->first();
return view ('portal.patient',compact('patient'));
}
Keep in mind that this will work only with an authenticated user.
If your database table structure is like this
Patients
--------
id //Unique ID of Patient
user_id //User that created
patient
Then you can do the check in controller like.
public function viewPatient($patient)
{
$patient_check = Patient::where('id', $patient)->where('user_id','=',Auth::user()->id)->first();
if($patient_check == null || count($patient_check) == 0)
{
return "You cannot view this patient";
}
else
{
return view ('portal.patient',compact('patient'));
}
}
This is simple and yet does the work.

How to give access to views to specific user in laravel?

I have a Category Controller which checks if user is logged in
class CategoryController extends Controller
{
public function __construct() {
$this->middleware('auth');
}
...
My category routes are :
//Category Controller
Route::get('admin/category/{category}/edit', ['uses'=>'categoryController#edit','as'=>'admin.category.edit']);
Route::put('admin/category/{category}', ['uses'=>'categoryController#update','as'=>'admin.category.update']);
Route::get('admin/category/{category}', ['uses'=>'categoryController#show','as'=>'admin.category.show']);
Route::delete('admin/category/{category}', ['uses'=>'categoryController#destroy','as'=>'admin.category.destroy']);
Route::get('admin/category/create', ['uses'=>'categoryController#create','as'=>'admin.category.create']);
Route::get('admin/category', ['uses'=>'categoryController#index','as'=>'admin.category.index']);
Route::post('admin/category', ['uses'=>'categoryController#store','as'=>'admin.category.store']);
Is there a way to give access to these views to only specific user?
For example if user email is admin123#gmail.com then he is allowed to go to those view.
I know I can check like this
if(Auth::user()->email == 'admin123#gmail.com')
{
dd('admin Logged in');
}
But this is possible if i go to individual view and put all my content in the if statement.
Is there way to handle this in controller.
Thanks.
You can use the middlewares for these kinds of work.
From the docs
Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
You should restrict users by route groups. Use middleware for that.
However, if you have complicated logic, sometimes you may want to check if user is admin in controller, model and other classes. In this case you can create global helper isAdmin() and use it for simple checks. Examples:
if (isAdmin()) {
// Do something
}
{{ isAdmin() ? 'active' : '' }}
A better way to define user role is like 0 for admin, 1 for user, 2 for member.
Then you can check the user role like:
if(Auth::check())
{
if(Auth::User()->user_type == 0)
{
return view('admin_dashboard');
}
else if(Auth::User()->user_type == 1)
{
return view('user_dashboard');
}
else if(Auth::User()->user_type == 2)
{
return view('member_dashboard');
}
}

Laravel - Deleting auth user account while user is logged in

I'm trying to build a function where a user can delete their own account while they are logged in. I'm struggling to find any example or logic/best practices.
The controller looks like this:
public function postDestroy() {
$user = User::find(Auth::user()->id);
$user = DB::delete('delete from users')->user(id);
return Redirect::route('site-home')->with('global', 'Your account has been deleted!');
}
I'm trying to grab the current Auth (logged in) user and use their id to delete them from the database. Then send them to the home page with a message.
Also, do I need to make sure the session is properly closed during this process, such as Auth::logout(); ?
I'm pretty new to Laravel, so any help would be appreciated.
Not sure how your routing looks like, but this should do the job.
$user = \User::find(Auth::user()->id);
Auth::logout();
if ($user->delete()) {
return Redirect::route('site-home')->with('global', 'Your account has been deleted!');
}
You should logout user before delete.
You merely gotta do like this:
$user=auth()->user();
$user->delete();

Laravel - Redirect after login

Im a bit of a newbie when it comes to Laravel so i was hoping someone could help out.
Im using the standard authentication and login stuff that ships with Laravel so theres nothing fancy going on, but what i want to do is check in the DB to see if a few fields are completed ( name, address, postcode ) .... If they are, then the user gets redirected to the dashboard, but if they aren't, the user will get redirected to the profile page to fill out the rest of their information.
Im guessing i should put something in my routes.php file in the
Route::post('login', function
part, but how do i check for the fields?
Any help would be greatly appreciated.
Cheers,
Once you have authenticated the user using Auth::check you'll be able to grab the authenticated user with Auth::user.
if (Auth::attempt($credentials))
{
$user = Auth::user();
if ($user->email == '' || $user->address == '')
{
return Redirect::to('user/profile');
}
return Redirect::to('home');
}
You just need to check the fields you want on the user to make sure they are there. If they're not then redirect them to the profile page. If they are redirect them to the home page or somewhere else.
You can also do it this way
if (Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password')))) {
return Redirect::to('users/dashboard');
} else {
return Redirect::to('users/profile');
}
You can use this code
if (Auth::guest())
{
//user is not authenticated or logged in;
return Redirect::to('login');
}else{
//user is authenticated and logged in;
return Redirect::to('profile');
}

Resources