User Is Not Logged In using Multi Auth/Guard in Spatie - laravel

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.

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?

Laravel 8 Multiple Auth with two different models return False even when credentials are true

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.',
]);
}

Laravel Login and redirect depending on role id

So I have login page that the admin or users can use to login. It went well until such time we have some changes and added the admin side. I only uses 1 table for all user types and I have role_id column that defines the users role. So if the role_id is 0, I have to redirect them to the dashboard page whereas if it's a user, will redirect to user page. I have tried as what is suggested in the internet but can't make it work. Here's what I have:
class UserLoginController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest:user')->except('logout');
}
public function showLoginForm()
{
return view('auth.user-login');
}
public function login(UserLoginRequest $request)
{
// Attempt to log the user in
if (Auth::guard('user')->attempt(['email' => $request->email, 'password' => $request->password])) {
// if successful, then redirect to their intended location
return redirect()->intended(route('user.dashboard'));
}
// if unsuccessful, then redirect back to the login with the form data
if (! User::where('email', $request->email)->where('password', bcrypt($request->password))->first() ) {
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['status' => 'Incorrect username or password.']);
}
}
public function logout()
{
Auth::guard('user')->logout();
return redirect()->route('user.login');
}
}
config/auth
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'guest' => [
'driver' => 'session',
'provider' => 'guests',
],
'user' => [
'driver' => 'session',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'guests' => [
'driver' => 'eloquent',
'model' => App\Guest::class,
],
],
MODEL
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $guard = 'user';
protected $fillable = [
//fillable cols
];
//change role id data type to integer
protected $casts = [
'role_id' => 'integer',
];
}
Now, where should I insert the condition to check if it's an admin or a user?
You can try it
public function login(UserLoginRequest $request)
{
// Attempt to log the user in
if (!Auth::guard('user')->attempt(['email' => $request->email, 'password' => $request->password])) {
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['status' => 'Incorrect username or password.']);
}
$user = Auth::guard('user')->user();
if ($user->role_id === 0) {
return redirect()->route('user.dashboard');
}
return redirect()->route('user.page');
}
Check below i have edited the method of login:
public function login(UserLoginRequest $request)
{
// Attempt to log the user in
if (Auth::guard('user')->attempt(['email' => $request->email, 'password' => $request->password])) {
// Over here this condition will be true when user is successfully login
// Below is the user data i have printed in that you can check the role of user which is login.
$user = Auth::user();
print_r($user);
}
// if unsuccessful, then redirect back to the login with the form data
if (! User::where('email', $request->email)->where('password', bcrypt($request->password))->first() ) {
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['status' => 'Incorrect username or password.']);
}
}

different login routes and login views for student and admin

