"Method [guard] does not exist - laravel

Why does this error appears when the guard exists in auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'manager' => [
'driver' => 'jwt',
'provider' => 'managers',
],
'admin' => [
'driver' => 'jwt',
'provider' => 'admins',
],
],
And the providers also sets with right format. In the controller the register function is down below:
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'username' => 'required|string|max:255',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
$user = new Manager();
$user->username = $request->username;
$user->password = bcrypt($request->password);
$user->save();
$token = JWTAuth::guard('manager')->attempt($request->only('username', 'password'));
return response()->json(compact('user', 'token'));
}
The JWTMiddleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class JWTAuth
{
public function handle($request, Closure $next, $guard)
{
try {
$user = JWTAuth::parseToken()->authenticate($guard);
if (!$user) {
throw new \Exception('User not found');
}
} catch (\Exception $e) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $next($request);
}
}
In kernel.php I have included these inside aliases array:
'jwt.manager' => \App\Http\Middleware\JWTManagerMiddleware::class,
'jwt.admin' => \App\Http\Middleware\JWTAdminMiddleware::class,
'jwt.auth' => \App\Http\Middleware\JWTAuth::class,
What am I doing wrong and how can I solve this?

Related

Invalid credentials in laravel using jwt

I have uploaded about this problem many more times and none worked for me, I tried my best but still not working. I am not sure where does it go wrong.I have installed tymon/jwt-auth from the documnetation and installed laravel service provide after publishing. Then I change the default guard as api and set one user guard and another one admin guard. Sets the providers , Here are the code:
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
'admin_api' => [
'driver' => 'jwt',
'provider' => 'admin_apis',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admin_apis' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
],
Then set this in jwt.php 'jwt' => Tymon\JWTAuth\Providers\JWT\Lcobucci::class,
Kernel.php
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
User Model:
<?php
// app/Models/User.php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
protected $fillable = [
'username', 'password',
];
protected $hidden = [
'password',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
class UserController extends Controller
{
public function login(Request $request)
{
$credentials = $request->only('username', 'password');
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'Invalid credentials'], 401);
}
return response()->json(compact('token'));
}
public function me()
{
$user = auth()->user();
return response()->json(compact('user'));
}
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
}
Api.php
<
?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\AdminDataController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\ManagerDataController;
// Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
// return $request->user();
// });
// routes/api.php
Route::post('user/login', [App\Http\Controllers\UserController::class,'login']);
Route::middleware('auth:api')->group(function () {
Route::get('user/me', [App\Http\Controllers\UserController::class,'me']);
Route::post('user/logout', [App\Http\Controllers\UserController::class,'logout']);
});
Route::post('admin/login', [App\Http\Controllers\AdminController::class,'login']);
Route::middleware('auth:admin_api')->group(function () {
Route::get('admin/me', [App\Http\Controllers\AdminController::class,'me']);
Route::post('admin/logout', [App\Http\Controllers\AdminController::class,'logout']);
});
It returns invalid credentials but the field data are exists. How can I solve this?

How can I access routes that has Laravel Guard?

I want to create Laravel code with login by multi-table. I don't have any problem with login, but when I access http://127.0.0.1:8000/api/products it shows Unathenticated :
How can I access route by whos currently logging in? here is my code :
*Thanks in advance
AccountController.php (Login Method)
public function login(Request $request)
{
if(strtolower($request->grantType) === "user") {
if(Auth::guard('user')->attempt(['email' => $request->email, 'password' => $request->password])){
$user = Auth::guard('user')->user();
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
$success['guard'] = $user;
return $this->sendResponse($success, 'User login successfully.');
}
else{
return $this->sendError('Unauthorized', ['error'=>'Invalid credentials'], 401);
}
} else if (strtolower($request->grantType) === "student") {
if(Auth::guard('student')->attempt(['email' => $request->email, 'password' => $request->password])){
$user = Auth::guard('student')->user();
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
$success['guard'] = $user;
return $this->sendResponse($success, 'User login successfully.');
}
else{
return $this->sendError('Unauthorized', ['error'=>'Invalid credentials'], 401);
}
} else if (strtolower($request->grantType) === "teacher") {
if(Auth::guard('teacher')->attempt(['email' => $request->email, 'password' => $request->password])){
$user = Auth::guard('user')->user();
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
$success['guard'] = $user;
return $this->sendResponse($success, 'Teacher login successfully.');
}
else{
return $this->sendError('Unauthorized', ['error'=>'Invalid credentials'], 401);
}
} else {
return $this->sendError('Bad Request', ['error'=>'No enum constant '.$request->grantType], 400);
}
}
Route/api.php
Route::post('register', [AccountController::class, 'register']);
Route::post('login', [AccountController::class, 'login']);
Route::middleware('auth:student')->group( function () {
Route::resource('products', ProductController::class);
});
config/auth.php
'defaults' => [
'guard' => 'user',
'passwords' => 'user',
],
'guards' => [
'user' => [
'driver' => 'session',
'provider' => 'user',
],
'teacher' => [
'driver' => 'session',
'provider' => 'teacher',
],
'student' => [
'driver' => 'session',
'provider' => 'student',
],
],

