Laravel 4 Auth wrong username or email error - php

i want to give the user a visual feedback if they entered wrong login information.
public function doLogin()
{
$rules = array(
'email' => 'required|email',
'password' => 'required|min:3'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::route('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($userdata)) {
return Redirect::route('dashhome')
->withJsd('true');
} else {
return Redirect::route('login')
->withErrors(['wrongpw','Wrong E-mail address or Password']);
}
}
}
and on my login view i have this code
#if ($errors->has('wrongpw'))
<script>
$.gritter.add({
title: 'Ups!',
text: "{{ $errors->first('wrongpw') }}",
class_name: 'warning',
time: ''
});
</script>
#endif
But that doesn't work. Any idea what i make wrong or any suggestions on how to do it better?
Thanks

i think you are not passing errors in a correct associative array,
try
->withErrors(array('wrongpw' => 'Wrong E-mail address or Password'));
or
->withErrors(['wrongpw' => 'Wrong E-mail address or Password']);

Related

Laravel "Wrong password" error message

I'm creating a login function in Laravel 5.4 and I want to show error message in the view when the password is incorrect. Also I have a custom message for account approval so it makes things a bit difficult for me. Meanwhile I put those messages together but is not very user-friendly. How can I separate them?
This is my controller:
public function login(Request $request)
{
// validate the form data
$this->validate($request, [
'email' => 'required|email|exists:users,email',
'password' => 'required|min:6'
]);
// attempt to log
if (Auth::attempt(['approve' => '1', 'email' => $request->email, 'password' => $request->password ], $request->remember)) {
// if successful -> redirect forward
return redirect()->intended(route('user.overview'));
}
// if unsuccessful -> redirect back
return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors([
'approve' => 'Wrong password or this account not approved yet.',
]);
}
As result i want to replace Wrong password or this account not approved yet with two separate messages:
If password is wrong to show: Password is wrong
If account not approved show: This account not approved yet
You can pass custom error messages for each validation rule, you can do this:
public function login(Request $request)
{
//Error messages
$messages = [
"email.required" => "Email is required",
"email.email" => "Email is not valid",
"email.exists" => "Email doesn't exists",
"password.required" => "Password is required",
"password.min" => "Password must be at least 6 characters"
];
// validate the form data
$validator = Validator::make($request->all(), [
'email' => 'required|email|exists:users,email',
'password' => 'required|min:6'
], $messages);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
} else {
// attempt to log
if (Auth::attempt(['approve' => '1', 'email' => $request->email, 'password' => $request->password ], $request->remember)) {
// if successful -> redirect forward
return redirect()->intended(route('user.overview'));
}
// if unsuccessful -> redirect back
return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors([
'approve' => 'Wrong password or this account not approved yet.',
]);
}
}
Before this, you have to include Validator class:
use Illuminate\Support\Facades\Validator;
Without writing a new custom login method we can easily handle a custom wrong password message with the Auth default login process.
Open LoginController from the location: app/Http/Controllers/Auth/
Include the Request class if not exit on top of the controller
use Illuminate\Http\Request;
Finally add below line of codes at the very bottom of your LoginController to process the response error with custom message
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => trans('auth.failed')];
// Load user from database
$user = \App\User::where($this->username(), $request->{$this->username()})->first();
if ($user && !\Hash::check($request->password, $user->password)) {
$errors = ['password' => 'Wrong password'];
}
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
You can use like this:
return Redirect::back()->withInput(Input::all());
If you're using Form Request Validation, this is exactly how Laravel will redirect you back with errors and the given input.
Excerpt from \Illuminate\Foundation\Validation\ValidatesRequests:
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())
->withErrors($errors, $this->errorBag());
Controller:
public function login(Request $request)
{
// validate the form data
$this->validate($request, [
'email' => 'required|email|exists:users,email',
'password' => 'required|min:6'
]);
// attempt to log
if (Auth::attempt(['approve' => '1', 'email' => $request->email, 'password' => $request->password ], $request->remember)) {
// if successful -> redirect forward
return redirect()->intended(route('user.overview'));
}
// if unsuccessful -> redirect back
return Redirect::back()
->withInput()
->withErrors(
[
'password' => 'Wrong Password',
],
[
'approve' => 'Account not approved',
],
);
}

