update profile password laravel 5 - php

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

Related

Laravel Routing returns blank page

to make it a bit short. I just made a registration form fully working with a controller, the routes and the view. Now I know it's common sense to use a Model for it and in the controller only call the method in the model. So i thought okay lets fix that. Now when I register an account I get a blank page. I bet the redirect is going wrong but I can't fix it maybe you can?
RegisterController.php
public function doRegister(){
$user = new User();
$user->doRegister();
}
User.php (model)
public function doRegister()
{
// process the form here
// create the validation rules ------------------------
$rules = array(
'username' => 'required|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|min:5',
'serial_key' => 'required|exists:serial_keys,serial_key|unique:users'
);
// create custom validation messages ------------------
$messages = array(
'required' => 'The :attribute is important.',
'email' => 'The :attribute is not a legit e-mail.',
'unique' => 'The :attribute is already taken!'
);
// do the validation ----------------------------------
// validate against the inputs from our form
$validator = Validator::make(Input::all(), $rules);
// check if the validator failed -----------------------
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
// redirect our user back to the form with the errors from the validator
return Redirect::to('/register')
->withErrors($validator)
->withInput(Input::except('password', 'password_confirm'));
} else {
// validation successful ---------------------------
// our duck has passed all tests!
// let him enter the database
// create the data for our duck
$duck = new User;
$duck->username = Input::get('username');
$duck->email = Input::get('email');
$duck->password = Hash::make(Input::get('password'));
$duck->serial_key = Input::get('serial_key');
// save our user
$duck->save();
// redirect with username ----------------------------------------
return Redirect::to('/registered')->withInput(Input::old('username'));
}
}
you need to make $user->doRegister(); a return statement
in your RegisterController you have to do
public function doRegister(){
$user = new User();
return $user->doRegister();
}
try this
return Redirect::to('/registered')
->with('bill_no', Input::get('username'));
in the '/registered' controller,..
use this
$username = Session::get("username");
above worked for me,...

Rule for Checking Old Password and New Password

I am checking for Old Password and New Password with Confirmation Password.
Here i want to check with whether OldPassword and New Password should not be same.
How can i do this ?
Here is my Rule :
public static $rulespwd = array('OldPassword' => 'required|pwdvalidation',
'NewPassword' => 'required|confirmed|min:1|max:10',
'NewPassword_confirmation' => 'required',
);
Here is my controller code for the validation :
$PasswordData = Input::all();
Validator::extend('pwdvalidation', function($field, $value, $parameters)
{
return Hash::check($value, Auth::user()->password);
});
$messages = array('pwdvalidation' => 'The Old Password is Incorrect');
$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('changepassword')->with('Messages', 'The Password Information was Updated');
}
Note : I am using model for validation rule.. How can i do this in model ??
Just use the different validation rule - as described in the Laravel docs
public static $rulespwd = array('OldPassword' => 'required|pwdvalidation',
'NewPassword' => 'required|confirmed|min:6|max:50|different:OldPassword',
'NewPassword_confirmation' => 'required',
);
Also - why are you limiting a password to 10 chars? That is silly - there is no reason to limit it at all. All your are doing is reducing your application security.

Laravel - Confide - Save Change Password

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.

how to check if a user email already exist

In laravel, when a new user is registering to my site and the email they use already exist in the database. how can tell the user that the email already exist ?. I am new to laravel framework. A sample code would be nice too.
The validation feature built into Laravel lets you check lots of things, including if a value already exists in the database. Here's an overly simplified version of what you need. In reality you'd probably want to redirect back to the view with the form and show some error messages.
// Get the value from the form
$input['email'] = Input::get('email');
// Must not already exist in the `email` column of `users` table
$rules = array('email' => 'unique:users,email');
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
echo 'That email address is already registered. You sure you don\'t have an account?';
}
else {
// Register the new user or whatever.
}
);
Laravel has built-in human readable error messages for all its validation. You can get an array of the these messages via: $validator->messages();
You can learn more about validation and what all you can do with it in the Laravel Docs.
Basic Usage Of Unique Rule
'email' => 'unique:users'
Specifying A Custom Column Name
'email' => 'unique:users,email_address'
Forcing A Unique Rule To Ignore A Given ID
'email' => 'unique:users,email_address,10'
Adding Additional Where Clauses
You may also specify more conditions that will be added as "where" clauses to the query:
'email' => 'unique:users,email_address,NULL,id,account_id,1'
The above is from the documentation of Laravel
You could add:
public static $rules = [
'email' => 'unique:users,email'
];
You can add more rules to the $rules like:
public static $rules = [
'email' => 'required|unique:users,email'
];
It will automatically produce the error messages
and add:
public static function isValid($data)
{
$validation = Validator::make($data, static::$rules);
if ($validation->passes())
{
return true;
}
static::$errors = $validation->messages();
return false;
}
to the model User.php
Then in the function you're using to register, you could add:
if ( ! User::isValid(Input::all()))
{
return Redirect::back()->withInput()->withErrors(User::$errors);
}
if(sizeof(Users::where('email','=',Input::get('email'))->get()) > 0) return 'Error : User email exists';
The great resource is only Laravel Documentation #
enter link description here
I also did like below when integrating user management system
$user = Input::get('username');
$email = Input::get('email');
$validator = Validator::make(
array(
'username' => $user,
'email' => $email
),
array(
'username' => 'required',
'email' => 'required|email|unique:users'
)
);
if ($validator->fails())
{
// The given data did not pass validation
echo 'invalid credentials;';
// we can also return same page and then displaying in Bootstap Warning Well
}
else {
// Register the new user or whatever.
$user = new User;
$user->email = Input::get('email');
$user->username = Input::get('username');
$user->password = Hash::make(Input::get('password'));
$user->save();
$theEmail = Input::get('email');
// passing data to thanks view
return View::make('thanks')->With('displayEmail', $theEmail);
}
public function userSignup(Request $request, User $data){
# check user if match with database user
$users = User::where('email', $request->email)->get();
# check if email is more than 1
if(sizeof($users) > 0){
# tell user not to duplicate same email
$msg = 'This user already signed up !';
Session::flash('userExistError', $msg);
return back();
}
// create new files
$data = new User;
$data->name = $request->name;
$data->email = $request->email;
$data->password = md5($request->password);
$data->save();
//return back
Session::flash('status', 'Thanks, you have successfully signup');
Session::flash('name', $request->name);
# after every logic redirect back
return back();
}
I think when u try something like this you earn a smooth check using Model
We can use the Validator.
In your Controller.
$validator = $request->validate([
'name' => 'required',
'phone' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required',
]);
In View
#error('email') <span class="text-danger error">{{ $message }}</span>#enderror
$this->validate($request, [
'fname' => 'required',
'lname' => 'required',
'email' => 'required|min:4|email|unique:users',
'password' => 'required',
]);
Try This

