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'
);
Related
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 am new to laravel.I have a controller called userController to mangae user in my application.Here i have a user authentication and profile system.It will send the user to its own profile after login.Sometimes user may wish to search for a random username or id field in the url to search for a user.If desired user is found ,their profile info will be shown in the profile section.But if no user is found i want my application to get the current logged in user and show his/her info instead.How i can do that?
if my user name is 'zim' i can write the url mydomain/user/zim ,it will get my profile,But if i search an invalid name say 'zi' mydomain/user/zi , i want my application to return mydomain/user/zim again
All i can manage here is to show a flash message if no user is found.Can't figure out how to retrieve the current logged user.Tried to use the Request class but seems not working
loginUser function():
public function loginUser(Request $request){
$data = $request->all();
$rules = array(
'name' => 'required',
'password'=>'required'
);
// Create a new validator instance.
$validator = Validator::make($data, $rules);
if($validator->fails()){
$errors=$validator->messages();
return redirect()->back()->withErrors($validator);
}else{
if(Auth::attempt(['name'=>$request['name'],'password'=>$request['password']])){
return redirect()->route('user.show',[$request['name']]);
}else{
return redirect()->back()->with('data', 'wrong username or password');
}
}
}
show() method in userController:
public function show($user,Request $request) // tried with Request but failed
{
//
$indicator=is_numeric($user)?'id':'name';
$info=userModel::where($indicator,'=',$user)->get()->first();
if($info){
return View::make('user.show')->with('user',$info);
}else{
session()->flash('message','no user');
return View::make('user.show');
}
}
You just need to change your show method slightly.
public function show($user,Request $request)
{
$indicator=is_numeric($user)?'id':'name';
$info=userModel::where($indicator,'=',$user)->get()->first();
if(empty($info)){
return View::make('user.show')->with('user',$info);
}else{
session()->flash('message','no user but here is your info :)');
return View::make('user.show')->with('user', Auth::user());
}
}
Edited for better logic.
public function show($username)
{
$info = userModel::where(username, $username)->get()->first();
if($info != null){
return View::make('user.show')->with('user', $info);
}
else{
session()->flash('message','No user found! But here is your info!');
return View::make('user.show')->with('user',Auth::user());
}
}
Here is a much simplified option. (Always allow the URL to collect only one type instead of checking if its id or username)
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.
*/
}
Working with Laravel 5 I'm facing an issue to where it routes to auth/login by default. When you login, it redirects to login causing an error. When I'm able to actually use http://localhost/login it actually routes to home like it should. Anything new that would be causing it behave like this?
HomeController shown below:
<?php namespace app\Http\Controllers;
class HomeController extends Controller {
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard to the user.
*
* #return Response
*/
public function index()
{
return view('home');
}
public function showLogin()
{
// show the form
return view('login');
}
public function doLogin()
{
// validate the info, create rules for the inputs
$rules = array(
'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 the validator fails, redirect back to the form
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
} else {
// create our user data for the authentication
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($userdata)) {
// validation successful!
// redirect them to the secure section or whatever
// return Redirect::to('secure');
// for now we'll just echo success (even though echoing in a controller is bad)
echo 'SUCCESS!';
} else {
// validation not successful, send back to form
return Redirect::to('login');
}
}
}
public function doLogout()
{
Auth::logout(); // log the user out of our application
return Redirect::to('login'); // redirect the user to the login screen
}
}
I figured it out to be that constructor.
public function __construct()
{
$this->middleware('auth');
}
I removed that and changed the view to 'auth/login' and it works like a charm.
So I have this code:
public function postLogin() {
// validate the info, create rules for the inputs
$rules = array(
'username' => 'required', // 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 the validator fails, redirect back to the form
if ($validator->fails()) {
return Redirect::route('login')
->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
} else {
$remember = (Input::has('remember')) ? true : false;
// create our user data for the authentication
$userdata = (array(
'username' => Input::get('username'),
'password' => Input::get('password')
), $remember);
// attempt to do the login
if (Auth::attempt($userdata)) {
// validation successful!
// redirect them to the secure section or whatever
// return Redirect::to('secure');
// for now we'll just echo success (even though echoing in a controller is bad)
echo 'SUCCESS!';
} else {
// validation not successful, send back to form
return Redirect::route('login')
->with('global', 'Incorrect username or password. Please try again.');
}
}
}
When it runs I get: syntax error, unexpected ','. Basically it isn't expecting the $remember to be passed there. Where is it meant to be? I've tried putting it here: Auth::attempt($userdate), $remember) { } but that didn't work either. It had the same error. Not sure what's going on. Any help would be appreciated.
You can use Auth::viaRemember() in your Authcontroller, to check if a user was already logged:
if (Auth::check() || Auth::viaRemember()) {...
And change your login-check as follows:
//Assuming, the remember-input is a checkbox and its value is 'on'
if (Auth::attempt($userData, (Input::get('remember') == 'on') ? true : false)) {...