Api for different tables using sunctum

I have three tables.
1-customer
2-seller
3-affilate
I am fresher for LARAVEL, now i am studying on LARAVEL 8, so i wanted to make login with token api from these tables. Then how can i make please please please help me i am not able to find any proper solutions.
I have added in config/auth.php
'guards' => [
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
'affilate' => [
'driver' => 'session',
'provider' =>'affilate',
],
'customer' => [
'driver' => 'session',
'provider' => 'customer',
],
'seller' => [
'driver' => 'session',
'provider' => 'seller',
],
],
'providers' => [
'admin' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
'customer' => [
'driver' => 'eloquent','model'=>App\Models\Customer::class,
],
'seller' => [
'driver' => 'eloquent',
'model' =>App\Models\Seller::class,
],
'affilate' => [
'driver' => 'eloquent',
'model' =>App\Models\Affilate::class,
],
],
Here Is my First Models For Customer
<?php
namespace App\Models;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Customer extends Authenticatable
{
use HasFactory, HasApiTokens, Notifiable;
protected $table = 'customer';
protected $primaryKey = 'id';
protected $fillable = [
'name', 'email', 'mobile', 'countryCode','email_verified_at',
'email_verified','passWord','confirmPassword'
];
protected $hidden = [
'passWord', 'remember_token',
];
}
Controller For Customer
<?php
namespace App\Http\Controllers\API;
use Carbon\Carbon;
use App\Models\Customer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class CustomerController extends Controller
{
public function customerLogin(Request $request)
{
if (Auth::guard('customer')->attempt($credentials))
{
$registerCustomer = Auth::Customer();
$token = $registerCustomer->createToken( $registerCustomer->name)->accessToken;
$success['success'] = true;
$success['message'] = "Success! you are logged in successfully";
$success['token'] = $token->plainTextToken;
$success['tokenExpiryTime'] = 2592000000; //converted 30days minutes in miliseconds
$success['customerName'] = $registerCustomer->name;
return response()->json(['success' => $success ], $this->successStatus);
}else {
return response()->json(['error'=>'Unauthorised'], 401);
}
}
public function registerCustomer(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|min:3|max:55',
'email' => 'required|email|unique:customers',
'mobile' => 'required|digits:10|unique:customers',
'countryCode' => 'required|digits:6|unique:customers',
'passWord' => 'required|alpha_num|min:8',
'confirmPassword' => 'required|same:passWord|alpha_num|min:8',
]);
if($validator->fails())
{
return response()->json(['error'=>'Unprocessable Entity','validationErrors' => $validator->errors()], 422);
}
$customerData = array(
'name' => $request->name,
'email' => $request->email,
'mobile' => $request->mobile,
'countryCode' => $request->countryCode,
'passWord' => Hash::make($request->passWord),
'confirmPassword' => Hash::make($request->confirmPassword),
'email_verified' => '0',
'email_verified_at' => Carbon::now(),
);
$saveCustomerData = Customer::create($customerData);
return $this->customerLogin($request);
}
}
And Here Is My Routes
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\CustomerController;
Route::post('/customer/register', [CustomerController::class,
'registerCustomer']);
Route::post('/customer/login', [CustomerController::class,
'customerLogin']);
I wanted To Know Where is my mistake its Showing ErrorErrorException: Undefined variable $credentials in file
Thanks Please Please Please Please Please Please Help Me
try this manual method as you told attempt() is not working in your case
public function customerLogin(Request $request)
{
$customer = Customer::where('email', $request->email)->first();
if (!$customer) {
return response()->json(['error' => 'email not found'], 400);
}
if (Hash::check($request->email, $customer->password)) {
auth()->login($customer);
$registerCustomer = Auth::user();
$token = $registerCustomer->createToken($registerCustomer->name)->accessToken;
$success['success'] = true;
$success['message'] = "Success! you are logged in successfully";
$success['token'] = $token->plainTextToken;
$success['tokenExpiryTime'] = 2592000000; //converted 30days minutes in miliseconds
$success['customerName'] = $registerCustomer->name;
return response()->json(['success' => $success], $this->successStatus);
} else {
return response()->json(['error' => 'Unauthorised'], 401);
}
}

