Laravel - Confide - Save Change Password - php

I managed to save a new password or change a password for a logged in user.
public function saveNewPassword() {
$rules = array(
'old_password' => 'required',
'password' => 'required|confirmed|different:old_password',
'password_confirmation' => 'required|different:old_password|same:password_confirmation'
);
$user = User::findOrFail(Auth::user()->id);
// Validate the inputs
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withInput();
} else {
$password = Input::get( 'password' );
$passwordConfirmation = Input::get( 'password_confirmation' );
if(!empty($password)) {
if($password === $passwordConfirmation) {
$user->password = $password;
$user->password_confirmation = $passwordConfirmation;
}
} else {
unset($user->password);
unset($user->password_confirmation);
}
// Save if valid. Password field will be hashed before save
$user->save();
}
// Get validation errors (see Ardent package)
$error = $user->errors()->all();
if(empty($error)) {
Session::flash('message', 'Successfully saved!');
return Redirect::back();
} else {
Session::flash('error', $error);
return Redirect::back();
}
}
The problem I have is, how to check the Old Password, that is equal to the current password? Any Ideas? Does Confide has his own methods for changing passwords?

I use this sollution for changing the password. In your rules you have one error: password_confirmation should be the same as password not password_confirmation.
Here is the complete and tested function:
public function changePassword($id){
$rules = array(
'old_password' => 'required',
'new_password' => 'required|confirmed|different:old_password',
'new_password_confirmation' => 'required|different:old_password|same:new_password'
);
$user = User::find(Auth::user()->id);
$validator = Validator::make(Input::all(), $rules);
//Is the input valid? new_password confirmed and meets requirements
if ($validator->fails()) {
Session::flash('validationErrors', $validator->messages());
return Redirect::back()->withInput();
}
//Is the old password correct?
if(!Hash::check(Input::get('old_password'), $user->password)){
return Redirect::back()->withInput()->withError('Password is not correct.');
}
//Set new password to user
$user->password = Input::get('new_password');
$user->password_confirmation = Input::get('new_password_confirmation');
$user->touch();
$save = $user->save();
return Redirect::to('logout')->withMessage('Password has been changed.');
}
This also works if you dont work with Confide.

From the github of confide:
Integrated with the Laravel Auth and Reminders component/configs.
So I would guess using the Auth::validate() method will do the trick.

Related

How can I decrypt password to login in laravel?

While changing the password I am using this function
public function passwordChange(Request $request, $userId)
{
$user = User::find($userId);
$user->password = Crypt::encrypt(Input::get('password'));
$user->save();
return redirect('my-profile');
}
So in my mongoDb database password insert in encrypted form, So whenever I have to login in system at that time how can I compare my password with password of database
public function authenticate(Request $request)
{
$rules = array(
'company_email' => 'required|email|exists:users,company_email',
'password' => 'required|string|max:20|min:4',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return view('pages.login')->with('v_errors', $validator->errors()->messages());
}
else
{
//get email and query
$authenticateMe = $request->only('company_email', 'password');
$user = User::where($authenticateMe)->first();
if (empty($user))
{
return view('pages.login')->with('not_exists', 'true');
}
//session set
// Session::put('key', $user->username, $user->file);
Session::put('key', ['username' => $user->username, 'email' => $user->company_email, 'userId' => $user->id, 'profilePicture' => $user->file]);
return redirect('my-profile');
}
}
I am not using php artisan make:auth
will anyone please help??
Instead of encrypting the password, use hashing. Laravel has its own documentation about how to use that: https://laravel.com/docs/5.8/hashing
Simply you can not decrypt an encrypted password but you can check user credentials by adding an array of user email & password to Auth::attempt() function Here is a link to the description: https://laravel.com/docs/5.8/authentication#authenticating-users?
Here is your function using Auth::attempt():
public function authenticate(Request $request)
{
$rules = array(
'company_email' => 'required|email|exists:users,company_email',
'password' => 'required|string|max:20|min:4',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return view('pages.login')->with('v_errors', $validator->errors()->messages());
}
else
{
//get email and query
$authenticateMe = $request->only('company_email', 'password');
if (Auth::attempt($authenticateMe)) {
$user = User::find(Auth::user()->id);
//session set
// Session::put('key', $user->username, $user->file);
Session::put('key', ['username' => $user->username, 'email' => $user->company_email, 'userId' => $user->id, 'profilePicture' => $user->file]);
return redirect('my-profile');
}else{
return view('pages.login')->with('not_exists', 'true');
}
}
}
And do not forget to add use Auth; to the function controller

