Autnenticate from different table in laravel - laravel

I have a table called customusers. I want to authenticate from this table. I am successful in registering the users and storing in customusers table but i am not able to login using Auth::atempt.
Below is my code
auth.php
<?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',
],
'custom' =>[
'driver' => 'session',
'provider' => 'customusers'
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'custom_api' => [
'driver' => 'token',
'provider' => 'customusers',
'hash' => false,
],
],
/*
|--------------------------------------------------------------------------
| 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,
],
'customusers' => [
'driver' => 'eloquent',
'model' => App\CustomUser::class,
],
// '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,
],
'customusers' => [
'provider' => 'customusers',
'table' => 'password_resets',
'expire' => 60,
]
],
];
CustomUser.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class CustomUser extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $guard = 'custom';
protected $table = 'customusers';
protected $fillable = [
'name', 'username', 'passcode',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'passcode', 'remember_token',
];
public function getAuthPassword()
{
return $this->passcode;
}
}
Route
Route::POST('/mlogin','Auth\LoginController#mLogin')->name('mylogin');
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
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');
$this->middleware('guest:custom')->except('logout');
}
public function mLogin(Request $request){
echo $request->input('username').' '.$request->input('passcode');;
if (Auth::guard('custom')->attempt([
'username' => $request->input('username'),
'passcode' => $request->input('passcode')
])) {
echo 'success';
} else {
echo 'fail';
}
}
}
I am unable to login. what am i doing wrong here please guide.

If I am understanding it correctly you can try using the https://packalyst.com/packages/package/sboo/multiauth for multiple auth tables.

you should use custom guard when using Auth Methods.
so when attempting to authenticate users use this
Auth::guard('custom')->attempt()

Related

"Undefined method 'createToken'" in UserAuthController in laravel 9

I'm trying to use passport in laravel and I'm following this tutorial: https://blog.logrocket.com/laravel-passport-a-tutorial-and-example-build/. But in step 4 I come across an error creating the UserAuthCotroller.
Here is my UserAuthController:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
class UserAuthController extends Controller
{
public function register(Request $request)
{
$data = $request->validate([
'name' => 'required|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|confirmed'
]);
$data['password'] = bcrypt($request->password);
$user = User::create($data);
$token = $user->createToken('API Token')->accessToken;
return response([ 'user' => $user, 'token' => $token]);
}
public function login(Request $request)
{
$data = $request->validate([
'email' => 'email|required',
'password' => 'required'
]);
if (!auth()->attempt($data)) {
return response(['error_message' => 'Incorrect Details.
Please try again']);
}
$token = auth()->user()->createToken('API Token')->accessToken;
return response(['user' => auth()->user(), 'token' => $token]);
}
}
I have searched and some people say that I just have to add this lines to my user.php file:
use HasApiTokens, HasFactory, Notifiable;
use Laravel\Passport\HasApiTokens;
Here is my user.php file
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Here is the error
[{
"resource": "/c:/xampp/htdocs/application-example/app/Http/Controllers/Auth/UserAuthController.php",
"owner": "_generated_diagnostic_collection_name_#1",
"code": "1013",
"severity": 8,
"message": "Undefined method 'createToken'.",
"source": "intelephense",
"startLineNumber": 40,
"startColumn": 34,
"endLineNumber": 40,
"endColumn": 45
}]
Here is my config/auth.php
<?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"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'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\Models\User::class,
],
// '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 each reset token will 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,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];
I have done that but still doesn`t work. Any idea?

Why is my laravel 8 custom guard login always return false?

This is the config/auth.php
I have edited the auth the student provider
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',
'hash' => false,
],
'student' => [
'driver' => 'session',
'provider' => 'students',
],
],
/*
|--------------------------------------------------------------------------
| 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\Models\User::class,
],
'students' => [
'driver' => 'eloquent',
'model' => App\Models\Student::class,
],
// '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,
'throttle' => 60,
],
'students' => [
'provider' => 'students',
'table' => 'password_resets',
'expire' => 15,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];
this is my student model
i have edited the student model using the user model as base
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Student extends Authenticatable
{
use HasFactory, Notifiable;
protected $guard = 'student';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'password',
'birthdate',
'Course',
'Year',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
This is my Student LoginController
My login controller return the login form and below is the login attempt that always return false so it always redirect me back to the login page.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
// use App\Http\Controllers\Auth\LoginController ;
// use Illuminate\Foundation\Auth\AuthenticatesUsers;
class Student_loginController extends Controller
{
// public function __construct()
// {
// $this->middleware('guest:student')->except('logout');
// }
public function index(){
return view('auth.student_login');
}
public function login(Request $request){
$this->validate($request,
[
'email' => 'required|email',
'password' => 'required',
]);
if(Auth::guard('student')->attempt($request->only('email','password'))){
return redirect()->back()->with('failed',' student not successfully logged in');
}
return redirect('student_dashboard')->with('success','student login');
}
}
this is my route
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\RegistrationController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\LoginController;
use App\Http\Controllers\LogoutController;
use App\Http\Controllers\WelcomeController;
use App\Http\Controllers\StudentController;
use App\Http\Controllers\Student_loginController;
use App\Http\Controllers\student_dashController;
/*
|--------------------------------------------------------------------------
| 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('/',[WelcomeController::class, 'index'])->name('welcome');
Route::get('register',[RegistrationController::class, 'index'])->name('register');
Route::get('dashboard',[DashboardController::class, 'index'])
->name('dashboard')
->middleware('auth');
Route::get('student_dashboard',[student_dashController::class, 'index'])
->name('student_dashboard');
Route::get('login',[LoginController::class, 'index'])
->name('login')
->middleware('guest');
Route::get('logout',[LogoutController::class, 'logout'])->name('logout');
Route::get('student_login',[Student_loginController::class, 'index'])->name('student_login');
Route::get('student',[StudentController::class, 'index'])->name('student')->middleware('auth');;
Route::get('student/{student_ID}', [StudentController::class, 'show'])->name('student.showstudent')->middleware('auth');;
Route::post('register',[RegistrationController::class, 'store'])->name('register.store');
Route::post('store_student', [RegistrationController::class, 'store_student'])->name('store_student')->middleware('auth');
Route::post('student_login',[Student_loginController::class, 'login'])->name('student_login.login');
Route::post('login',[LoginController::class, 'login'])->name('login.login');
Route::post('student',[StudentController::class, 'store'])->name('student.store')->middleware('auth');;
Route::delete('student/{student_ID}',[StudentController::class, 'destroy'])->name('student.destroy')->middleware('auth');;
Route::put('showstudent/{student_ID}',[StudentController::class, 'edit'])->name('showstudent.edit')->middleware('auth');;
// Route::get('/', function () {
// return view('welcome');
// });
if(Auth::guard('student')->attempt($request->only('email','password'))){
return redirect()->back()->with('failed',' student not successfully logged in');}
Your are redirecting back with a failed message when login is true. You have redirect back with a failed message when login is fail. You have to write the logic like this.
if(!Auth::guard('student')->attempt($request->only('email','password'))){
return redirect()->back()->with('failed',' student not successfully logged in');}
Last you have to protect student_dashboard route with middleware auth with its guard
auth:student
Route::middleware('auth:student')->group(function(){
Route::get('student_dashboard',[student_dashController::class, 'index'])
->name('student_dashboard');}
or return the middleware in your dashboard controller contsructor method like this
public function __construct()
{
$this->middleware('auth:student');
}

Able to access login page when user is still login in laravel

I have created login functionality using Laravel Default Auth, everything is working except i am able to access login page still when user is Login in application, i want to redirect user to dashboard url if user hit
http://myapplication/login
it should automatically redirect to
http://myapplication/dashboard
My controller code is :
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 = 'user/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
RedirectIfAuthenticated.php
public function handle($request, Closure $next, $guard = null)
{
if ((Auth::guard($guard)->check()) && $guard == 'web') {
return redirect('/');
}
if ((Auth::guard($guard)->check()) && $guard == 'admin') {
return redirect('/dashboard');
}
return $next($request);
}
Auth.php
<?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',
'hash' => false,
],
'admin' => [
'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,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
// '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,
],
],
];
Please edit your RedirectIfAuthenticated Middleware like the following
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
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()) {
return redirect('user/dashboard');
}
return $next($request);
}
}

It leads to unauthorized result in my API when i am Changing the default table "users" linked with auth in laravel,

When i am trying to change the table users, that is by default linked with the Auth in laravel my API always gives me "unauthorized user" response and when i use the default table user it works fine. I want to know why it is happening?
I have made all the changes that is required to switch the table from users to my choice table.
my table name is : apitable, Model_name: apitablemodel
changes in auth.php:
<?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' => 'api',
'Passwords' => 'apitable', //if want to change the table attached with auth then make changes here
],
/*
|--------------------------------------------------------------------------
| 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' => 'apitabel',
],
'api' => [
'driver' => 'passport',
'provider' => 'apitable',
],
],
/*
|--------------------------------------------------------------------------
| 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,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'apitable' => [
'driver' => 'eloquent',
'model' => App\apitablemodel::class,
],
// '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,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
'apitable' => [
'provider' => 'apitable',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Here is my model file
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
// use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class apitablemodel extends Authenticatable
{ use HasApiTokens, Notifiable;
//
protected $table='apitable';
protected $fillable = ['Email', 'Password','token'];
public $timestamps=false;
protected $hidden = [
'Password', 'token',
];
}
Here is my controller file
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\apitablemodel;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
// response()->json(['success' => $success], $this-> successStatus);
class product extends Controller
{ public $successStatus = 200;
public function login(Request $request){
if(Auth::check(['Email' => request('Email'), 'Password' => request('Password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
$user->token=$success['token'];
// $token->expires_at=Carbon::now()->addMinutes(1);
$user->save();
return response()->json(["token_expires in :"=>"2min","token"=>$user->token]);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
public function update(Request $req){
$obj= User::find($req->id);
$obj->email=$req->email;
if($obj->save()){
return response()->json(['success'=>'Updated']);
}
else{
return ["status:"=>"Unauthorized user, make sure your are login"];
}
}
}
I have two functions in my controller, one is for updating the data that is present in the "apitable" table and one for login so that only authenticated users can update the database table values.
When i hit my API in postman it gives me unauthorized response as for which i have write the condition in my controller. I want to know why if condition is failing.
I think you should use Auth::attempt() method for login.
public function login(Request $request){
$credentials = $request->only('Email', 'Password');
if(Auth::attempt($credentials)){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
$user->token=$success['token'];
// $token->expires_at=Carbon::now()->addMinutes(1);
$user->save();
return response()->json(["token_expires in :"=>"2min","token"=>$user->token]);
} else {
return response()->json(['error'=>'Unauthorised'], 401);
}

How to change the Authentication model in Laravel

I need to change the default User model in my Laravel Application to Admin model. I followed the tutorial given in change Authentication model in Laravel 5.3
the Admin model must do authentication, register and reset password. This is what I did so far.
After doing php artisan make:auth, I created Admin.php model
namespace Modules\Admin\Entities;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Admin extends Authenticatable
{
use Notifiable;
protected $fillable = ['name','email','password'];
protected $hidden = [
'password', 'remember_token',
];
}
This is config/auth.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' => 'admins',
],
/*
|--------------------------------------------------------------------------
| 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' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
/*
|--------------------------------------------------------------------------
| 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' => \Modules\Admin\Entities\Admin::class,
],
// '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' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
],
];
and this is RegisterController.php
namespace App\Http\Controllers\Auth;
use Modules\Admin\Entities\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
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 = '/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'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:admins'],
'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)
{
return Admin::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
This code creates a user in admins table, but when I try to login, it throws the following error:
Argument 2 passed to Illuminate\Auth\SessionGuard::__construct() must be an instance of Illuminate\Contracts\Auth\UserProvider, null given, called in ...\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php on line 125
I can't understand why this error happens.
Change your code on config/auth.php:
'web' => [
'driver' => 'session',
'provider' => 'admins',
],
to:
'web' => [
'driver' => 'session',
'provider' => 'users',
],
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.
Change in your config/auth.php file like this:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
]
]

Resources