I am new in CI hmvc and i am using CI generate_crud() method like below :
public function index()
{
$crud = $this->generate_crud('users');
$crud->columns('groups', 'username', 'email', 'first_name', 'last_name', 'company', 'no_employee', 'active');
$this->unset_crud_fields('ip_address', 'last_login');
// only webmaster and admin can change member groups
if ($crud->getState()=='list' || $this->ion_auth->in_group(array('webmaster', 'admin')))
{
$crud->set_relation_n_n('groups', 'users_groups', 'groups', 'user_id', 'group_id', 'name');
}
// only webmaster and admin can reset user password
if ($this->ion_auth->in_group(array('webmaster', 'admin')))
{
$crud->add_action('Reset Password', '', 'admin/user/reset_password', 'fa fa-repeat');
$crud->add_action('Edit', '', 'admin/user/edit_user', 'edit-icon');
}
// disable direct create / delete Frontend User
$crud->unset_add();
$this->mPageTitle = 'Users';
$this->render_crud();
}
This returns me the list of all active and inactive users but i want only active users in list. How can i modify my code with so that i can get list of only active users.
You need to set the condition for the active = true
$crud->where('active',true);
This will only return the active columns.
Related
I am sending a update request like:
Route::put('user/{user}/edit-user-education', 'UpdateUserEducationController#editUserEducation');
My controller is :
class UpdateUserEducationController extends Controller
{
public function editUserEducation(UserEducation $education, User $user, EditUserEducationRequest $request)
{
$education->school = $request->school;
$education->degree = $request->degree;
$education->user_id = $user->id; // here to validate
$education->save();
return response()->json([
'message' => 'Education Updated'
]);
}
}
Now how I can validate the request user_id with the user_id already in inserted in DB ? I want to ensure that the only user can update the record who created that one.
How to do so ? Thanks in advance
Check out the docs on validation here:
https://laravel.com/docs/8.x/validation
Specifically, I think you want the exists rule:
https://laravel.com/docs/8.x/validation#rule-exists
The quick and dirty way is to add your validation in the controller but there are some better methods as explained in the docs. I usually opt for Form Requests, which it looks like you've already done as your request is an instance of EditUserEducationRequest.
In the controller you can add:
$validated = $EditUserEducationRequest->validate([
'user_id' => 'required|exists:users',
]);
I assume your user table is called users.
You could alternatively state the exists validation rule for user_id in the rules array of your Form Request as per the docs.
EDIT:
I actually missed a requirement in your original post that is that the user sending the request must be the same user as the one being updated.
That can be handled in the the authorize method of your form request with something like:
public function authorize()
{
return $this->user()->id == $this->user_id;
}
Simply make a check that current user is the same user who is trying to update record.
class UpdateUserEducationController extends Controller
{
public function editUserEducation(UserEducation $education, User $user, EditUserEducationRequest $request)
{
if($user->id==Auth::user()->id){
$education->school = $request->school;
$education->degree = $request->degree;
$education->user_id = $user->id; // here to validate
$education->save();
return response()->json([
'message' => 'Education Updated'
]);
}
else{
return response()->json([
'error' => 'Invalid User'
]);
}
}
}
I created a yii\base\DynamicModel in controller and I have one form with attributes from this model. I need access these attributes after submitting form in controller.
controller.php
public function actionCreate()
{
$model = new DynamicModel([
'name', 'age', 'city'
]);
if($model->load(Yii::$app->request->post())){
$model->age = $model->age + 5;
/*
* code....
* */
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
But $model->age, $model->name etc. returns nothing.
I could only access the attribute this way: Yii::$app->request->get('DynamicModel')['age']
What is the correct way to access these attributes?
You need to configure validation rules in order to automatically load attributes by load():
$model = new DynamicModel(['name', 'age', 'city']);
$model->addRule(['name', 'age', 'city'], 'safe');
if ($model->load(Yii::$app->request->post())) {
// ...
Using safe will accept values as is without actual validation, but you may consider adding real validation rules to ensure correct state of your model.
I have this method in my DocumentsController and am trying to implement some simple permissions system, in that a user that is not an admin must have been assigned a branch and a department before adding, editing or deleting a Document.
Here is the code for the method
/**
* Check the credentials of the user that is not an admin
* to add, modify a document
*/
private function checkCredentials() {
$user = auth()->user();
// dd((!is_admin() && !$user->branch_id && !$user->department_id));
if (!is_admin() && !$user->branch_id && !$user->department_id) {
// dd(redirect()->route('documents'));
return redirect()->route('documents')->with([
'class' => 'alert-danger',
'message' => 'Ask your administrator to assign you a branch and department first',
]);
}
}
And here is how am calling it in one of my controller methods that mapped to the route Route::get('/documents/add', ['as' => 'documents.add', 'uses' => 'DocumentsController#create',]);
public function create()
{
$this->checkCredentials();
...
return view('main/documents/create', $data);
}
Problem is the redirection is not working as it continues to display the form, even when the user has not yet been assigned a branch or department, that is when both the branch_id and department_id are both equal to null.
What could be the reason for this? Thank you.
You are not returning the redirect from the controller, try this:
/**
* Check the credentials of the user that is not an admin
* to add, modify a document
*/
private function checkCredentials() {
$user = auth()->user();
// dd((!is_admin() && !$user->branch_id && !$user->department_id));
if (!is_admin() && !$user->branch_id && !$user->department_id) {
// dd(redirect()->route('documents'));
return false;
}
}
public function create()
{
if(!$this->checkCredentials()) {
return redirect()->route('documents')->with([
'class' => 'alert-danger',
'message' => 'Ask your administrator to assign you a branch and department first',
]);
}
...
return view('main/documents/create', $data);
}
I think you use authorization (gate/policy). https://laravel.com/docs/5.8/authorization
Your code need to be
<?php
private function checkCredentials() {
$user = auth()->user();
if (!is_admin() && !$user->branch_id && !$user->department_id) {
return redirect()->route('documents.add')->with([
'class' => 'alert-danger',
'message' => 'Ask your administrator to assign you a branch and department first',
]);
}
}
public function create()
{
$this->checkCredentials();
//...
return view('main/documents/create', compact('data'));
}
If the admin is logging in. I want him to go to admin/dashboard. otherwise to the users dashboard. The controller of login is follow. In the users table, I have a column of 'role' and the value are '1' and '2'. 1 stands for admin and 2 for user. and there is separate table for role.
Login User function
public function login(){
$data['title'] = 'Login';
//validating form
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() ===FALSE){
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}else{
//Get username
$username = $this->input->post('username');
//Get password in md5
$password= md5($this->input->post('password'));
//Login User.... passing username and password
$user_id = $this->user_model->login($username, $password);
//checking userid
if($user_id){
//creating session if user_id is present
$user_data=array(
'user_id'=>$user_id,
'username'=>$username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//set message
$this->session->set_flashdata('user_loggedin', 'Login successful');
redirect('posts');
}else{
//creating session if user_id is not present
$this->session->set_flashdata('login_failed', ' Invalid credentials');
redirect('users/login');
}
}
}
while validating the user, you have to send an array as a response to login call.
$user_info = $this->user_model->login($username, $password); // User Info should be an Array $user_info = array('user_id' => '123', 'role' => '1'); if exist and $user_info = array(); if not
if(isset($user_info['user_id']) && !empty($user_info['user_id'])) {
$user_data=array(
'user_id'=>$user_info['user_id'],
'username'=>$username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
$this->session->set_flashdata('user_loggedin', 'Login successful');
if($user_info['role'] == 1){
redirect('admin/dashboard');
} else {
redirect('user/dashboard');
}
}
Sure this will help you.
I don't know exactly the column name what you set for user role. Say this is user_role_id and here is my example for you.
//checking userid
if($user_id){
//creating session if user_id is present
$user_data=array(
'user_id'=>$user_id, // you should change this variable to $user_id['id']
'username'=>$username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//set message
$this->session->set_flashdata('user_loggedin', 'Login successful');
if($user_id['user_role_id'] == 1){
redirect('admin/dashboard', 'refresh');
}
else if($user_id['user_role_id'] == 2){
redirect('users/dashboard', 'refresh');
}
}else{
//creating session if user_id is not present
$this->session->set_flashdata('login_failed', ' Invalid credentials');
redirect('users/login');
}
The main developer of the contemporary CodeIgniter , Mr Lonnie Ezell
in this post on the CodeIgniter's forum,
https://forum.codeigniter.com/thread-67063-post-339924.html#pid339924
explains the use of CodeIgniter filters
http://codeigniter.com/user_guide/incoming/filters.html
Please , pay attention to and kindly note the example he does
Thinking about who writes the post...
you have the correct CodeIgniter's approach for the users and admins accessibility delimitations
So let's create your filter in /App/Filters by copying the skeleton you find in the documentation #
https://codeigniter.com/user_guide/incoming/filters.html#creating-a-filter
e.g. save it as /App/Filters/AccessFilter.php
customize the name according with your needs and fill the before method with your is-logged-in check and redirect action if not logged in
then go to the Filters configuration setup in /App/Config/Filters.php and
assign your brand new created filter an alias name
'accessCheck' => \App\Filters\AccessFilter::class
select the policy that best fits your need, e.g. the bottom one in the Filters.php config file and note the provided hint that comes with the default CodeIgniter installation it tells
/* List filter aliases and any before/after uri patterns that they should run on, like: 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']], */
well so let's use it
public $filters = [
'accessCheck' => ['before' => ['controllerName(/*)?']]
];
where controllerName is the controller you want to deny access if the user is not logged in
please note that you can deny multiple controllers as array and also note that the regex condition will stop the access to every method of the controller including the index() one
so it will stop both
site_url("/controllerName")
site_url("/controllerName/*")
Bonus:
Also note that filters can be set in the custom routes strings as parameters
https://codeigniter.com/user_guide/incoming/routing.html#applying-filters
( this selective use, will allow to e.g. avoid already logged in users to access the login page or the sign up page and other similar "deviations" )
I am having an error... I don't know how to fix this...
I am doing something that will set page privileges to admin employee and other roles.
But suddenly I doesn't get the value of my variable role.
public function login(Request $req)
{
$username=$req->input('email');
$password=$req->input('password');
$breadcrumb = 'Dashboard';
$pageTitle = 'CollabUX | Dashboard';
$prepath ='../';
$currentURL = Req::url();
$user = DB::table('add_users')->where(['username'=>$username,'password'=>$password])->get();
if(count($user)>0){
session(['isloggedin' => 'true']);
session(['roles' => $user->role]);
return View::make('dashboard')->with(
array('breadcrumb' => $breadcrumb,'pageTitle' => $pageTitle,'currentURL' => $currentURL,'prepath' => $prepath));
}
else{
//redirect page
$data = array(
'error' => 1,
'remarks' => 'Invalid Username/Password. Please try again.'
);
return View::make('login')->with('data', $data);
}
}
Well, there are two solutions.
You can define a user in code as admin
or you can create a separate table
userroles (id, title)
then you have to check with your requirements.
if only one user can have only role
then add userrole_id in users table and update accordingly.
if one user can have multiple roles
then create a separate table
users_to_userroles (id, user_id, userrole_id)
and it will be a pivot table.