Logout user from all browser when password is reset in laravel 5.6

When the user changes their password, they get Logged Out from the browser. However, if they are logged into another browser at the same time they stay logged in on the other browser.
I want to log out the user from all browsers they are logged into when they reset their password.
Here login controller.
function checklogin(Request $request)
{
$this->validate($request, ['email' => 'required|email', 'password' => 'required|string|min:3']);
$user_data = array(
'email' => $request->get('email') ,
'password' => $request->get('password')
);
$remember_me = $request->has('remember') ? true : false;
if (Auth::attempt($user_data, $remember_me))
{
return redirect()->intended('dashboard');
}
else
{
return back()->with('error', 'Wrong Login Details');
}
}
send mail function as below
function sendEmail(Request $request)
{
$this->validate($request, ['email' => 'required|exists:users']);
$email = $request->email;
$name = User::where('email', $email)->first();
$name = $name->name;
$token = Password::getRepository()->createNewToken();
$link = url("password/reset?email=$email&token=$token");
$value = Password_resets::where('email', $email)->first();
if (isset($value))
{
Password_resets::where('email', $email)->update(['email' => $email, 'token' => $token]);
}
else
{
Password_resets::insert(['email' => $email, 'token' => $token]);
}
Mail::to($email)->send(new \App\Mail\ResetPassword($link, $name));
return redirect()->back()->with('success', 'Please check your Email for Password Reset');
}
password reset function as below
function resetpasswordchange(Request $request)
{
$passwordtoken = $request->input('passwordtoken');
$email = $request->input('email');
$user_password = $request->input('user_password');
$users['user'] = Password_resets::where('token', $passwordtoken)->where('email', $email)->get();
if (empty($users['user'][0]))
{
$settoken = '0';
}
else
{
$settoken = $users['user'][0]->token;
}
if (($settoken) == $passwordtoken)
{
$update = array(
'password' => bcrypt($user_password) ,
);
User::where('email', $email)->update($update);
/* Auth::logout();
auth()->logoutOtherDevices(bcrypt($user_password),'password');*/
return redirect()->route('login')->with('success', 'Password has been Updated.');
}
else
{
return redirect()->back()->with('error', 'Token & Email Not Match!.');
}
}
How I can logout the user from all browsers who they are logged already ?
Open App\Http\Kernel and inside the protected $middlewareGroups property uncomment the \Illuminate\Session\Middleware\AuthenticateSession::class middleware. This compares the password hash of the user to see if the session is valid or not.

Perform User Authentication if email provided exists in the database

