Suppose I am logged in as admin group, then when I access main_page, there is an 'Export' button. But if I am in members group, it will not be showed up.
Recently, I was thinking to use if logic in views. Is it right? Or I still have to use logic on controller?
You can check user type in controller and pass it to view
Controller
if ($this->ion_auth->is_admin())
{
$this->data['user_type'] = 'admin';
}
else if($this->ion_auth->logged_in()){
$this->data['user_type'] = 'member';
}
Now you can use same variable in view to process your data. Yes you have to write ternary operator/if condition to check
View
($user_type == 'admin') ? 'statment_code_here' : 'statment_code_here';
In case of multiple conditions check in view, you can use if else statements.
Related
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.
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');
}
}
I have a User model. The User Model is related to the Role model such that each and every user can have only 1 role assigned to a user. One of the role is a Vendor role. In order to check that the current user is a vendor I do something like this
protected function isVendor()
{
$roles = Role::where('role_slug', 'vendor')->get();
if(isset($roles) && $roles->count() > 0)
return true;
return false;
}
and I use the following code from my blade to state that the current user is a vendor and perform some more actions (like displaying some more panels)
<p>{!! Auth::user()->isVendor !!}</p>
However I keep getting this error
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
Would you know why this is happening ?
Thanks
First of all, your method is protected, which means you can not call it like this. Change it to public.
Second, you are trying to access the function like propery, so Eloquent is trying to resolve a relationship, instead if calling your function. So the correct way to call your function is:
<p>{!! Auth::user()->isVendor() !!}</p>
I made an application where there are two controllers (user and home). The user controller performs actions such as registering a user and logging them in/out, while the home controller is used to perform actions once the user is authenticated.
I found this answer on SO: What is the best practice for restricting specific pages to logged in users only in Codeigniter?
But I saw that the verifying of a session value is performed in a separate, custom controller. I was wondering why that's necessary?
In my home controller, I have a function that checks to see whether a session value for an item is set to true and allow the user the functionality provided in the home controller, otherwise redirect them back to the user controllers index method which loads the login view. This function is called in the constructor of the home controller like so:
public function __construct()
{
parent::__construct();
$this->is_loggedIn();
}
public function is_loggedIn()
{
$check_login = $this->session->userdata('isLoggedIn');
if(!isset($check_login) || $check_login != 1)
{
redirect('user');
}
}
This works great; the user is not allowed access to pages/functions within the home controller unless they are authenticated.
However, this isn't the case for functions within my user controller. If I login and then logout, I can still access a function within the user controller i.e. localhost/sitename/user/register even though I've logged out and shouldn't be able to access such functions. They should redirect to the login page (user controllers index method) instead, but instead allow the user to carry on using the functions in the user controller.
I tried including the above is_loggedin() function inside the user controller to check whether the users session is valid and call the function from the user controllers constructor, but I ended up with a redirect loop (rightfully so).
So I was wondering how it would be possible to disallow access to the user controllers functions when the user is not authenticated.
Another way I've thought of is to include the is_loggedin() function in each of the functions within the user controller, but I was wondering if there was a cleaner way to do this. For now this is my temporary fix. Please let me know if there is a more OOP friendly way
You should only check if the session === FALSE.
public function __construct()
{
parent::__construct();
$this->is_loggedIn();
}
public function is_loggedIn()
{
$check_login = $this->session->userdata('isLoggedIn');
if($check_login === FALSE)
{
redirect('user');
}
}
Be sure to delete isLoggedIn when the user logs out.
$this->session->unset_userdata('isLoggedIn');
I'm using the MVC PHP framework Codeigniter and I have a straight forward question about where to call redirect() from: Controller or Model?
Scenario:
A user navigates to www.example.com/item/555. In my Model I search the item database for an item with the ID of 555. If I find the item, I'll return the result to my controller. However, if an item is not found, I want to redirect the user somewhere. Should this call to redirect() come from inside the model or the controller? Why?
No your model should return false and you should check in your controller like so:
class SampleModel extends Model
{
//Construct
public function FetchItem($id)
{
$result = $this->db->select("*")->from("table")->where("item_id",$id)->get();
if($result->num_rows() == 0)
{
return false;
}
//return result
}
}
and within your controller do:
function item($id)
{
$Item = $this->SampleModel->FetchItem($id);
if(!$Item)
{
redirect("class/error/no_item");
}
}
Models are for data only either return a standard result such as an key/value object or a boolean.
all logic should be handled / controlled by the Controller.
Models are not page specific, and are used globally throughout the whole application, so if another class / method uses the model, it might get redirect to the incorrect location as its a different part of your site.
It seems like the controller would be the best place to invoke your redirect because the controller typically delegates calls to the model, view, or in your case, another controller.
However, you should use whatever makes the most sense for your application and for what will be easier to maintain in the future, but also consider that rules do exist for a reason.
In short, if a coworker were to try to fix a bug in your code, what would the "reasonable person" standard say? Where would most of them be most likely to look for your redirect?
Plus, you said you're returning the result to your controller already... perhaps that's where you should make your redirect...