How can disable the password filed ? ( laravel ) - laravel

I've system don't required the password input just one input
when I login , so I created this:
public function do_login()
{
if (auth()->attempt(['user_id' => request('user_id')])) {
return redirect('home');
} else {
session()->flash('erorr', trans('Your Id Incorrect'));
return redirect('/')->withInput();
}
} //ends of do_login
and this is the error appears to me >
image

You can't use Auth's attempt without a password.
Since you're letting anyone in with just the ID, all you need is:
auth()->loginUsingId(request('user_id'))
You may want to look up the ID in your database first, or loginUsingId should throw an exception you can try/catch for.
If user_id doesn't correspond to the id column of your users table, you may need a slightly different approach:
$user = User::where('user_id', request('user_id'))->first();
auth()->login($user);

Related

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

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.

Trying to get property of non-object on codeigniter when check data

I would like to show data from database with "where" condition, how to show data in controller, the error show is "Trying to get property of non-object"
here is my controller :
$checkpassword = $this->m_user->checkpassword($oldpassword);
if($this->input->post('oldpassword') != $checkpassword->password)
{
$data['inputerror'][] = 'oldpassword';
$data['error_string'][] = 'your old password is wrong';
$data['status'] = FALSE;
}
and here is my model :
function checkpassword($oldpassword)
{
$this->db->where('password',$oldpassword);
return $this->db->get($this->table)->row();
}
When you perform row() or result() (any type of result object) and you get no results e.g. empty array or stdClass object you cannot access any of the properties because it is empty. That is why it is critical to build in num_rows().
function checkpassword($oldpassword)
{
$this->db->where('password',$oldpassword);
$query = $this->db->get($this->table)
if ($query->num_rows() > 0) {
return $query->row();
} else {
return null;
}
}
Usage:
if (is_null($checkpassword) || $this->input->post('oldpassword') != $checkpassword->password) { ... }
Now I have two problems with your code:
It appears that you are storing plaintext passwords (a big no no)
You check the password on the basis of the entire user table as per a comment you stated above but it is still possible that two users have the same password and thus you should also include a $this->db->where('username', $this->input->post('username')) in you check password function.
Given these two remarks it seems like your understanding of authentication systems is rather rudimentary (I don't mean to say this to be rude), and maybe you should consider using a pre-built plugin like Ion Auth, I use it myself and can recommend it.

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 handle data before delete from model in Laravel?

I have the following method:
public function destroy($id)
{
$id = \JWTAuth::parseToken()->authenticate();
$offer = Offer::findOrFail($id);
$offer->delete();
return response()->json(["offer" => $offer]);
}
How handle data before deleting? I need to check if user has permit to delete data or not
When you use the authenticate() method, the user model is retrieved so it means the id you have is not an id but a User. Have you checked the documentation of JWT Because first and foremost you have to retrieve the user and this is sufficient:
$user = \JWTAuth::parseToken()->authenticate();
Then if you have a field for example in your users table to tell if the user have the right say admin which can be 1 or 0 then you can do the following:
if($user->admin == 1)
{
$offer = Offer::findOrFail(1); //say id
$offer->delete();
return response()->json(["offer" => $offer]);
}
return response()->json(['error' => 'you dont have the right to delete this'], 403);
Just a little scratch on the idea, but my best advice is to do some searches on how JWT is implemented, I am pretty sure you will find tons of them online.
I would recommend using the Model's delete event:
https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L1122
and handle it.
This will guarantee that if you use the delete method on a model, you always check permissions.

Retrieve password stored in db

I created user profile for my application. In this user profile, user can update their information just like email address, password, position, company name .. etc. If user want to change one of their information, user need to provide current password. And I will verify current password user provided is correct or not. Error is I can't verify the current password user provided. Below is the part of my user controller codes.
if($request['current_pwd'])
{
if($request['new_pwd'])
{
if($user->password == bcrypt($request['current_pwd']))
{
$user->password = bcrypt($request['new_pwd']);
}else{
return redirect()->back()->with(['message' => 'Wrong current password !']);
}
}elseif($user->password == bcrypt($request['current_pwd']))
{
$user->save();
}else{
return redirect()->back()->with(['message' => 'Wrong Current Password ! Check Again!']);
}
}else{
return redirect()->back()->with(['message' => 'Please enter your current password !']);
}
if the user want to change their current password, user must enter current password, new password, . If current password is equal the password stored in db, the new password will be update. If not, return with messages.
try this
first include Hash namespace in your controller,
use Illuminate\Support\Facades\Hash;
and use the following condition to make sure the current password is entered is valid
if($request->has('current_password')){
$current_password = $request->input('current_password');
if(!Hash::check($current_password,Auth::user()->password)){
return redirect()->back()->withInput()->withErrors([
'current_password' => 'You current password doesnot match with the logined user\'s !'
]);
}
}
You should match the encrypted "current password" entry with the password the user already has. You can get the user's password by using the function Auth::user()
So your condition would be:
if(bcrypt($request['current_pwd']) == Auth::user()) {
// Do password change
} else {
// Invalid password error
}
There is another function: getAuthPassword() which you can use by specifying the user ID, like so:
$user = User::find('1');
$user->getAuthPassword();
This will get the password for user ID 1
Due to salting! this kind of $user->password == bcrypt($request['current_pwd'] checking will not work!
Try making hash of same password you will get different hash!
So Check like this in laravel 5.2
$crypt = new Hashing\BcryptHasher();
$match = $crypt->check($user->password, $request['current_pwd']);

Resources