Check for active user state with laravel

This is pretty standard login function and validation that works nicely. But I also want to check that the user is active. I have set up a column in my users table with 'active' set to either 0 or 1.
public function post_login()
{
$input = Input::all();
$rules = array(
'email' => 'required|email',
'password' => 'required',
);
$validation = Validator::make($input, $rules);
if ($validation->fails())
{
return Redirect::to_route('login_user')
->with_errors($validation->errors)->with_input();
}
$credentials = array(
'username' => $input['email'],
'password' => $input['password'],
);
if (Auth::attempt($credentials))
{
// Set remember me cookie if the user checks the box
$remember = Input::get('remember');
if ( !empty($remember) )
{
Auth::login(Auth::user()->id, true);
}
return Redirect::home();
} else {
return Redirect::to_route('login_user')
->with('login_errors', true);
}
}
I've tried something like this already:
$is_active = Auth::user()->active;
if (!$is_active == 1)
{
echo "Account not activated";
}
But this can only be used within the 'auth attempt' if statement and at that point the users credentials(email and pass) are already validated. So even if the users account if not active at this point they are already logged in.
I need a way to return validation to let them know they still need to activate their account and check if their account is set at the same time their email and pass are being checked.
Filters are the way to go. It's easy and clean to solve this problem, see my example below.
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
else
{
// If the user is not active any more, immidiately log out.
if(Auth::check() && !Auth::user()->active)
{
Auth::logout();
return Redirect::to('/');
}
}
});
Can't you use something like this:
if (Auth::once($credentials))
{
if(!Auth::user()->active) {
Auth::logout();
echo "Account not activated";
}
}
Just make the active field one of the confirmations. You can do this:
$credentials = array(
'username' => $input['email'],
'password' => $input['password'],
'active' => 1
);
if (Auth::attempt($credentials))
{
// User is active and password was correct
}
If you want to specifically tell the user they are not active - you can follow it up with this:
if (Auth::validate(['username' => $input['email'], 'password' => $input['password'], 'active' => 0]))
{
return echo ('you are not active');
}
A better solution might be to create an Auth driver that extends the Eloquent Auth driver already in use and then override the attempt method.
Then change your auth config to use your driver.
Something like:
<?php
class Myauth extends Laravel\Auth\Drivers\Eloquent {
/**
* Attempt to log a user into the application.
*
* #param array $arguments
* #return void
*/
public function attempt($arguments = array())
{
$user = $this->model()->where(function($query) use($arguments)
{
$username = Config::get('auth.username');
$query->where($username, '=', $arguments['username']);
foreach(array_except($arguments, array('username', 'password', 'remember')) as $column => $val)
{
$query->where($column, '=', $val);
}
})->first();
// If the credentials match what is in the database we will just
// log the user into the application and remember them if asked.
$password = $arguments['password'];
$password_field = Config::get('auth.password', 'password');
if ( ! is_null($user) and Hash::check($password, $user->{$password_field}))
{
if ($user->active){
return $this->login($user->get_key(), array_get($arguments, 'remember'));
} else {
Session::flash('authentication', array('message' => 'You must activate your account before you can log in'));
}
}
return false;
}
}
?>
In your login screen, check for Session::get('authentication') and handle accordingly.
Alternatively, allow them to log in but don't let them access any pages other than one that offers a link to resend the activation email.
This is what I do:
if (\Auth::attempt(['EmailWork' => $credentials['EmailWork'], 'password' => $credentials['Password']], $request->has('remember'))) {
if (\Auth::once(['EmailWork' => $credentials['EmailWork'], 'password' => $credentials['Password']])) {
if (!\Auth::user()->FlagActive == 'Active') {
\Auth::logout();
return redirect($this->loginPath())
->withInput($request->only('EmailWork', 'RememberToken'))
->withErrors([
'Active' => 'You are not activated!',
]);
}
}
return redirect('/');
}
return redirect($this->loginPath())
->withInput($request->only('EmailWork', 'RememberToken'))
->withErrors([
'EmailWork' => $this->getFailedLoginMessage(),
]);

Categories