Auth not working in other module laravel 4 creolab

hi i create a project in hmvc architecture with creolab module in laravel 4 here
let say i divided my project into 3 module like example there
--module--
auth
shop
content
the scenario here user must login in auth modul first
after that they be able to access 2 module left (Shop & content)
when i try to auth protecting route in module shop or content like this example
Authenticating Group */
Route::group(array('before' => 'auth'), function() {
Route::get('shop', array(
'as' => 'shop',
'uses' => 'App\Modules\Shop\Controllers\ShopController#getShop'
));
});
i can't access it although i already success login in modul Auth
i already confirm it i success login with return string like this
i think the problem is here
in my module account, my accountController contain script like this
public function postLogin() {
$validator = Validator::make(Input::all(), array(
'username' => 'required',
'password' => 'required'
));
if($validator->fails()) {
return Redirect::route('login.post')
->withErrors($validator);
} else {
$auth = Auth::attempt(array(
'username' => Input::get('username'),
'password' => Input::get('password')
));
if($auth) {
return "login success";
// return Redirect::intended('shop');
}
else {
return Redirect::route('login')
->with('global', 'Email or Password Not Match');
}
}
}
when i return simple string (disable redirect) i got login successin screen that indicate i already success login, but when i active redirect to another module, i got push back to login page
i check auth state with this simple script in login page like this
#if (Auth::check())
{{ login }}
#else
{{ "not login "}}
#endif
and got not login text
can someone help me?
#update
public function postLogin() {
$validator = Validator::make(Input::all(), array(
'username' => 'required',
'password' => 'required'
));
if($validator->fails()) {
return Redirect::route('login.post')
->withErrors($validator);
} else {
$auth = Auth::attempt(array(
'username' => Input::get('username'),
'password' => Input::get('password')
));
if($auth) {
return Redirect::intended('shop');
}
else {
return Redirect::route('login')
->with('global', 'Email or Password Not Match');
}
}
}
#2nd Update
route in shop module
<?php
/* Authenticating Group */
Route::group(array('before' => 'auth'), function() {
Route::get('shop', array(
'as' => 'shop',
'uses' => 'App\Modules\Shop\Controllers\ShopController#getShop'
));
Route::post('shop', array(
'as' => 'shop.post',
'uses' => 'App\Modules\Shop\Controllers\ShopController#postShop'
));
Route::post('shop-delete', array(
'as' => 'shop.delete',
'uses' => 'App\Modules\Shop\Controllers\ShopController#postShopDelete'
));
});
#update my authentication filters.php
/*
|--------------------------------------------------------------------------
| Authentication Filters
|--------------------------------------------------------------------------
|
| The following filters are used to verify that the user of the current
| session is logged into this application. The "basic" filter easily
| integrates HTTP Basic authentication for quick, simple checking.
|
*/
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
});
Try this if it works.
if(Auth::attempt(['usernae' => Input::get('username'), 'password' => Input::get('password')]))
{
return 'login success';
}else{
return 'login failed';
}

Wrong Laravel validation messasges

I get the wrong error messages. My purpose is following :
1. checking username / pw combination, and if it doesn't match, "wrong username/pw combination" error through validator.
2. captcha (mews) is troubling me. Even user enters true captcha chars (no case-sensitive by config) I get the error message.
Here is my validator :
FYI: i have a table "user" instead of users, and i can use it nicely in other controllers.
protected function loginValidator()
{
$message = array(
'exists:user,username' => 'Wrong username/pass combination',
'exists' => 'Wrong :attribute.',
'required' => ':attribute cannot be empty',
'captcha' => 'Wrong captcha'
);
return Validator::make(Input::all(),[
'usernameInput' => 'required|exists:user,username',
'passwordInput' => 'required',
'captchaInput' => 'captcha|required'
], $message);
}
Even if username/pass combination is true, i get wrong captcha message.
Thanks in advance.
protected function loginValidator()
{
$validator = Validator::make(
array(
'name' => 'Dayle',
'password' => 'lamepassword',
'email' => 'email#example.com'
),
array(
'name' => 'required',
'password' => 'required|min:8',
'email' => 'required|email|unique:users'
)
);
if ($validator->fails())
{
// The given data did not pass validation
$data['messages'] = $validator->messages()->all();
}
else
{
//complete validation
}
return View::make('home.login', $data);
}

