I'm new to laravel, so i started by creating a messaging application. User should be able to send message to each other. So i created migrations, seeds,models and also defined relationships in models. Everything was working fine. I was able to seed perfectly.
So i created a login page, applied validations. But now i'm unable to login.
Here is the route :
Route::group(array('prefix'=>'social'), function(){
Route::get('/', array('as' => 'loginformshow', 'uses' => 'LoginformController#showLogin'));
Route::post('loginform', array('as'=>'loginformdo', 'uses'=>'LoginformController#doLogin'));
Route::get('loggedin', array('as'=>'loggedin', 'uses'=>'LoginformController#loggedin'));
});
Here's the respective method in controller
public function doLogin(){
$rules = array('email'=> 'required|email', 'password'=>'required');
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::to('social')->withErrors($validator)->withInput(Input::except('password'));
}else {
$userdata = array('email' => Input::get('email'), 'password' => Input::get('password'));
if(Auth::attempt($userdata)) {
return Redirect::route('loggedin');
}else echo "Invalid User";
}
}
Auth::attempt is returning false every time and so the output is Invalid User.
i used print_r to check the data received in $userdata and it's showing correct credentials.
Here's the User model:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* 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');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
public function conversationsReply(){
return $this->hasMany('ConversationReply', 'user_id', 'id');
}
}
Related
I am trying to make a custom login with multi auth. For the meantime, I am trying to do the login for admin. When an admin logs in, the login function handles it (it also just refreshes without the login function) Auth:attempt() seems to be always returning false, however (I have a different table name and fields). Aside from that, I can freely access the dashboard by just changing the url even if the user is not really logged in.
AuthController
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = 'admin/dashboard';
/**
* Where to redirect users after logout.
*
* #var string
*/
protected $redirectAfterLogout = 'admin/login';
/**
* Guard for admin
*
*
*/
protected $guard = 'admin';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'OUsername' => 'required|max:255|unique:users',
'OPassword' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return Admin::create([
'OUsername' => $data['OUsername'],
'OPassword' => bcrypt($data['OPassword']),
]);
}
/**
* Show login form.
*
*
*
*/
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('pages.admin.login');
}
/**
* Show registration form.
*
*
*
*/
public function showRegistrationForm()
{
return view('pages.admin.register');
}
public function login(Request $request)
{
//Get inputs
$username = $request->input('username');
$password = $request->input('password');
//Redirect accordingly
if (Auth::guard('admin')->attempt(array('OUsername' => $username, 'OPassword' => $password)))
{
return redirect()->intended('admin/dashboard');
}
else
{
//when echoing something here it is always displayed thus admin login is just refreshed.
return redirect('admin/login')->withInput()->with('message', 'Login Failed');
}
}
Admin Provider Model
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'account_officer_t';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'OUsername', 'OPassword',
];
public $timestamps = false;
/**
* Set primary key
*
* #var int
*/
protected $primaryKey = 'AccountOfficerID';
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'OPassword', 'remember_token',
];
public function getAuthPassword()
{
return $this->OPassword;
}
Routes
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::group(['namespace' => 'Admin', 'middleware' => 'guest'], function(){
//This uses the guest middleware with the class name RedirectIfAuthenticated
Route::auth();
//Route for admin dashboard view
Route::get('admin/dashboard', array('as' => 'dashboard', 'uses' => 'AdminController#showDashboard'));
});
Route::group(['middleware' => ['web']], function () {
//Route for login
Route::get('admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('admin/login','AdminAuth\AuthController#login');
Route::get('admin/logout','AdminAuth\AuthController#logout');
//Route for registration
Route::get('admin/ims-register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/ims-register', 'AdminAuth\AuthController#register');
});
RedirectIfAuthenticated (guest middleware)
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard('admin')->check()) {
return redirect('admin/dashboard');
}
if (Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
I have just started learning the MVC framework and started using Laravel. Thank you for the help.
Notes
My passwords are stored using bcrypt() with column length of 255
I have tried checking if the hash from the table matches my input using Hash::check. It returns true. But when I do this:
dd( Auth::guard('admin')->attempt(array('OUsername' => $username, 'OPassword' => $password)));
It is false.
Tried checking the results based on the answer from this question especially # 7. Still the same.
The problem seems to be with this line
'OPassword' => $password
I changed it to
'password' => $password
It has to be password not OPassword. And then in my Admin model I specified
public function getAuthPassword()
{
return $this->OPassword;
}
I am using
Route::auth();
for making user login in Laravel.
There are multiple phones linked to a user and saved in table:phones.
Tables are
users : id,email,password
phones: id,user_id,phone_number
How to make user login with both Email/Phones and password
In App\Traits\Auth, create a file named LoginUser.php.
<?php
namespace App\Traits\Auth;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
trait LoginUser
{
/**
* Handle a Authenticates the User.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->attemptLogin($request)) {
return $this->successfulLogin($request);
}
return $this->failedLogin($request);
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
'username' => 'required',
'password' => 'required',
]);
}
/**
* Attempt to log the user into the application.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function attemptLogin(Request $request)
{
//Try with email AND username fields
if (Auth::attempt([
'phone' => $request['username'],
'password' => $request['password']
],$request->has('remember'))
|| Auth::attempt([
'email' => $request['username'],
'password' => $request['password']
],$request->has('remember'))){
return true;
}
return false;
}
/**
* This is executed when the user successfully logs in
*
* #var Request $request
* #return Reponse
*/
protected function successfulLogin(Request $request){
return redirect($this->redirectTo);
}
/**
* This is executed when the user fails to log in
*
* #var Request $request
* #return Reponse
*/
protected function failedLogin(Request $request){
return redirect()->back()->withErrors(['password' => 'You entered the wrong username or password']);
}
}
Then in
App\Http\Controllers\Auth
rewrite (or create) LoginController.php and paste this
<?php
namespace App\Http\Controllers\Auth;
use App\Traits\Auth\LoginUser;
use App\Http\Controllers\Controller;
class LoginController extends Controller
{
use LoginUser;
/**
* Where to redirect users after registration.
*
* #var string | URL
*/
protected $redirectTo = '/mPanel';
/**
* Displays login page
*
* #return \Illuminate\Http\Response
*/
public function show(){
return response()->view('LOGIN PAGE HERE');
}
}
Finally in your routes file, add these routes:
Route::get('login', 'Auth\LoginController#show');
Route::post('login', 'Auth\LoginController#login');
I want to use column email and password for login.
Password is hashed during registration and saved to the database ('driver' => 'database').
Email column is not primary key, but just unique.
AuthController.php:
// Get all the inputs
$userdata = array(
'email' => Input::get('username'),
'password' => Input::get('password')
);
// Declare the rules for the form validation.
$rules = array(
'email' => 'Required',
'password' => 'Required'
);
// Validate the inputs.
$validator = Validator::make($userdata, $rules);
// Check if the form validates with success.
if ($validator->passes())
{
// Try to log the user in.
if (Auth::attempt($userdata, true))
{
// Redirect to homepage
return Redirect::to('')->with('success', 'You have logged in successfully');
}
else
{
// Redirect to the login page.
return Redirect::to('login')->withErrors(array('password' => 'password invalid'))->withInput(Input::except('password'));
}
}
Anyway, I just got error:
ErrorException
Undefined index: id
It also shows me this:
public function getAuthIdentifier()
{
return $this->attributes['id'];
}
What I am doing wrong? Thanks
EDIT
User model:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* 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');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
getAuthIdentifier is an interface method. GenericUser class is implementating that method and requires user id.
So check do you really have id attribute on your model.
In case this helps someone in the future here is how I resolved this. As #WereWolf suggested you do want to set
protected $primaryKey = 'id';
in your model, but your driver should also be 'eloquent' in your auth.php config.
'driver' => 'eloquent',
This will tell laravel to use your Eloquent model as the user object instead of the generic user object from the database table.
You most probably didn't assign your primary key in the user table, the ID should be primary key and also you may add following in your User model to specify your custom primary key:
protected $primaryKey = 'id';
Make sure that, the primary key in the user table matched with this ($primaryKey), means that, must be same.
In Laravel4,I have written the following code in routes but it always redirect me to login page.
I have googled and found it on stack overflow too and tried all solutions but not succeeded.I am sure it would be a silly mistake but kindly track it out.Thank You
Routes:
Route::post('login', function ()
{
$user = array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password'))
);
/* Store entered username and password in an array named as 'user' */
print_r($user);
if (Auth::attempt($user))
{
return Redirect::route('home')->with('flash_notice', 'You are successfully logged in.');
/* Authentication Success!!..Redirect user to home page */
}
else
{
return Redirect::route('login')
->with('flash_error', 'Your username/password combination was incorrect.')->withInput();
/* Authentication failure!! lets go back to the login page */
}
});
User Model:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
// public $timestamps = false;
/**
* The primary key of the table.
*
* #var string
*/
protected $primaryKey = 'id';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
}
User Seeder:
<?php
class UserSeeder extends Seeder {
public function run()
{
DB::table('users')->delete();
return array('table'=>'users',
array(
'username' => 'admin',
'password' => 'admin'
),
);
}
}
When you ask the Auth class to attempt a login, you pass in the username and pass as it is. But if you look into the method, it will first hash the password to make it secure and then match it with database entry. When you are storing it, from your present implementation, its not hashed.
As suggested above, you should make this change in your seeder:
array(
'username' => 'admin',
'password' => Hash::make('password')
),
Although I am not very sure if the way you are using seeder is correct by syntax, but if it works, just hash the password there.
You should hash your password.
array(
'username' => 'admin',
'password' => Hash::make('password')
),
You can find more information in the docs.
This is routes file and $users shows the values but login fails
Route::post('login', function () {
$user = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
if(Auth::attempt($user))
{
return Redirect::to('profile')
->with('flash_notice', 'You are successfully logged in.');
}
else
{
// authentication failure! lets go back to the login page
return Redirect::route('login')
->with('flash_error', 'Your username/password combination was incorrect.')
->withInput();
}
});
Modal:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* 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');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
When using the authentication mechanism provided by Laravel you should pass the following check list:
The database column where you store the password should be a string with a length of 60 characters.
The password should be stored encrypted, no plain. Since we are talking about BCrypt it has to be a value similar to: $2a$10$KssILxWNR6k62B7yiX0GAe2Q7wwHlrzhF3LqtVvpyvHZf0MwvNfVu.
You have to configure the security mechanism by editing the file located app/config/auth.php.
After that, you will eventually have your problem solved.