authentication from two table using laravel - 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.

Related

How can I validate the request user in Laravel?

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'
]);
}
}
}

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 can I get the value of my role using this query

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.

Pass user id in laravel after logged in

I would like to pass / submit the user_id of the currently logged on user. How will I do it in laravel 5.2? Please need help
I am not sure on my code on how will I use Auth:user() blah blah. Need help with this. I am new to this.
You can use the login functionality like this and pass the datas to the required pages as per your wish.
public function Dologin()
{
// create our user data for the authentication
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
);
if (Auth::attempt($userdata))
{
$user_id=Auth::user()->user_id;// user_id it will change as per the users table in your project.
return redirect('index');
}
else
{
}
}
Make sure you save your password using bcrypt method and for that alone the Auth::check() and Auth::user() will work.
auth()->id() will provide the user id

Hash::check() return false in laravel 5

I'm just starting with laravel 5, I'm doing a simple login function to check if email and password passed by user matches with the email and password stored in the database. I've been reading the documentation ([https://laravel.com/docs/5.0/hashing1) but Hash::check($content['password'], $user->{'password'}) returns false always. My code looks like this.
When I create a new user I hash the password like that:
$content = json_decode($request->getContent(), true);
$user -> password = Hash::make($content['email']);
And my login function looks like that:
public function login(Request $request)
{
$content = json_decode($request -> getContent(), true);
$user = DB::table('users')->where('email', $content['email'])->first();
if (Hash::check($content['password'], $user->{'password'}))
{
// Redirect to dashboard
}
}
Thanks in advance!!
Actually you are hashing the email instead of password while creating the user. change the code from
$user->password = Hash::make($content['email']);
To
$user->password = Hash::make($content['password']);
i came up with same issue. check database users table, password field. make the size of the field to 60 or more. this fixed mine.
The facade Hash just will encrypt your data:
Hash::make('123456');
is the same that:
$password = bcrypt('123456');
to login a user you need to use AuthController functions:
Auth::attempt(['email' => 'test#test.com' , 'password' => Hash::make('password')]);
it's a example.
If you're receiving a request, you can add this method to login:
if(Auth::attempt(['email' => $request->email, 'password' => $request->password , 'active' => 1])){
flash()->success('Successfully logged in!');
return redirect('/');
}
the attempt function will hash your password field and will compare with database data.

Resources