Laravel update password passes validation but doesn't update record

Hi I am using Laravel and I am using a couple of packages for user auth and roles which are Zizaco Confide and I want to update the users password firstly they should input there current password a new password and confirm the password and they should match. Now the validation works but the users password isn't updated in the database. My code is below:
public function updatePassword($id) {
$rules = array(
'now_password' => 'required',
'password' => 'min:5|confirmed|different:now_password',
'password_confirmation' => 'required_with:password|min:5'
);
//password update.
$now_password = Input::get('now_password');
$password = Input::get('password');
$passwordconf = Input::get('password_confirmation');
$validator = Validator::make(Input::only('now_password', 'password', 'password_confirmation'), $rules);
if ($validator->fails()) {
return Redirect::back()->withErrors($validator);
}
elseif (Hash::check($now_password, Auth::user()->password)) {
$user = User::find($id);
$user->password = Hash::make($password);
$user->save();
return Redirect::back()->with('success', true)->with('message','User updated.');
} else {
return Redirect::back()->withErrors('Password incorrect');
}
}
Any ideas why the users password is not isn't updated using this block of code
$user = User::find($id);
$user->password = Hash::make($password);
$user->save();
User Model
<?php
use Zizaco\Confide\ConfideUser;
use Zizaco\Confide\ConfideUserInterface;
use Zizaco\Entrust\HasRole;
class User extends Eloquent implements ConfideUserInterface
{
use SoftDeletingTrait;
use ConfideUser;
use HasRole;
protected $softDelete = true;
public function favourites()
{
return $this->hasMany('Favourite');
}
}
To check inputted password:
1.
$now_password = Input::get('now_password');
$user = DB::table('users')->where('name', Auth::user()->name)->first();
if(Hash::check($now_password, $user->password)){
//Your update here
}
2.
$now_password = Input::get('now_password');
if(Hash::check($now_password, Auth::user()->password)){
//Your update here
}
To check if they match and if the new password is different than old.
$rules = array(
'now_password' => 'required|min:8',
'password' => 'required|min:8|confirmed|different:now_password',
'password_confirmation' => 'required|min:8',
);
And edit your form to (or enter your names):
{{ Form::label('now_password', 'Old Password') }}
{{ Form::password('now_password')}}
{{ Form::label('password', 'New Password') }}
{{ Form::password('password')}}
{{ Form::label('password_confirmation', 'Confrim New Password') }}
{{ Form::password('password_confirmation')}}
Update
Ok, so you don't want to edit only passwords.
Edit your rules:
$rules = array(
'now_password' => 'required|min:5',
'password' => 'min:5|confirmed|different:now_password',
'password_confirmation' => 'required_with:password|min:5'
);
I think that current password should be required in every type of change. Other inputs imo shouldn't be required, because you don't know which data user want to edit.
You should also add to your rules something like:
'username' => alpha_num|unique:users,username
etc.. (for more see http://laravel.com/docs/4.2/validation#available-validation-rules)
If Validator pass, you should check which data user want to change (which inputs are not empty).
Something like:
if(!empty(Input::get('firstname'))){
$user->firstname = Input::get('firstname');
}
etc...with every input.
Try it like this:
public function updatePassword($id)
{
$user = User::findOrFail($id);
User::$rules['now_password'] = 'required';
// other rules here
$validator = Validator::make($data = Input::all(), User::rules('update', $id));
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
array_forget($data, 'password_confirmation');
array_forget($data, 'now_password');
$data['password'] = Hash::make($data['password']);
$user->update($data);
return Redirect::back()->with('success', true)->with('message','User updated.');
}
remember your password confirmation field name must be "password_confirmation" if you used first way...
if you used another name for password confirm field you can use second way.
$this->validate($request, [
'email' => 'required|unique:user|email|max:255',
'username' => 'required|max:20',
'password' => 'required|min:3|confirmed',
'password_confirmation' => 'required',
'gender' => 'required|in:m,f',
]);
$this->validate($request, [
'email' => 'required|unique:user|email|max:255',
'username' => 'required|max:20',
'password' => 'required|min:3',
'confirm_password' => 'same:password',
'gender' => 'required|in:m,f',
]);
public function change_password_post($id)
{
$rules = array(
'current' => 'required|string|min:8',
'new' => 'required|string|min:8',
'confirm' => 'required|same:new'
);
$validator = Validator::make(Input::only('current', 'new', 'confirm'), $rules);
if($validator->fails())
{
return Redirect::back()
->withErrors($validator);
}
else
{
$users = User::where('id', '=', $id)->first();
if (Hash::check(Input::get('current'), $users->password))
{
if(Input::get('new') == Input::get('confirm'))
{
$users->password =Hash::make(Input::get('new'));
$users->save();
$msg = array('msg' => 'Password changed Successfully');
return Redirect::back()
->withErrors($msg);
}
else
{
$msg = array('msg' => 'New password and Confirm password did not match');
return Redirect::back()
->withErrors($msg);
}
}
else
{
$msg = array('msg' => 'Current password is incorrect');
return Redirect::back()
->withErrors($msg);
}
}
}

Laravel sign in (Auth::attempt) not working

Hi there I have problem with Laravel. I can't sign in. I tried everything what I found online. Maybe somebody have any idea where I made mistake. Create new user and send email work fine. Sign in I don't know work like loop come back to view no errors or any messages. I work with debug mode in laravel but it wasn't show any errors.
<?php
class AccountController extends BaseController {
//Sign in function start
public function getSignIn(){
return View::make('account.signin');
}
public function postSignIn(){
$validator = Validator::make(Input::all(),
array(
'email' => 'required|email',
'username' => 'required'
)
);
if($validator->fails()){
return Redirect::route('account-sign-in')
->withErrors($validator)
->withInput();
}else{
if($auth = Auth::attempt(array(
'email' => Input::get('email'),
'password' => Input::get('password'),
'active' => 1
), true)){
return Redirect::to('/');
}else{
return Redirect::route('account-sign-in')
->with('global', 'Email/password wrong or account not activated');
}
}
return Redirect::route('account-sign-in')
->with('global', 'There was a problem signing you in');
}
//Sign in function end
//Create new account function start
public function getCreate(){
return View::make('account.create');
}
public function postCreate(){
$validator = Validator::make(Input::all(),
array(
'email' => 'required|max:50|email|unique:users',
'username' => 'required|max:20|min:3|unique:users',
'password' => 'required|min:6',
'password_again' => 'required|same:password'
)
);
if($validator->fails()){
return Redirect::route('account-create')
->withErrors($validator)
->withInput();
}else{
$email = Input::get('email');
$username = Input::get('username');
$password = Input::get('password');
//Activation code
$code = str_random(60);
$user = User::create(array(
'email' => $email,
'username' => $username,
'password' => Hash::make($password),
'code' => $code,
'active' => 0
));
if($user){
//Send link function start
Mail::send('emails.auth.active', array(
'link' => URL::route('account-active', $code),
'username' => $username),function($message) use ($user){$message->to($user->email, $user->username)->subject('Activation your account');});
//Send link function end
return Redirect::route('home')
->with('global', 'Your account has been created! We have sent you an email with activation link');
}
}
}
public function getActivate($code){
$user = User::where('code', '=', $code)->where('active', '=', 0);
if($user->count()){
$user = $user->first();
//Update user to active state
$user->active = 1;
$user->code ='';
if($user->save()){
return Redirect::route('home')
->with('global', 'Activated! You can now sign in!');
}
}
return Redirect::route('home')
->with('global', 'We could not activate your account. Please try again later.');
}
//Create new account function end
}
?>
In postSignIn() validator you specify that username is required when from what i can see from your logic and error messages, you need the user to specify an email and a password to login. Instead try:
$validator = Validator::make(Input::all(),
array(
'email' => 'required|email',
'password' => 'required'
)
);
When submitting the login form with email and password, the validator always fails since there is no username input

Categories