Laravel 5 Auth:attempt() always returns false - php

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

Related

Where can I get individual files for my Laravel Framework?

I am working with an inherited site based on the Laravel Framework which I upgraded from 5.6 to 8.0. I most aspects the site works great, but I occasionally sumble upon missing pieces. For example, I just discovered that the Reset Password feature does not work. Looking into it I find that there is a route for this:
Route::post('password/reset/{token}', ['as' => 'app.password.reset.post', 'uses' => 'App\Auth\ResetPasswordController#reset']);
Yet there is no 'reset()' method in the ResetPasswordController. Additionally, the ResetPasswordController uses the trait 'ResetsPassword', yet there is no such trait located under
Illuminate\Foundation\Auth\ResetsPasswords;
I tried checking the github repo for the Laravel framework, but these pieces were not there. I also looked under laravel-ui and didn't see them. According to the documentation,
"Laravel includes Auth\ForgotPasswordController and Auth\ResetPasswordController classes that contains the logic necessary to e-mail password reset links and reset user passwords. All of the routes needed to perform password resets may be generated using the laravel/ui Composer package"
I'm a little nervous about doing a general update as all other pieces are in place and working so I was looking for a way to obtain the individual pieces and have not found anything.
Here are my login routes:
Route::group(['prefix' => 'app'], function () {
//Auth::routes();
Route::get('login', ['as' => 'app.login', 'uses' => 'App\Auth\LoginController#showLoginForm']);
Route::post('login', ['as' => 'app.login.post', 'uses' => 'App\Auth\LoginController#login']);
Route::post('logout', ['as' => 'app.logout.post', 'uses' => 'App\Auth\LoginController#logout']);
Route::post('password/email', ['as' => 'app.password.email.post', 'uses' => 'App\Auth\ForgotPasswordController#sendResetLinkEmail']);
Route::get('password/reset', ['as' => 'app.password', 'uses' => 'App\Auth\ForgotPasswordController#showLinkRequestForm']);
Route::get('password/reset/{token}', ['as' => 'app.password.reset', 'uses' => 'App\Auth\ResetPasswordController#showResetForm']);
Route::post('password/reset/{token}', ['as' => 'app.password.reset.post', 'uses' => 'App\Auth\ResetPasswordController#reset']);
And this is what my ResetPasswordController looks like:
namespace App\Http\Controllers\App\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\ResetsPasswords;
class ResetPasswordController 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;
/**
* Where to redirect users after password reset.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->redirectTo = route('app.dashboard');
$this->middleware('guest');
}
/**
* Display the password reset view for the given token.
*
* If no token is present, display the link request form.
*
* #param \Illuminate\Http\Request $request
* #param string|null $token
* #return \Illuminate\Http\Response
*/
public function showResetForm(Request $request, $token = null)
{
return view('app.auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
}
Also, from what I've read there is possibly an updated reset.blade.php. My question is what is my best approach to fix the reset password bug?
This is the trait for reseting passwords, that I found in my project, I hope it can help you somehow.
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Illuminate\Validation\ValidationException;
trait ResetsPasswords
{
use RedirectsUsers;
/**
* Display the password reset view for the given token.
*
* If no token is present, display the link request form.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function showResetForm(Request $request)
{
$token = $request->route()->parameter('token');
return view('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
public function reset(Request $request)
{
$request->validate($this->rules(), $this->validationErrorMessages());
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($request, $response)
: $this->sendResetFailedResponse($request, $response);
}
/**
* Get the password reset validation rules.
*
* #return array
*/
protected function rules()
{
return [
'token' => 'required',
'email' => 'required|email',
'password' => ['required', 'confirmed', Rules\Password::defaults()],
];
}
/**
* Get the password reset validation error messages.
*
* #return array
*/
protected function validationErrorMessages()
{
return [];
}
/**
* Get the password reset credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(Request $request)
{
return $request->only(
'email', 'password', 'password_confirmation', 'token'
);
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #param string $password
* #return void
*/
protected function resetPassword($user, $password)
{
$this->setUserPassword($user, $password);
$user->setRememberToken(Str::random(60));
$user->save();
event(new PasswordReset($user));
$this->guard()->login($user);
}
/**
* Set the user's password.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #param string $password
* #return void
*/
protected function setUserPassword($user, $password)
{
$user->password = Hash::make($password);
}
/**
* Get the response for a successful password reset.
*
* #param \Illuminate\Http\Request $request
* #param string $response
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
protected function sendResetResponse(Request $request, $response)
{
if ($request->wantsJson()) {
return new JsonResponse(['message' => trans($response)], 200);
}
return redirect($this->redirectPath())
->with('status', trans($response));
}
/**
* Get the response for a failed password reset.
*
* #param \Illuminate\Http\Request $request
* #param string $response
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
protected function sendResetFailedResponse(Request $request, $response)
{
if ($request->wantsJson()) {
throw ValidationException::withMessages([
'email' => [trans($response)],
]);
}
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
/**
* Get the broker to be used during password reset.
*
* #return \Illuminate\Contracts\Auth\PasswordBroker
*/
public function broker()
{
return Password::broker();
}
/**
* Get the guard to be used during password reset.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard();
}
}

Middleware redirecting loop error in Laravel

I am trying to redirect users based on which role they enter in the registration page, however I keep getting the 'redirect too many times' error. I think its because I am using both the auth and guest mddlewares on the home page however I can not seem to fix it
Web.php:
Route::get('/', function () {
return view('auth.login');
});
Auth::routes();
// Using middleware guest (Redirect If Authenticated) to check role and redirect to right route.
Route::middleware(['guest'])->group(function(){
Route::get('/home', 'HomeController#index')->name('home');
});
Route::prefix('referrer')->group(function(){
/* need a more advanced middleware to give a notification when a brand user hits the
* referrer register/login page.
* e.g. logout and switch account, or simply make the referrer auth pages not accessible.
*/
Route::get('/login/{program_id?}', 'ReferrerController#showLoginForm')->name('referrer.login')->middleware('guest');
Route::post('/login/{program_id?}', 'Auth\LoginController#login')->name('referrer.login.user');
Route::get('/', 'ReferrerController#getHome')->name('referrer.home')->middleware('auth');
//program middieware
Route::middleware(['program.exist'])->group(function(){
Route::get('/register/{program_id?}', 'ReferrerController#showRegistrationForm')->name('referrer.register');
Route::post('/register/{program_id?}', 'ReferrerController#register')->name('referrer.register.user');
});
});
Register Controller:
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
// protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* 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, [
'name' => ['required', 'string', 'max:255'],
'role' => ['required', 'integer', 'between:1,3'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'role_id' => $data['role'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
return $user;
}
protected function redirectTo() {
$role = auth()->user()->role_id;
switch ($role) {
case '3':
return RouteServiceProvider::REF_HOME;
break;
case '1':
//temp set as brand home
return RouteServiceProvider::ADMIN_HOME;
break;
default:
return RouteServiceProvider::HOME;
break;
}
}
}
Home Controller:
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
RedirectIfAuthenticated Middleware:
class RedirectIfAuthenticated
{
/**
* 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($guard)->check()) {
// User role
$role = Auth::user()->role->name;
switch ($role) {
//role_id = 3
case 'referrer':
return redirect(RouteServiceProvider::REF_HOME);
break;
//role_id = 1
case 'admin':
//temp set as brand home
return redirect(RouteServiceProvider::ADMIN_HOME);
break;
default:
return redirect(RouteServiceProvider::HOME);
break;
}
}
return $next($request);
}
}
your index function in the HomeController has auth and guest middlewares, just use one of them only.

Not able to login on using laravel

I have created a login page using laravel 5.5 using command php artisan make:auth
even after entering correct credentials. i am unable to login. It redirects me to login page.
Table structure
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL DEFAULT '',
`email` varchar(100) NOT NULL DEFAULT '',
`password` varchar(100) NOT NULL DEFAULT '',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`remember_token` varchar(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
KEY `name` (`name`),
KEY `email` (`email`),
KEY `password` (`password`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
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::get('/', 'HomeController#index');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/logout', function () {
Auth::logout();
return redirect('/login');
});
LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
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']);
}
}
When i try check the whether i am able enter the user details successfully the check is success full or not in file.
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
trait AuthenticatesUsers
{
use RedirectsUsers, ThrottlesLogins;
/**
* Show the application's login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
return view('auth.login');
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
*/
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
/**
* Attempt to log the user into the application.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->filled('remember')
);
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(Request $request)
{
return $request->only($this->username(), 'password');
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
//
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Symfony\Component\HttpFoundation\Response
*
* #throws ValidationException
*/
protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
]);
}
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function username()
{
return 'email';
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
return redirect('/');
}
/**
* Get the guard to be used during authentication.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard();
}
}
When i dump $this->attemptLogin($request) the response is true.
Please help.

Unable to get login using laravel 5.4

Hi I'm developing user authentication on basis of SOAP API response using Laravel 5.4, for that I've implemented UserProvider and AuthServiceProvider but still unsuccessful.
Here is the implementation of UserProvider
namespace App\Authentication;
use App\Http\Controllers\ApiCallsController;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\UserProvider as IlluminateUserProvider;
use Config;
use Illuminate\Foundation\Auth\User;
class UserProvider implements IlluminateUserProvider
{
/**
* #param mixed $identifier
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveById($identifier)
{
// Get and return a user by their unique identifier
$http_client = new ApiCallsController();
$check_user = $http_client->HttpClient("GET", Config::get('constants.c2mCloud') . '/user/UserTypeOrName/' . $identifier);
$users = json_decode($check_user);
if ($users->responseCode == "00") {
if (count($users->users) > 0) {
$user = new User();
$users = $users->users[0];
$user->id = $users->userId;
$user->c2MUsername = $users->c2MUsername;
$user->createdAt = $users->createdAt;
$user->lastModifiedAt = $users->lastModifiedAt;
$user->password = $users->password;
$user->userType = $users->userType;
$user->active = $users->active;
return new \App\User([
'id' => $users->userId
]);
}
}
}
/**
* #param mixed $identifier
* #param string $token
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByToken($identifier, $token)
{
// Get and return a user by their unique identifier and "remember me" token
}
/**
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param string $token
* #return void
*/
public function updateRememberToken(Authenticatable $user, $token)
{
// Save the given "remember me" token for the given user
}
/**
* Retrieve a user by the given credentials.
*
* #param array $credentials
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials)
{
// Get and return a user by looking up the given credentials
$http_client = new ApiCallsController();
$check_user = $http_client->HttpClient("GET", Config::get('constants.c2mCloud') . '/user/UserTypeOrName/' . $credentials['c2MUsername']);
$users = json_decode($check_user);
if ($users->responseCode == "00") {
if (count($users->users) > 0) {
$users = $users->users[0];
// return $users->users[0];
return new \App\User([
'id' => $users->userId,
// 'c2MUsername' => $users->c2MUsername,
// 'createdAt' => $users->createdAt,
// ''
]);
}
}
}
/**
* Validate a user against the given credentials.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param array $credentials
* #return bool
*/
public function validateCredentials(Authenticatable $user, array $credentials)
{
// Check that given credentials belong to the given user
}
}
And implementation of AuthServiceProvider
<?php
namespace App\Authentication;
use Auth;
use App\Authentication\UserProvider;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* #return void
*/
public function boot()
{
Auth::provider('c2m_provider', function($app, array $config) {
return new UserProvider();
});
}
/**
* Register bindings in the container.
*
* #return void
*/
public function register()
{
//
}
}
and my User class is
<?php
namespace App;
use Illuminate\Contracts\Auth\Authenticatable;
class User implements Authenticatable
{
/**
* #return string
*/
public function getAuthIdentifierName()
{
// Return the name of unique identifier for the user (e.g. "id")
}
/**
* #return mixed
*/
public function getAuthIdentifier()
{
// Return the unique identifier for the user (e.g. their ID, 123)
}
/**
* #return string
*/
public function getAuthPassword()
{
// Returns the (hashed) password for the user
}
/**
* #return string
*/
public function getRememberToken()
{
// Return the token used for the "remember me" functionality
}
/**
* #param string $value
* #return void
*/
public function setRememberToken($value)
{
// Store a new token user for the "remember me" functionality
}
/**
* #return string
*/
public function getRememberTokenName()
{
// Return the name of the column / attribute used to store the "remember me" token
}
}
And in my controller after using Auth::login($user); when I check is user logged in by Auth::check() it alwys return false.
Anyone who can help me?
Try using Auth::attempt($username,$password)
if (Auth::attempt($username,$password)) {
//user is logged in
} else {
//user is not logged in
}
Auth::check() simply checks if the user is logged in. It doesn't actually process the login.
For custom Authentication, we need in to implement these 4 classes in laravel 5.4. And this implementation is working for me in a live project.
namespace App\Auth;
use Illuminate\Contracts\Auth\Authenticatable as User_Authenticatable;
class Authenticatable implements User_Authenticatable
{
/**
* The column name of the "remember me" token.
*
* #var string
*/
protected $rememberTokenName = 'remember_token';
/**
* Get the name of the unique identifier for the user.
*
* #return string
*/
public function getAuthIdentifierName()
{
return "id";
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->{$this->getAuthIdentifierName()};
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the token value for the "remember me" session.
*
* #return string
*/
public function getRememberToken()
{
if (! empty($this->getRememberTokenName())) {
return $this->{$this->getRememberTokenName()};
}
}
/**
* Set the token value for the "remember me" session.
*
* #param string $value
* #return void
*/
public function setRememberToken($value)
{
if (! empty($this->getRememberTokenName())) {
$this->{$this->getRememberTokenName()} = $value;
}
}
/**
* Get the column name for the "remember me" token.
*
* #return string
*/
public function getRememberTokenName()
{
return $this->rememberTokenName;
}
}
2nd
namespace App\Auth;
use Illuminate\Contracts\Auth\Access\Authorizable as User_Authorizable;
use Illuminate\Contracts\Auth\Access\Gate;
Class Authorizable Implements User_Authorizable
{
/**
* Determine if the entity has a given ability.
*
* #param string $ability
* #param array|mixed $arguments
* #return bool
*/
public function can($ability, $arguments = [])
{
return app(Gate::class)->forUser($this)->check($ability, $arguments);
}
/**
* Determine if the entity does not have a given ability.
*
* #param string $ability
* #param array|mixed $arguments
* #return bool
*/
public function cant($ability, $arguments = [])
{
return ! $this->can($ability, $arguments);
}
/**
* Determine if the entity does not have a given ability.
*
* #param string $ability
* #param array|mixed $arguments
* #return bool
*/
public function cannot($ability, $arguments = [])
{
return $this->cant($ability, $arguments);
}
}
3rd
namespace App\Auth;
use Illuminate\Auth\Notifications\ResetPassword as ResetPasswordNotification;
class CanResetPassword extends ResetPasswordNotification
{
}
4th
<?php
namespace App\Auth;
use App\Http\Controllers\ApiCallsController;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\UserProvider as IlluminateUserProvider;
use Config;
use App\Models\ApiUser;
class UserProvider implements IlluminateUserProvider
{
/**
* #param mixed $identifier
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveById($identifier)
{
// Get and return a user by their unique identifier
return ApiUser::getUser(null, null, $identifier);
}
/**
* #param mixed $identifier
* #param string $token
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByToken($identifier, $token)
{
// Get and return a user by their unique identifier and "remember me" token
}
/**
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param string $token
* #return void
*/
public function updateRememberToken(Authenticatable $user, $token)
{
// Save the given "remember me" token for the given user
}
/**
* Retrieve a user by the given credentials.
*
* #param array $credentials
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials)
{
// Get and return a user by looking up the given credentials
return ApiUser::getUser($credentials['c2MUsername']);
}
/**
* Validate a user against the given credentials.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param array $credentials
* #return bool
*/
public function validateCredentials(Authenticatable $user, array $credentials)
{
// Check that given credentials belong to the given user
$api_user = \App\Models\ApiUser::getUser($credentials['c2MUsername']);
if(!empty($api_user)){
return true;
}
return false;
}
}
My Custom Auth Provider
<?php
/**
* Created by PhpStorm.
* User: CresenTech
* Date: 23-Oct-17
* Time: 7:19 PM
*/
namespace App\Providers;
use Illuminate\Support\Facades\Auth;
use App\Auth\UserProvider;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class CustomAuthProvider extends ServiceProvider {
/**
* The policy mappings for the application.
*
* #var array
*/
// protected $policies = [
//// 'App\Model' => 'App\Policies\ModelPolicy',
// ];
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
/**
* Register any authentication / authorization services.
*
* #return void
*/
// $this->registerPolicies();
Auth::provider('custom',function()
{
return new UserProvider();
});
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
//
}
}
And my auth.php in config directory
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
//
// 'c2m' => [
// 'driver' => 'session',
// 'provider' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
// 'users' => [
// 'driver' => 'eloquent',
// 'model' => App\User::class,
// ],
'users' => [
'driver' => 'custom',
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
// 'table' => 'password_resets',
'expire' => 60,
],
],
];

Login by Email/Phone number in Laravel Auth()

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

Categories