How can I get the value of my role using this query - session

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.

Related

authentication from two table using laravel

I am new in laravel, I trying to make custom validation from two tables,
i have table users (contain id,email, password,job_type) and
another table name employee with fields user_id,admin_type_id,
my problem is when I trying to check data with login user and confirm he is an employee with job_tybe =1 in table Employee and conform is type is admin by admin_type_id =1 when I make var_dump($admin) i get output is null
I found my problem is password registers in database not password that send from a form
how can I make password is I dental to make login
condition of login is job_tybe =1+ admin_type_id =1
this is my code:-
public function authenticate(Request $request)
{
$credentials = array(
'email' => $request->get('email'),
'password' => $request->get('password'),
);
//check user is employee
$admin=User::where(['email' => $credentials['email'],'password' =>Hash::make($credentials['password']) ,'deleted'=>1,'status'=>1,'job_type'=>1])->first();
//get admin type
$adminType=Employee::where(['id_user' => $admin->id, 'admin_type_id'=>1,'deleted'=>1,'status'=>1])->first();;
if($adminType !=null)
{
if (Auth::attempt($credentials)) {
return redirect()->route('brand.create');
exit();
}
return redirect()->back()->with("messageError","Invalid Email Or Password");
}
To make password use "bcrypt('password')" method.

ID and connection

In my administrator panel, I have 2 Roles, admin and former:
For now, I have 3 users:
the first role is admin, the pseudo is admin and email address is admin#gmail.com
the second role is former, it has like pseudo Remace and email address is test#gmail.com
the third user is always a former, it has like pseudo Gofette and email address is ledeluge1990#gmail.com
For information, the administrator is the only one to create records.
Here, I have 2 recordings: (It's the informations of the formers)
Now, my goal is that each former has access to his informations.
So, the first former is Remace with email adresse test#gmail.com.
I log in with email adresse of Remace ( test#gmail.com )
I see this :
In fact, I retrieve the informations of Gofette and not those of Remace, why ???
Now, I want to connect with the user Gofette with email adresse ledeluge1990#gmail.com...
I see nothing ???
I think my problem is in my function index() ????
public function index()
{
if($has_role = auth()->user()->hasRole('admin')){
$garages = Garage::oldest()->paginate(5);
return view('admin.garages.index', compact('garages'));
} else{
$garages = Garage::where('id', Auth::user()->id)->paginate(5);
return view('admin.garages.index', compact('garages'));
}
}
public function create()
{
$localites = Localite::all();
return view('admin.garages.create', compact('localites', 'garages'));
}
public function store(Request $request)
{
$request->validate([
'nom' => 'required|string|max:25|min:3|alpha',
'adresse' => 'required|string|max:50|min:12',
'fk_localite' => 'required',
'telephone' => 'required|string|min:8|max:11',
'email' => 'required|email|max:25|min:10'
]);
$exists = Garage::where('nom', $request->get('nom'))->where('adresse', $request->get('adresse'))->where('fk_localite', $request->get('fk_localite'))->where('telephone', $request->get('telephone'))->where('email', $request->get('email'))->count();
if (!$exists){
Garage::create($request->all());
return redirect()->route('garages.index')
->with('success', 'Un nouvel enregistrement a été effectué');
}
else{
return redirect()->route('garages.index')
->with('error', 'Doublon, cet enregistrement existe déjà! ');
}
}
Thanks a lot for your help.
As stated by the comment above your $garages = Garage::where('id', Auth::user()->id)->paginate(5);. It's searching for Garage records with an id matching the user's id.
To solve this problem, you can :
Change the query to : $garages = Garage::where('email', Auth::user()->email)->paginate(5);
Or create another user_id field in garages table to assign each of the former to their garages.

Edit user profile for logged in user(codeigniter)

Help guys, is there any solution how to edit profile for logged in user, my code makes a change to all row, not a spesific row. it doesn't change only logged in user but for all user(row). So any idea?
here is my controller:
public function updateData(){
$param['first_name'] = $this->input->post('first_name');
$param['last_name'] = $this->input->post('last_name');
$param['email'] = $this->input->post('email');
$this->Model_members->updateData($param);
$data['title'] = "Passion";
$data['subtitle'] = "Synergize people";
$data['description'] = "Synergize people";
$data['view_isi2'] = "profile1";
$this->load->view('layouts/templates',$data);
}}
and this is my model:
public function updateData($param){
$field = array(
'first_name' => $param['first_name'],
'last_name' => $param['last_name'],
'email' => $param['email']
);
$this->db->update('users',$field);
$this->db->where('id',$this->session->userdata('$id'));
return 1;
}
very appreciate for the help!
You need to use $this->db->where() before $this->db->update()
why?:
because $this->db->update() runs the query, the next line is only a beginning trunck of sql query, which is not executed, therefor all rows are updated.

redirect to admin and user based on user role in code igniter

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" )

How to redirect to a specific url

I have the following code:
public function numbergrouppost() {
$groupname = Input::get('groupname');
$no_of_members = Input::get('no_of_members');
$create = Group::create([
'group_name' => $groupname,
'no_of_members' => $no_of_members,
'user_id' => Auth::id()]);
return Redirect::route('grouppage');
The question is how do I redirect to the page that contains group_id (primary key) within the url. In other words I want to redirect to a url that looks like this:
'/grouppage/{id}'
I could create a function within my home controller but how would I access the $groupname variable(code below)? Or would it be best to query the most recent group created by the user?
public function groupname() {
$groupbutton = Group::where('user_id', Auth::id())->where('group_name', $groupname)->first();
return View::make('grouppage');
Route:
Route::get('/grouppage/{id}', array( 'as' => 'grouppage', 'uses' => 'HomeController#groupname'));
Assuming $groupId is id of the group, you can pass variable on route like this :
return Redirect::route('grouppage', ['id' => $groupId]);
Then, in your groupname function you can retrieve the id :
public function groupname($id) {
// get group by id
$groupbutton = Group::where('user_id', Auth::id())->where('id', $id)->first();
// pass the gruoupbutton to the view
return View::make('grouppage', ['groupbutton' => $groupbutton]);
}
You can redirect to your route by passing parameters. For example if your group id is 10, you can try something below.
return Redirect::route('grouppage', array(10));
in your case group_id can be retrieved using $create->group_id.
return Redirect::route('grouppage', array($create->group_id));
Please refer to http://laravel.com/docs/4.2/responses#redirects.

Resources