on my profile update form i have fullname password and confirm password fields . currently my validations are works only for
empty fields and password mismatch. but how can i add password charactor limits validations as well ?
password should be min:5 and max 15 charactors.
please advice.
public function changePasswordPost()
{
$user = Auth::user();
if (Input::get('password')) {
if (Input::get('password') !== Input::get('confirm_password')) {
return Redirect::route('admin-change-password')->with('error', 'Password field is not identical to Confirm Password.');
}
$user->update();
return Redirect::route('admin-change-password')->with('success', 'You have successfully updated login details.');
}
return Redirect::route('admin-change-password')->with('error', 'Input Missing');
}
You need to do something like this:
use Validator;
public function changePasswordPost(Request $request)
{
$user = Auth::user();
if ($request->get('password')) {
if (($request->get('password') !== $request->get('confirm_password')) ||
(Validator::make($request->all(), ['password' => 'min:5|max:15'])->fails())) {
return redicrect()->route('admin-change-password')->with('error', 'Password field is not identical to Confirm Password.');
}
$user->update();
return redirect()->route('admin-change-password')->with('success', 'You have successfully updated login details.');
}
return redirect()->route('admin-change-password')->with('error', 'Input Missing');
}
I haven't tested this code but the point is that you need to use Validator class from laravel. Note that I have changed some of the stuff to use laravel-5.1 friendly API.
Note that you can get cleaner code by adding Validation before you do anything. Something like this:
public function changePasswordPost(Request $request)
{
/**
* This basically captures your password matching
* and password length cases in a compact way so
* you don't need all the if statements.
*/
$validation = Validator::make($request->all(),
['password' => 'required|min:5|max:15',
'confirm_password' => 'required|same:password']);
if ($validation->fails())
{
response()->redirect('admin-change-password')->with('error', 'bad input');
}
/**
* Here you do the rest of the processing like updating the database.
*/
}
Related
How to authenticate a user password from a given request in Laravel? How is the password checked against the password hash stored in the database?
**
This is my Controller
**
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class MainController extends Controller
{
function login1(Request $request){
$username = $request->input('username');
$password = $request->input('password');
$data = DB::table('users')->where(['username'=>$username, 'password'=>$password])->first();
if($data == null){
echo "error";
$notification = array(
'message' => 'User Does not Exists!',
'alert-type' => 'error'
);
return back()->with($notification);
}
else{
$request->session()->put('user',$data);
return redirect('dashboard');
}
}}
In basic terms, what you want to do is:
Query the users table for a user, with the given username.
Check whether their hashed password compares the hash of the provided password.
So, you want to first query the table for a user with the given username. Then after retrieving the user, and verifying that they exist, you can then check if the provided password matches the hashed password on the retrieved model.
public function login(Request $request): Response
{
$user = User::where('username', $request->get('username'));
if (!$user || !Hash::check($request->get('password'), $user->password)) {
return back()->with([
'message' => 'Incorrect username and/or password.',
'alert-type' => 'error'
]);
}
$request->session()->put('user', $user);
return redirect('dashboard');
}
However, there is baked in functionality in Laravel for this, and it's probably simpler to do something like this, depending on your needs:
public function login(Request $request): Response
{
if (!Auth::attempt(['username' => $request->get('username'), 'password' => $request->get('password')]) {
return back()->with([
'message' => 'Incorrect username and/or password.',
'alert-type' => 'error'
]);
}
return redirect('dashboard');
}
https://laravel.com/api/8.x/Illuminate/Support/Facades/Auth.html#method_attempt
like this
$encrypted = Crypt::encrypt('password_name_variable');
I want to write a custom authentication on laravel, I want to know should I use default auth or should I write a new?
my auth workflow is:
Step 1- Show email form (in this step we will get just email address)
Step 1-2- check for email existence and if email exists we will go to Step 2 and if not exists I should redirect user to Step 3
Step 2- get the user password (validate password and if everything was OK user will login)
Step 3- show registration form and fill the email with entered user email address (validate form and register user)
What is your solution ?
//Login rules
public function user_login_rules(array $data)
{
$messages = [
'email.required' => 'Please enter your email'
];
$validator = Validator::make($data, [
'email' => 'required'
], $messages);
return $validator;
}
Your post method
public function postSignIn(Request $request)
{
$request_data = $request->all();
$validator = $this->user_login_rules($request_data);
if($validator->fails())
{
return redirect()->back()->withErrors($validator)->withInput();
}
else
{
$email = $request_data['email'];
$user_details = User::where('email', $email)->first();
if(count($user_details) > 0)
{
$credentials = array('email'=> $email ,'password'=> $request_data['password']);
if ($this->auth->attempt($credentials, $request->has('remember')))
{
//Login successful
return redirect()->to('/home');
}
else
{
$error = array('password' => 'Please enter a correct password');
return redirect()->back()->withErrors($error);
}
}
else
{
//Display register page with email
return view('register')->with('email', $email);
}
}
}
i want to add password update option for logged user therefore i used following code
controller auth\authController.php
public function updatePassword()
{
$user = Auth::user();
$rules = array(
'old_password' => 'required',
'password' => 'required|alphaNum|between:6,16|confirmed'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::route('change-password', $user->id)->withErrors($validator);
} else {
if (!Hash::check(Input::get('old_password'), $user->password)) {
return Redirect::route('change-password', $user->id)->withErrors('Your old password does not match');
} else {
$user->password = Input::get('password');
$user->save();
return Redirect::route('change-password', $user->id)->with("message", "Password have been changed");
}
}
}
Routes
Route::post('change-password', 'Auth\AuthController#updatePassword');
Route::get('change-password', 'Auth\AuthController#updatePassword');
im getting following error
FatalErrorException in AuthController.php line 123:
Class 'App\Http\Controllers\Auth\Auth' not found
for this line "$user = Auth::user();"
Your question has hidden answer..I have similar problem like #faz..I have done the trick with his question's code actually
The correct way to achieve this -
protected function postChangePassword(ChangePasswordFormRequest $request){
$user = Auth::user();
$current_password = Input::get('current_password');
$password = bcrypt(Input::get('password'));
$user_count = DB::table('users')->where('id','=',$this->user_id)->count();
if (Hash::check($current_password, $user->password) && $user_count == 1) {
$user->password = $password;
try {
$user->save();
$flag = TRUE;
}
catch(\Exception $e){
$flag = FALSE;
}
if($flag){
return redirect('/u/0/change/password')->with('success',"Password changed successfully.");
}
else{
return redirect('/u/0/change/password')->with("danger","Unable to process request this time. Try again later");
}
}
else{
return redirect('/u/0/change/password')->with("warning","Your current password do not match our record");
}
}
Please note for Hash and Auth, we need to include class at the top and user_id I have get through constructor $this->user_id = Auth::user()->id;. I think I have helped people.
You didn't import Auth class.
add this at the top of the file. after the namespace.
use Illuminate\Support\Facades\Auth;
Its namespace issue, Try :
//if this method is not protected by a middleware for only authenticated users
//verify that user is currently logged in:
if(!$user = \Auth::user()) abort(503); //or return redirect()->route('login')
$rules = array(
'old_password' => 'required',
'password' => 'required|alphaNum|between:6,16|confirmed'
);
Or Add the namespace at the top of your AuthController
use Auth;
class AuthController{
....
}
As i can understand your issue you just use auth namespace of laravel, just write this line at top of your controller file
use Auth;
will solve your problem.
I have a Input validation to change user password, when i tried to submit the form i got always an error that the new password and confirm password are not matched even, this is my post action :
public function doChangePassword()
{
if(Auth::check())
{
$validator = Validator::make(Input::all(), User::$updatePasswordRules);
// if the validator fails, redirect back to the form
if ($validator->fails()) {
return Redirect::to('change-password')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();
} else {
// store
$user = User::find(Auth::user()->id);
if(Auth::user()->password==Input::get('new_password')){
$user->password = Hash::make(Input::get('new_password'));
$user->save();
}
else{
return Redirect::to('change-password')->with('message', 'The password is not correct');
}
// redirect
Session::flash('message', 'Successfully updated password!');
return Redirect::to('login');
}
}
else{
return Redirect::to('login');
}
}
this is my rules :
public static $updatePasswordRules = array(
'password'=>'required|alpha_num|between:6,12',
'new_password'=>'required|alpha_num|between:6,12|confirmed',
'password_confirmation'=>'required|alpha_num|between:6,12'
);
so please if someone has an idea i will be very appreciative
It's because Laravel expects (for your specific case) confirmed field to be named new_password_confirmation
From doc "The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input."
Thus rules should look like (also change input name in form):
public static $updatePasswordRules = array(
'password'=>'required|alpha_num|between:6,12',
'new_password'=>'required|alpha_num|between:6,12|confirmed',
'new_password_confirmation'=>'required|alpha_num|between:6,12'
);
Or you can do it with same validation rule (if don't want to update form inputs):
public static $updatePasswordRules = array(
'password'=>'required|alpha_num|between:6,12',
'new_password'=>'required|alpha_num|between:6,12|same:password_confirmation',
'password_confirmation'=>'required|alpha_num|between:6,12'
);
I need to check if a user has posted the same password as the one in the database. Field for old password is 'oldpass'. The custom validator i created is called 'passcheck'. It should fail or pass accordingly.
My UsersController code below doesnt work. What could have I have done wrong?
$rules = array(
'oldpass' => 'passcheck',
);
$messages = array(
'passcheck' => 'Your old password was incorrect',
);
Validator::extend('passcheck', function($attribute, $value, $parameters)
{
if(!DB::table('users')->where('password', Hash::make(Input::get('oldpass')))->first()){
return false;
}
else{
return true;
};
});
$validator = Validator::make($inputs, $rules, $messages);
You should use something like this,
$user = DB::table('users')->where('username', 'someusername')->first();
if (Hash::check(Input::get('oldpass'), $user->password)) {
// The passwords match...
return true;
}
else {
return false;
}
So, you have to get the record using username or any other field and then check the password.
#lucasmichot offered even shorter solution:
Validator::extend('passcheck', function ($attribute, $value, $parameters)
{
return Hash::check($value, Auth::user()->getAuthPassword());
});
I would make it like this:
/**
* Rule is to be defined like this:
*
* 'passcheck:users,password,id,1' - Means password is taken from users table, user is searched by field id equal to 1
*/
Validator::extend('passcheck', function ($attribute, $value, $parameters) {
$user = DB::table($parameters[0])->where($parameters[2], $parameters[3])->first([$parameters[1]]);
if (Hash::check($value, $user->{$parameters[1]})) {
return true;
} else {
return false;
}
});
This validator rule will make database query to check current user's password
You can make it even shorter and save query:
Validator::extend('passcheck', function ($attribute, $value, $parameters) {
return Hash::check($value, Auth::user()->getAuthPassword());
});
Please dont tie your rule to an Html element. Use the parameters Laravel provides to create your custom rules. This would be (asuming that you have a user authenticated):
Validator::extend('passcheck', function($attribute, $value, $parameters) {
return Hash::check($value, Auth::user()->password); // Works for any form!
});
$messages = array(
'passcheck' => 'Your old password was incorrect',
);
$validator = Validator::make(Input::all(), [
'oldpass' => 'passcheck',
// more rules ...
], $messages);