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?
Related
i'm try to using multi auth using Admin Guard and implement with Spatie, after login succes using the Admin Guard, then access the Group Middleware but i got an error 403 USER IS NOT LOGGED IN.
this is my code :
Admin Model :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class Administration extends Authenticable
{
use HasFactory, Notifiable, HasRoles;
protected $guard_name = 'admins';
protected $fillable = [
'name', 'email', 'username', 'password', 'photo'
];
protected $hidden = ['password'];
}
LoginController :
public function __construct()
{
$this->middleware('guest:admins')->except('logout');
}
public function authenticated(Request $request, $user)
{
if ($user->hasRole('admin')) {
return redirect()->route('bank.master-bank.index');
} else if ($user->hasRole('finance')) {
return redirect()->route('bank.master-bank.index');
} else if ($user->hasRole('supervisor')) {
return redirect()->route('bank.master-bank.index');
}
return redirect('login');
}
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required'
]);
if (auth()->guard('admins')->attempt($request->only('email', 'password'))) {
$request->session()->regenerate();
$this->clearLoginAttempts($request);
return redirect()->intended('/bank/master-bank');
} else {
$this->incrementLoginAttempts($request);
return redirect()
->back()
->withInput()
->withErrors(["Incorrect user login details!"]);
}
}
Auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
'admins' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Administration::class,
],
],
Route Web.php
Route::group(['middleware' => 'auth:admins'], function () {
Route::group(['middleware' => ['role:admin']], function () {
Route::group(['prefix' => 'user', 'as' => 'user.'], function () {
Route::get('/', [UserAdminController::class, 'user_panel'])->name('user_panel');
Route::get('/role-user', [UserAdminController::class, 'role_panel'])
Route::get('/detail_user/{id}', [UserAdminController::class, 'detail_user'])
Route::resource('/verif-user', VerifUserController::class);
});
});
});
when access the Route::group(['middleware' => ['role:admin']], function () { i got error 403
USER IS NOT LOGGED IN.
Check you haven't define your middleware role and you are using it here.
i have created a second model for authenticating as company, i add the guard and provide
but enable to login!
Company class :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
class Company extends Authenticatable
{
use HasFactory;
protected $guard = 'company';
protected $guarded = [];
}
Config/Auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'company' => [
'driver' => 'session',
'provider' => 'company',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'company' => [
'driver' => 'eloquent',
'model' => App\Models\Company::class,
],
],
CompanyLoginController
use App\Http\Controllers\Controller;
use App\Models\Entreprise;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class CompanyLoginController extends Controller
{
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::guard('company')->attempt($credentials)) {
$request->session()->regenerate();
return redirect()->intended('dashboard');
}
return back()->withErrors([
'email' => 'The provided credentials do not match our records.',
]);
}
}
the $hasher->check() was the one returning false after going deep in te code but for some reason i couldn't find the solution.
as you said you builtin function is not working so you can try manual method like this
public function authenticate(Request $request)
{
$company = Company::where('email', $request->email)->first();
if (!$company) {
return back()->withErrors([
'email' => 'The email doest not exist.',
]);
}
if (Hash::check($request->password, $company->password)) {
auth()->guard('company')->login($company);
return redirect()->intended('dashboard');
}
return back()->withErrors([
'email' => 'The provided credentials do not match our records.',
]);
}
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);
}
}
i need to create three authentication: user, admin, restUser.
I managed to create multiple login for user and admin but when try to add login for restUser it returns user form...
this is my code:
app/Teretaneusers.php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Teretaneusers extends Authenticatable
{
use Notifiable;
protected $guard = 'teretaneuser';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
and I create table in MySQL database teretaneusers with column: name, email, password
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins',
],
'teretaneuser' => [
'driver' => 'session',
'provider' => 'teretaneusers',
],
'teretaneuser-api' => [
'driver' => 'token',
'provider' => 'teretaneusers',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admins::class,
],
'teretaneusers' => [
'driver' => 'eloquent',
'model' => App\Teretaneusers::class,
],
],
Controllers/UserGymController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserGymController extends Controller
{
public function __construct()
{
$this->middleware('auth:teretaneuser');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('teretaneuser');
}
}
Controllers\Auth\UserGymLoginController.php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
class UserGymLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:teretaneuser');
}
public function showLoginForm(){
return view('auth.teretaneuser-login');
}
public function login(Request $request){
//validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]
);
//attempt to log user in
if(Auth::guard('teretaneuser')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
return redirect()->intended(route('userGym.dashboard'));
}
return redirect()->back()->withInput($request->only('email','remember'));
}
}
auth/teretaneuser-login.blade.php
form class="form-horizontal" method="POST" action="{{
route('userGym.login.submit') }}"
and web.php
Auth::routes();
Route::get('/home', 'HomeController#index');
Route::prefix('admin')->group( function() {
Route::get('/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/', 'AdminController#index')->name('admin.dashboard');
});
Route::prefix('userGym')->group( function() {
Route::get('/login', 'Auth\UserGymLoginController#showLoginForm')->name('userGym.login');
Route::post('/login', 'Auth\UserGymLoginController#login')->name('userGym.login.submit');
Route::get('/', 'UserGymController#index')->name('userGym.dashboard');
});
Can somebody tell me where I'm wrong? When I try login from adress http://localhost/logovanje/public/userGym/login
it redirest me to http://localhost/logovanje/public/home
I use Laravel 5.4
I did the same for the admin and it worked.
Most likely you still have a valid session and you got a middleware (possibly RedirectIfAuthenticated) that is coming into play.
I think you could use Sentinel for this as it has an authentication package called roles and permissions
Here's a link for its documentation.
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,
];