Every laravel newbie struggles with multi auth, I am no exception
I am trying to make student management system. There will two different routs for admin admin/login and for student student/login.
The student can't register itself, but he will be registered by admin.
So a student has only access to student/dashboard, registration of students will be done by the admin on admin/dashboard.
Below is the detail what I have already done:
created migration for both admin and student.
created guard for both admin and student.
modified login controller and added adminLogin and studentLogin methods.
modified RedirectIfAuthenticated middleware
Config/auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'students' => [
'driver' => 'session',
'provider' => 'students',
],
'web-admin'=>[
'driver'=>'session',
'provider'=>'admin',
],
'api' => [
'driver' => 'token',
'provider' => 'students',
'hash' => false,
],
],
'providers' => [
'students' => [
'driver' => 'eloquent',
'model' => App\Student::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'passwords' => [
'students' => [
'provider' => 'students',
'table' => 'password_resets',
'expire' => 60,
],
'admin' => [
'provider' => 'admin',
'table' => 'password_resets',
'expire' => 60,
],
],
LoginController.php
lass LoginController extends Controller
{
use AuthenticatesUsers;
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('guest:web-admin')->except('logout');
$this->middleware('guest:students')->except('logout');
}
public function showAdminLoginForm()
{
return view('admin.login', ['url' => 'admin']);
}
public function adminLogin(Request $request)
{
$this->validate($request, [
'admin_id' => 'required',
'password' => 'required|min:8'
]);
if (Auth::guard('admin')->attempt(['admin_id' => $request->adminid, 'password' => $request->password], $request->get('remember'))) {
return redirect()->intended('/admin/dashboard');
}
return back()->withInput($request->only('admin_id', 'remember'));
}
public function showStudentLoginForm()
{
return view('student.login', ['url' => 'student']);
}
public function studentLogin(Request $request)
{
$this->validate($request, [
'roll_no' => 'required',
'password' => 'required|min:8'
]);
if (Auth::guard('writer')->attempt(['roll_no' => $request->roll_no, 'password' => $request->password], $request->get('remember'))) {
return redirect()->intended('/student/dashboard');
}
return back()->withInput($request->only('roll_no', 'remember'));
}
}
RedirectAuthenticated.php
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if('web_admin'==='$guard'){
return redirect('/admin/dashboard');
}
return redirect('/admin/login');
}
if (Auth::guard($guard)->check()) {
if('students'==='$guard'){
return redirect('/student/dashboard');
}
return redirect('/student/login');
}
return $next($request);
}
}
I have created two folders in the view, student and admin. They both have two files. login.blade.php and dashboard.blade.php
What laravel does it it shows login, and register under auth folder.
I want to give two routes one for /admin/login which return admin.login view.
Same for student /student/login which return student.login view.
I want to remove /register route and make the link to available on admin dashboard , there will be no admin register link.
Also restrict the user from accessing admin area.
**I don't want the whole code, just help me steps and way that I should follow or changes I have to make **
Finally I solved it. I didn't use php artisan make:auth, instead I did it from scratch. Created a fresh project, deleted User.php and the migration.
Created models Student.php and Admin.php along with migrations and controllers.
php artisan make:model Student -mc
php artisan make:model Admin -mc
After than I created guards, I deleted default guard (I don't know It was right to do so, but I felt that if there is no need of default guard and also it was using users table so I deleted).
Here is config/auth.php
'guards' => [
'student'=>[
'driver'=>'session',
'provider'=>'students'
],
'admin'=>[
'driver'=>'session',
'provider'=>'admins'
],
],
'providers' => [
'students'=>[
'driver'=>'eloquent',
'model'=>App\Student::class,
],
'admins'=>[
'driver'=>'eloquent',
'model'=>App\Admin::class,
]
So I have two guards student and admin.
Here is the admin model Admin.php
class Admin extends Authenticatable
{
use Notifiable;
protected $fillable = [
'firstname', 'lastname','admin_id', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
and model Student Student.php
class Student extends Authenticatable
{
use Notifiable;
protected $fillable = [
'firstname', 'lastname','admin_id', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
After this I modified AdminController.php
class AdminsController extends Controller
{
use AuthenticatesUsers;
protected $guard = 'admin';
public function showLogin(){
return view('admin.login');
}
public function dashboard(){
return view('admin.dashboard');
}
public function login(Request $request){
$this->validate($request,[
'admin_id' => 'required',
'password'=>'required|min:8',
]);
if(Auth::guard('admin')->attempt(['admin_id'=>$request['admin_id'], 'password'=>$request['password']])){
return redirect('admin/dashboard');
}
return redirect('/admin');
}
}
Then I created routes Web.php
Route::get('/', function () {
return view('welcome');
});
Route::get('/admin','AdminsController#showLogin');
Route::get('/student','StudentsController#showLogin');
Route::get('/admin/dashboard','AdminsController#dashboard');
Route::get('/student','StudentsController#showLogin');
Route::post('/admin/login','AdminsController#login');
Route::post('/student/login','StudentsController#login');
Now, at this time login works. I still need to do a lot. If any suggestion, I welcome that, please comment below.

Laravel - Multiple Authentication

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.

Resources