I'm making my login system, through the LoginController controller, which in turn calls a request called loginRequest [I still have to update some names to Pascal]
My request only has two rules that username and password are required.
Then in a function getCredentials() I capture the username of this and validate that it is an email or not, this to give the user the option to log in both ways.
To identify if the user is actually an email, create a method 'isMail' in which I establish $factory with the content validated through an alias set to Validacion\Factory , ValidationFactory, but when executing the submit button it throws me the error :
Target [Illuminate\contracts\Validation\Factory] is not instantiable.
Could you help me?
template [login.blade.php]:
#extends('components\header')
<section class="vh-100">
<div class="container-fluid h-custom">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-4">
<img src="{{ URL::asset('img/logo.png') }}"
class="img-fluid" height="500">
</div>
<div class="col-md-8 col-lg-6 col-xl-4 offset-xl-1">
<form action="{{route('samein.login')}}" method="POST">
#csrf
<!-- Email input -->
<div class="form-outline mb-4">
<input type="text" name="username" class="form-control form-control-lg"
placeholder="Usuario" />
<label class="form-label" for="form3Example3">Usuario</label>
</div>
<!-- Password input -->
<div class="form-outline mb-3">
<input type="password" name="password" class="form-control form-control-lg"
placeholder="Contraseña" />
<label class="form-label" for="form3Example4">Contraseña</label>
</div>
<div class="text-rigth text-lg-start mt-4 pt-2">
<button type="submit" class="btn btn-primary btn-lg"
style="padding-left: 2.5rem; padding-right: 2.5rem;">Iniciar Sesión</button>
</div>
</form>
</div>
</div>
</div>
</section>
controller[LoginController.login]
<?php
namespace App\Http\Controllers;
use App\Http\Requests\loginrequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Queue\RedisQueue;
class LoginController extends Controller
{
public function index(){
return view('login');
}
public function login( loginrequest $request ){
$credentiales = $request->getCredentials();
if( Auth::validate($credentiales) ){
return redirect()->to('login')->withErrors('auth.failed');
}
$user = Auth::getProvider()->retrieveByCredentials($credentiales);
Auth::login($user);
return $this->authenticated($request,$user);
}
public function authenticated (Request $request,$user){
return redirect('accountModule.indexusers');
}
}
and my Request[loginrequst.php]
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\contracts\Validation\Factory as ValidationFactory;
class loginrequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
//
'username'=>'required',
'password'=>'required'
];
}
public function getCredentials(){
$username = $this->get('username');
if( $this->isMail($username) ){
return['email'=> $username,
'password' => $this->get('password')
];
}
return $this->only('username','password');
}
public function isMail($value){
$factory = $this->container->make(ValidationFactory::class);
return !$factory->make(['username'=>$value],['username'=>'email'])->fails();
}
}
I was reading your problem and I found interesting the way you plan to check if the email is there or not.
I know it doesn't answer your question but you could try the following:
In your Request:
public function rules()
{
return [
//
'username'=>'required',
'password'=>'required'
];
}
In your controller:
public function login( loginrequest $request ){
$field = filter_var($request->input('username'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
$request->merge([$field => $request->input('username')]);
//validate credentials
if (!Auth::validate($request->only($field, 'password'))) {
return redirect()->to('login')->withErrors('auth.failed');
}
//create a session
$user = Auth::getProvider()->retrieveByCredentials($request->only($field, 'password'));
Auth::login($user);
return redirect()->to('/');
}
don't forget to configure your web.php file, so that the routes work for you. I hope I've helped.
Related
I am working on a login system for two users - admin and customer. For the admins, I've used the default auth files, but created new ones for the customer. My question is that the auth::check for admins works, but it doesn't for customers. So it doesn't query the database and logs in any email and any password. How can I fix this?
customerlogin.php
#extends('layouts.app')
#section('title','CustomerLogin')
#push('css')
#endpush
#section('content')
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-1">
#include('layouts.partial.msg')
<div class="card">
<div class="card-header" data-background-color="purple">
<h4 class="title">Customer Login</h4>
</div>
<div class="card-content">
<form method="POST" action="{{ route('customerLogin') }}">
#csrf
<div class="row">
<div class="col-md-12">
<div class="form-group label-floating">
<label class="control-label">Email</label>
<input type="email" class="form-control" name="email" value="{{ old('email') }}" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group label-floating">
<label class="control-label">Password</label>
<input type="password" class="form-control" name="password" required>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Login</button>
Back
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
#push('scripts')
#endpush
CustomerLogController
<?php
namespace App\Http\Controllers;
use App\Category;
use App\Item;
use App\Slider;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AutenticatesUser;
use Illuminate\Support\Facades\Hash;
use Auth;
use Redirect;
use Session;
use Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class CustomerLogController extends Controller
{
use AutenticatesUser;
/**
* Where to redirect users after login.
*
* #var string
*/
protected function authenticated() {
if($customers = Auth::customers()){
return redirect()->route('homepage');
}
}
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* Create a new controller instance.
*
* #return void
*/
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$sliders = Slider::all();
$categories = Category::all();
$items = Item::all();
return view('homepage',compact('sliders','categories','items'));
}
public function logout(Request $request) {
$this->guard()->logout();
$request->session()->invalidate();
return redirect('/');
}
}
web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::redirect('lara-admin','login');
Route::get('/','HomeController#index')->name('welcome');
Route::get ('/homepage', 'HomepageController#index')->name('homepage');
Route::post('/reservation','ReservationController#reserve')->name('reservation.reserve');
Route::post('/contact','ContactController#sendMessage')->name('contact.send');
Auth::routes();
Route::resource ('customerLogin', 'CustomerLoginController');
Route::post('homepage', 'CustomerLogController#index')->name('customerLogin');
Route::get('/logout', 'CustomerLogController#logout');
Route::group(['prefix'=>'admin','middleware'=>'auth','namespace'=>'Admin'], function (){
Route::get('dashboard', 'DashboardController#index')->name('admin.dashboard');
Route::resource('slider','SliderController');
Route::resource('category','CategoryController');
Route::resource('item','ItemController');
Route::get('reservation','ReservationController#index')->name('reservation.index');
Route::post('reservation/{id}','ReservationController#status')->name('reservation.status');
Route::delete('reservation/{id}','ReservationController#destory')->name('reservation.destory');
Route::get('contact','ContactController#index')->name('contact.index');
Route::get('contact/{id}','ContactController#show')->name('contact.show');
Route::delete('contact/{id}','ContactController#destroy')->name('contact.destroy');
});
Any help would be much appreciated!
In an older version of Laravel, when we created new auth files, we had the same issue as you're having - that Auth::Check() did not work. At all. Could not work out why.
We ended up manually checking the login, ensuring that it was correct, by using Hash::check() and then processing the login using Auth::LoginUsingId().
if(Hash::check($password, $user->u_pass)){
Auth::LoginUsingId($user->id);
return redirect()->intended('/');
}
At this point, all the Auth:: functions worked as intended.
It was a hacky solution, but it did work.
Im trying to create login form and its controller but when i try to login it doesnt work can any one help me i'm very new in laravel.
here is my form
<form action="/login" method="post">
{{ csrf_field() }}
<div class="form-group has-feedback">
<input type="email" name="email" class="form-control" placeholder="Email">
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" class="form-control" placeholder="Password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-7">
<div class="checkbox">
<label>
<input type="checkbox"> Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-xs-5">
<button type="submit" class="btn btn-primary btn-raised btn-block ">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
and here is my route
Route::get('/login', 'loginController#create');
Route::post('/login', 'loginController#store');
and my loginController is
class loginController extends Controller
{
public function __construct(){
$this->middleware('guest', ['except' => 'destroy']);
}
public function create(){
return view('pages.admin.login');
}
public function store(){
if(! auth()->attempt(request(['email', 'password']))){
return back()->withErrors([
'message' => 'Please check your credentials'
]);
}
return redirect('/home');
}
}
My user modal is
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'fname','oname','lname', 'email', 'phone','password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Please where i'm i doing wrong on these, when i entered email and password as my credential it just refresh and back to login page
auth()->attempt() requires an array, you're sending the return value of request() as a single argument, may that be it?
Your function should be like this with Request facade.
public function store(Request $request){
if(! auth()->attempt($request->only(['email', 'password']))){
return back()->withErrors([
'message' => 'Please check your credentials'
]);
}
return redirect('/home');
}
Here is how your attempt function should be like:
if(Auth::attempt( ['email'=> $request['email'],'password' => $request['password'] ])
Add these on top of LoginController
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
and modify your store method
public function store(Request $request){
$email = $request->email;
$password = $request->password;
if (! Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication Failed...
return back()->withErrors([
'message' => 'Please check your credentials'
]);
}
return redirect('/home');
}
Also remove password from $hidden in your User Model.
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'remember_token',
];
Hope it's helpful.
You can use php artisan make:auth and laravel will produce everything needed for a login including the controller and then you can go into your resource and edit to make it look how you imagined.
This is what my login controller looks like after using php artisan make:auth
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
I have followed a tutorial to add authentication to my application. I have a login route which has the method post and the form is also submitting as a post method. But whenever I click on the login button. Laravel throws an error of MethodNotAllowed. I assume that it is getting the method as a get request but the route is a post. Error is in thecompiled.php.
Route
Route::any('signup',['as' => 'signup' , 'uses' => 'Auth\AuthController#getRegister']);
Route::any('loginForm',['as' => 'loginForm' , 'uses' => 'Auth\AuthController#showLoginForm']);
Route::post('login',['as' => 'login' , 'uses' => 'Auth\AuthController#login']);
Route::any('postRegister',['as' => 'postRegister' , 'uses' =>'Auth\AuthController#postRegister']);
View
<form id="login" method="post" action="{{ route('login') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<input type="email" placeholder="User Email" id="email" name="email" class="form-control" value="{{old('email')}}"/>
</div>
<div class="form-group">
<input type="password" placeholder="Your Password" id="password" name="password" class="form-control" {{--value="{{old('email')}}"/--}}>
</div>
<div class="row">
<div class="mj_checkbox">
<input type="checkbox" value="1" id="check2" name="checkbox">
<label for="check2"></label>
</div>
<span> remember me</span>
</div>
</div>
<div class="form-group pull-right">
<span>forget password ?</span>
</div>
</div>
</div>
</div>
<input type="submit">
</div>
</form>
{authentication code is here}
<?php namespace App\Http\Controllers\Auth;
//use \App\Http\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\LoginRequest;
use App\Http\Models\Company;
use Hash;
class AuthController extends Controller {
/**
* the model instance
public function __construct(Guard $auth, \App\User $user)
{
$this->user = $user;
$this->auth = $auth;
$this->middleware('guest', ['except' => ['getLogout']]);
}
public function getRegister()
{
return view('public-pages.Home.signup');
public function postRegister(Request $request)
{
$company = new Company;
$company-> companyName = $request -> companyName;
$company-> email = $request -> email;
$company-> password = Hash::make($request-> password);
$company-> address = $request -> address;
$company-> employeeName = $request -> employeeName;
$company-> phone_no = $request -> phone_no;
$company-> country = $request -> country;
$company-> city = $request -> city;
$company -> save();
return redirect('loginForm');
}
public function showLoginForm()
{
return view('public-pages.Home.login');
}
public function login(LoginRequest $request)
{
if ($this->auth->attempt($request->only('email', 'password')))
{
return redirect('Private-pages.Company.cmp-home');
} else {
return redirect('/login')->withErrors([
'email' => 'The credentials you entered did not match our records. Try again?',
]);
}
public function getLogout()
{
$this->auth->logout();
return redirect('/');
}
}
in laravel 5 i try the PasswordController and the ResetsPasswords but always i have a route probleme
Route.php
Route::controllers(['uses' => 'Auth/PasswordController']);
Route::get('home/ResetsPasswords',array('as'=>'getEmail' ,'uses' => 'home/ResetsPasswords#getEmail') );
Route::post('home/ResetsPasswords',array('as'=>'postEmail' ,'uses' => 'home/ResetsPasswords#postEmail' ));
Route::get('home/ResetsPasswords/{token}',array('as' => 'getReset','uses' => 'home/ResetsPasswords#getReset' ) );
Route::post('home/ResetsPasswords/{token}', array( 'as' => 'postReset','uses' => 'home/ResetsPasswords#postReset'));
Route::get('home/ResetsPasswords',array('as'=>'getEmailSubject' ,'uses' => 'home/ResetsPasswords#getEmailSubject') );
Route::get('home/ResetsPasswords',array('as'=>'redirectPath' ,'uses' => 'home/ResetsPasswords#redirectPath') );
The PasswordController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
use ResetsPasswords;
public function __construct()
{
$this->middleware('guest');
}
}
the ResetsPasswords.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Create a new password controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Create a new password controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
ResetsPasswords.php
<?php
//namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
trait ResetsPasswords
{
/**
* Display the form to request a password reset link.
*
* #return \Illuminate\Http\Response
*/
public function getEmail()
{
return view('auth.password');
}
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
$response = Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject($this->getEmailSubject());
});
switch ($response) {
case Password::RESET_LINK_SENT:
return redirect()->back()->with('status', trans($response));
case Password::INVALID_USER:
return redirect()->back()->withErrors(['email' => trans($response)]);
}
}
/**
* Get the e-mail subject line to be used for the reset link email.
*
* #return string
*/
protected function getEmailSubject()
{
return isset($this->subject) ? $this->subject : 'Your Password Reset Link';
}
/**
* Display the password reset view for the given token.
*
* #param string $token
* #return \Illuminate\Http\Response
*/
public function getReset($token = null)
{
if (is_null($token)) {
throw new NotFoundHttpException;
}
return view('auth.reset')->with('token', $token);
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postReset(Request $request)
{
$this->validate($request, [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed',
]);
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$response = Password::reset($credentials, function ($user, $password) {
$this->resetPassword($user, $password);
});
switch ($response) {
case Password::PASSWORD_RESET:
return redirect($this->redirectPath());
default:
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #param string $password
* #return void
*/
protected function resetPassword($user, $password)
{
$user->password = bcrypt($password);
$user->save();
Auth::login($user);
}
/**
* Get the post register / login redirect path.
*
* #return string
*/
public function redirectPath()
{
if (property_exists($this, 'redirectPath')) {
return $this->redirectPath;
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}
}
and for the views
first the emails/password.blade.php
<?php
Click here to reset your password: {{ url('password/reset/'.$token) }}
?>
the auth/password.blade.php
#extends('layouts.master')
#section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Reset Password</div>
<div class="panel-body">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form-horizontal" role="form" method="POST" action="/password/email">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Send Password Reset Link
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
the reset.blade.php
#extends('layouts.master')
#section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Reset Password</div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form-horizontal" role="form" method="POST" action="/password/reset">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="token" value="{{ $token }}">
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Reset Password
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
and finally my login view
Mot de passe oublié?
so the error is
Call to undefined method Laravel\Routing\Route::controllers()
can you please help me :/ i try to change the route many time but always the same problem !!!!!!!
thank you
Implicit controllers are deprecated on Laravel 5. You need to remove this:
Route::controllers(['uses' => 'Auth/PasswordController']);
More info: https://laravel.com/docs/5.2/routing#route-model-binding
This is for laravel 5
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
This is for laravel 5.2
Route::group(['middleware' => ['web']], function () {
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
});
I think you are using in routes.php
use Illuminate\Routing\Route;
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
if you use this then the error comes.
Call to undefined method Illuminate\Routing\Route::controllers()
to avoid this error use this
use Illuminate\Support\Facades\Route;
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Note:Dont need to import anything route
leave it as
The below one also works
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
I have created a test user on my laravel app. The details are
user: joe#gmail.com pass: 123456
When I go through the registration process everything works as expected and an entry is made into the users table of the database
Once this is finished I redirect the user to the dashboard.
public function postCreate(){
//Rules
$rules = array(
'fname'=>'required|alpha|min:2',
'lname'=>'required|alpha|min:2',
'email'=>'required|email|unique:users',
'password'=>'required|alpha_num|between:6,12|confirmed',
'password_confirmation'=>'required|alpha_num|between:6,12'
);
$validator = Validator::make(Input::all(), $rules);
if($validator->passes()){
//Save in DB - Success
$user = new User;
$user->fname = Input::get('fname'); //Get the details of form
$user->lname = Input::get('lname');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));//Encrypt the password
$user->save();
return Redirect::to('/books')->with('Thank you for Registering!');
}else{
//Display error - Failed
return Redirect::to('/')->with('message', 'The Following Errors occurred')->withErrors($validator)->withInput();
}
}
I then navigate back to the landing page and attempt to log in using the credentials above and I keep getting told that Auth::attempt() is failing hence my user cannot log into the application.
public function login(){
if(Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password')))){
//Login Success
echo "Success"; die();
return Redirect::to('/books');
}else{
//Login failed
echo "Fail"; die();
return Redirect::to('/')->with('message', 'Your username/password combination was incorrect')->withInput();
}
}
Does anyone know why this is happening? This is the Schema for my users table:
Schema::create('users', function($table){
$table->increments('id');
$table->integer('type')->unsigned();
$table->string('fname', 255);
$table->string('lname', 255);
$table->string('email')->unique();
$table->string('password', 60);
$table->string('school', 255);
$table->string('address_1', 255);
$table->string('address_2', 255);
$table->string('address_3', 255);
$table->string('address_4', 255);
$table->string('remember_token', 100);
$table->timestamps();
});
Any help is much appreciated.
'View for Login':
<div class="page-header">
<h1>Home page</h1>
</div>
<!-- Register Form -->
<form action="{{ action('UsersController#postCreate') }}" method="post" role="form">
<h2 class="form-signup-heading">Register</h2>
<!-- Display Errors -->
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
<!-- First Name -->
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" name="fname" />
</div>
<!-- Last Name -->
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" name="lname" />
</div>
<!-- Email -->
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" />
</div>
<!-- Password-->
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" />
</div>
<!-- Confirm Password -->
<div class="form-group">
<label>Confirm Password</label>
<input type="password" class="form-control" name="password_confirmation" />
</div>
<input type="submit" value="Register" class="btn btn-primary"/>
</form>
<!-- Login Form -->
<form action="{{ action('UsersController#login') }}" method="post" role="form">
<h2 class="form-signup-heading">Login</h2>
<!-- Email -->
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" />
</div>
<!-- Password-->
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" />
</div>
<input type="submit" value="Login" class="btn btn-primary"/>
</form>
Can you run this function below - and tell me where the error occurs? It will diagnose the problem:
public function testLogin()
{
$user = new User;
$user->fname = 'joe';
$user->lname = 'joe';
$user->email = 'joe#gmail.com';
$user->password = Hash::make('123456');
if ( ! ($user->save()))
{
dd('user is not being saved to database properly - this is the problem');
}
if ( ! (Hash::check('123456', Hash::make('123456'))))
{
dd('hashing of password is not working correctly - this is the problem');
}
if ( ! (Auth::attempt(array('email' => 'joe#gmail.com', 'password' => '123456'))))
{
dd('storage of user password is not working correctly - this is the problem');
}
else
{
dd('everything is working when the correct data is supplied - so the problem is related to your forms and the data being passed to the function');
}
}
Edit: one thought - are you sure the user is being correctly saved in the database? Have you tried to 'empty/delete' your database and try your code again? In your current code, it will fail if you keep registering with joe#gmail.com - because it is unique. But you dont catch the error anywhere. So empty the database and try again...
Edit 2: I found another question you posted with the same problem - and in there you mentioned that the following code is your user model?
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
public function getAuthIdentifier() {
}
public function getAuthPassword() {
}
public function getRememberToken() {
}
public function getRememberTokenName() {
}
public function getReminderEmail() {
}
public function setRememberToken($value) {
}
}
Is that EXACTLY your current user model? Because if so - it is wrong - none of those functions should be blank.
This is what a CORRECT user model should look like for Laravel 4.2
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
You would make sure about:
your model:
mine looks like:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'users';
protected $hidden = array('password');
public function getAuthIdentifier()
{
Return $this->getKey ();
}
public function getAuthPassword()
{
return $this->password;
}
}
make sure your app/config/auth.php is configured correctly
make sure app/config/app.php has service provider
'Illuminate\Auth\AuthServiceProvider',
Make sure your controller class has auth. before writing class you have used Auth (I mean include Auth class)
That all could make Auth doesn't work well
With password hashing enabled, the User model must override these methods:
public function getAuthIdentifierName()
{
return 'email';
}
public function getAuthIdentifier()
{
return request()->get('email');
}
public function getAuthPassword()
{
return Hash::make(request()->get('password'));
}
What is the value for strlen(Hash::make(Input::get('password')))? If it is greater than 60, then this would cause the authentication to fail each time, as the stored password is not the full hash.
Good day, here is what I discovered when I encountered the same error: A simple string compare will reveal that the two hashing methods produce two different hashed values.
echo strcmp(Hash::make('password'),bcrypt('password'));
My assumption is that Auth::attempt([]) uses bcrypt() to hash out passwords which produces a different value to what you used Hash:make().