How to authenticate multiple type of user with same auth guard [Lumen]

I am developing an API Application using Lumen 8. I have 3 types of users. For them, I use 3 different Models. I am using JWT authentication [packege- tymon/jwt-auth].
Here is my Auth.php config. I use 3 types of auth guard
return [
'defaults' => [
'guard' => env('AUTH_GUARD', 'user'),
'passwords' => 'users',
],
'guards' => [
'user' => [
'driver' => 'jwt',
'provider' => 'users',
],
'vendor_user' => [
'driver' => 'jwt',
'provider' => 'vendor_users',
],
'super_user' => [
'driver' => 'jwt',
'provider' => 'super_users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\Models\User::class
],
'vendor_users' => [
'driver' => 'eloquent',
'model' => \App\Models\VendorUser::class
],
'super_users' => [
'driver' => 'eloquent',
'model' => \App\Models\SuperUser::class
]
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'vendor_users' => [
'provider' => 'vendor_users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'super_users' => [
'provider' => 'super_users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
For login, I use 3 different routes using the mentioned auth guard.
protected function login(Request $request, $guard = 'user')
{
//validate incoming request
$this->validate($request, [
'email' => 'required|string',
'password' => 'required|string',
]);
$credentials = $request->only(['email', 'password']);
if (! $token = Auth::guard($guard)->attempt($credentials)) {
return response()->json(responseFormat(ERROR,___('Unauthorized')), 401);
}
return $this->respondWithToken($token);
}
public function userLogin(Request $request)
{
return $this->login($request,'user');
}
public function superUsersLogin(Request $request)
{
return $this->login($request,'super_user');
}
public function vendorUsersLogin(Request $request)
{
return $this->login($request,'vendor_user');
}
I have managed to get a token for successful login from all 3 types of users.
But I am facing a problem when I authenticate all user using Authenticate middleware
public function handle($request, Closure $next, $guard = null)
{
if ($this->auth->guard($guard)->guest()) {
return response(responseFormat(ERROR,'Unauthorized.'), 401);
}
return $next($request);
}
It only works for the default auth-guard type user (which is user guard). If I want to authenticate other user types I had to use a different route and mention which auth-guard to use.
$router->group(['middleware' => 'auth','prefix' => 'api'], function ($router)
{
$router->get('/send-email', 'EmailController#sendEmail');
$router->get('/users', 'UsersController#users');
});
$router->group(['middleware' => 'auth:vendor_user','prefix' => 'api/vendor'], function ($router)
{
$router->get('/send-email', 'EmailController#sendEmail');
$router->get('/users', 'UsersController#users');
});
$router->group(['middleware' => 'auth:super_user','prefix' => 'api/super_user'], function ($router)
{
$router->get('/send-email', 'EmailController#sendEmail');
$router->get('/users', 'UsersController#users');
});
Is there any way where I can authenticate all 3 types of users for the same route? so that I don't have to a different route for each type of user.
$router->group(['middleware' => 'auth','prefix' => 'api'], function ($router)
{
$router->get('/send-email', 'EmailController#sendEmail');
$router->get('/users', 'UsersController#users');
});
Like this API can be used by all 3 types of users and authenticated by the same auth-guard or some other ways.
BS: I must use 3 different tables for 3 types of users.
Create a separate middleware to attempt the credential. Then, set the default guard Auth should use. You don't have to pass the guard to login.
In LoginController
public function __construct()
{
$this->middleware('SetAuthGuard:user')->except('logout');
$this->middleware('SetAuthGuard:vendor_users')->except('logout');
$this->middleware('SetAuthGuard:super_users')->except('logout');
}
SetAuthGuard middleware
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
$credentials = $request->only('email','password');
foreach ($guards as $guard) {
if (Auth::guard($guard)->attempt($credentials)) {
Auth::shouldUse($guard);
}
}
return $next($request);
}

Laravel 5.2 dashboard redirect loop

I am new to laravel and am using the 5.2 version. Through tutorials and such I have found online I have been able to use make:auth for a user account. However I have three different types of users (viewer, artist, sponsor) meaning that each user has to be on their own table and have their own registration. This is a huge project with a ton of registered users each with different options. That being said I am not able to use just one table and create roles it is just to big of a project for that.
I have created two of the three log in systems. The problem I am having is that after the artist is signed in and sent to the artist dashboard I get a :too many redirects” error. The url directs to the correct dashboard but the page does not display. Any help would be much appreciated.
Routes.php
Route::group(['middleware' => ['web']], function () {
Route::get('/', function () {
return view('welcome');
});
Route::get('/artist', function () {
return view('artist');
});
Route::get('/sponsor', function () {
return view('sponsor');
});
Route::get('/viewer', function () {
return view('viewer');
});
Route::get('/contact', function () {
return view('contact');
});
Route::get('/ArtistRegistration', function () {
return view('ArtistRegistration');
});
Route::get('/artdashboard', function () { 'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'artist' => [
'provider' => 'artist',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
return view('artdashboard');
});
Route::post('/signup', [
'uses' => 'UserController#postSignup',
'as' => 'signup'
]);
Route::post('/signin', [
'uses' => 'UserController#postSignin',
'as' => 'signin'
]);
Route::get('/dashboard', [
'uses' => 'UserController#getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
//Route::group(['middleware' => ['artist']], function () {
Route::post('/signupart', [
'uses' => 'ArtistController#postSignupArt',
'as' => 'signupart'
]);
Route::post('/signinart', [
'middleware' => 'artist',
'uses' => 'ArtistController#postSigninArt',
'as' => 'signinart'
]);
Route::group(['middleware' => 'artist', 'as' => 'artdashboard'], function() {
Route::get('artdashboard', 'ArtistController#getArtDashboard');
});
//Route::get('/artdashboard', [
//'uses' => 'ArtistController#getArtDashboard',
//'as' => 'artdashboard',
//'middleware' => 'artist'
// ]);
Auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
//For Artists
'artist' => [
'driver' => 'session',
'provider' => 'artist',
//'table' => 'artists',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
//for Artists
'artist' => [
'driver' => 'eloquent',
'model' => App\Artist::class,
'table' => 'artists',
],
],
Artist.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;
class artist extends Model implements Authenticatable
{
//protected $table = 'artists';
use \Illuminate\Auth\Authenticatable;
}
ArtistController.php
<?php
namespace App\Http\Controllers;
use App\Artist;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
Class ArtistController extends Controller
{
//public function __construct()
//{
//$this->middleware('artist');
//}
public function getArtDashboard()
{
return view('artdashboard');
}
public function postSignupArt(Request $request)
{
$this->validate($request, [
'userName' => 'required|min:4',
'userEmail' => 'required|email|unique:artists',
'userPass' => 'required|min:3',
'first_name' => 'required|max:120',
'last_name' => 'required|max:120',
'zip' => 'required|max:5',
]);
$userName = $request['userName'];
$userEmail = $request['userEmail'];
$userPass = bcrypt($request['userPass']);
$first_name = $request['first_name'];
$last_name = $request['last_name'];
$zip = $request['zip'];
$artist = new Artist();
$artist->userName = $userName;
$artist->userEmail = $userEmail;
$artist->userPass = $userPass;
$artist->first_name = $first_name;
$artist->last_name = $last_name;
$artist->zip = $zip;
$artist->save();
Auth::login($artist);
return redirect()->route('/artdashboard');
}
public function postSigninArt(Request $request)
{
$this->validate($request, [
'userEmail' => 'required',
'userPass' => 'required'
]);
//if (Auth::guard('artist')->attempt($credentials)) {
if (Auth::guard('artist')->attempt(['userEmail' => $request['userEmail'], 'userPass' => $request['userPass']])) {
return redirect()->route('artdashboard');
}
return redirect()->back();
}
}
Middleware\ArtistAuthenticate
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class ArtistAuthenticate
{
/**
* 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 = 'artist')
{
//if ($this->auth->check())
//{
//return new RedirectResponse(url('/artdashboard'));
//}
//return $next($request);
//}
//}
if (Auth::guard($guard)->guest()) {
//if ($this->middleware('guest', ['only'=>['artist', 'viewer', 'sponsor', 'welcome', 'contacts']])
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
}//else{
return redirect()->route('artdashboard');
// }
}
return $next($request);
}
}
Kernal.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'artist' => \App\Http\Middleware\RedirectifAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
//'artist' => \App\Http\Middleware\ArtistAuthenticate::class,
'guest' => \App\Http\Middleware\RedirectifNotArtist::class,
];

Resources