In Laravel, is it possible to do a sign-in base on user email only - no password needed.
I'ved tried
public function postSignIn(){
$validator = Validator::make(Input::only('email') , array(
'email' => 'required',
));
if ($validator->fails()) {
return Redirect::to('/')->with('error', 'Please fill out your information ')->withErrors($validator)->withInput();
}
$email = strtolower(Input::get('email'));
$auth = Auth::attempt(array('email' => $email ));
if ($auth) {
return Redirect::to('/dashboard')->with('success', 'Hi '. Auth::user()->name .'! You have been successfully logged in.');
}
else {
return Redirect::to('/')->with('error', 'Username/Password Wrong')
->with('username', $username)
->withErrors($validator);
}
I keep getting : Undefined index: password
Do I need to modify the any kind of Auth driver for this to work ?
Any hints/ suggestions on this will be much appreciated !
You can do something like this:
public function postSignIn(){
$validator = Validator::make(Input::only('email') , array(
'email' => 'required',
));
if ($validator->fails()) {
return Redirect::to('/')->with('error', 'Please fill out your information ')->withErrors($validator)->withInput();
}
$email = strtolower(Input::get('email'));
try{
$user = User::where('email', $email)->firstOrFail();
Auth::login($user);
return Redirect::to('/dashboard')->with('success', 'Hi '. Auth::user()->name .'! You have been successfully logged in.');
}
catch(ModelNotFoundException $exception){
return Redirect::to('/')->with('error', 'Username/Password Wrong')
->with('username', $username)
->withErrors($validator);
}
}
You can check more info in here on how to manually login your users (you will have to scroll down a little bit)

update profile password laravel 5

I am working in laravel 5.1 and my update profile was working but will not encrypted and not working now.
When I try to update the user table will also password_confirmation field and causes a conflict in the database. I do not understand.
In the form says successfully but the database does not update any
Code
public function updatePassword() {
$passwordData = Input::except('_token');
$validation = Validator::make($passwordData, User::$passwordData);
if ($validation->passes()) {
array_forget($passwordData,'password_confirmation');
User::where(array(
'password' => Hash::make(Input::get('password'))
));
Session::flash('password', 'Perfil editado com sucesso');
return Redirect::to('backend/perfil/password');
} else {
return Redirect::to('backend/perfil/password')->withInput()->withErrors($validation);
}
}
user
public static $passwordData = array(
'password' => 'required|confirmed',
'password_confirmation' => 'required'
);
Follow this simple steps to get rid of anything
Step 1 : Get the password from the form
$PasswordData = Input::all();
Step 2 : Validate your password
Validator::extend('pwdvalidation', function($field, $value, $parameters) {
return Hash::check($value, Auth::user()->password);
});
Step 3 : Define the validation rule in your User Model
public static $rulespwd = array('OldPassword' => 'required|pwdvalidation',
'NewPassword' => 'required|confirmed|alphaNum|min:5|max:10',
'NewPassword_confirmation' => 'required',
);
Note : You shall define your own rule according to your need
Step 4 : If the rule is passed, then update else throw error messages to your view
$validator = Validator::make($PasswordData, User::$rulespwd, $messages);
if ($validator->passes()) {
$user = User::find(Auth::user()->id);
$user->password = Input::get('NewPassword');
$user->save();
return Redirect::to(Session::get('urlpath') . '/changepassword')->withInput()->with('Messages', 'The Password Information was Updated');
} else {
return Redirect::to(Session::get('urlpath') . '/changepassword')->withInput()->withErrors($validator);
}

Unexpected T Variable Laravel

I'm getting an error on the following on:
$user->email = Input::get('email');
I'm really unsure what is wrong with the code, it seems perfectly fine. I looked up t variable errors, simply involve missing a bracket or semi colon. But as far as I'm aware it seems fine.
If anyone could help me out, that would be great.
If there is any other code, could you list it as a comment and i'll happily add it.
Thanks!
public function doRegister()
{
$rules = array(
'name' => 'required|min:3', // name
'email' => 'required|email', // make sure the email is an actual email
'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()){
// validation not successful, send back to form
Redirect::back()->withErrors;
} else {
$user = Input::all();
User::addNewUser();
if (Auth::attempt($user)) {
return Redirect::to('member');
}
}
}
User model
public static function addNewUser()
{
$user = new User;
$user->name     = Input::get('name');
$user->email    = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
}
It's because of $user->save; it's a method not a property and it should be called like
$user->save();
Instead of
$user->save;
Update : Also, it's U not u
$user = new user;
should be
$user = new User; // capital U
Also, after if ($validator->fails())
Redirect::back()->withErrors;
should be
return Redirect::back()->withErrors($validator);
Update : So, after fixing 3 errors (so far), your full code should be
public function doRegister()
{
$rules = array(
'name' => 'required|min:3',
'email' => 'required|email',
'password' => 'required|alphaNum|min:3'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()){
return Redirect::back()->withErrors($validator);
}
else {
$user = new User;
$user->name =Input::get('name');
$user->email= Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
if (Auth::attempt($user)) {
return Redirect::to('member');
}
}
}

Categories