In my project, I just need one authentication for admins and not for users and also have users table in my database but I don't want to use it in the authentication and in Admins table I want to use 'AD_AdminEmail' field as email and 'AD_AdminPassword' as authentication password and admins routes separated to management.php file.
These codes below not working and no errors but they redirect me to the login page again and Passwords in database hashed with laravel Hash::make() but Auth::attempt do not recognize it as hashed one and send a select query with plain password not hashed yet.
Here are My web route Codes:
Route::get('/login', [ 'as' => 'login', 'uses' => function() {
return view('LoginAndRegister');
}])->name('login');
Route::post('/ManagerLogin', 'Auth\LoginController#Authenticate');
Here are My LoginController Codes:
<?php
namespace App\Http\Controllers\Auth;
use App\Admin;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function username()
{
return 'AD_AdminEmail';
}
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function credentials(Request $request)
{
return $request->only($this->username(), 'AD_AdminPassword');
}
protected function validateLogin(Request $Request){
$this->validate($Request, [
$this->username() => 'required|email,',
'AD_AdminPassword' => 'required|min:8',
]);
}
public function Show()
{
return view('LoginAndRegister');
}
public function Authenticate(\Illuminate\Http\Request $Request)
{
$AdminEmail = $Request->input('AD_AdminEmail');
$AdminPassword = $Request->input('AD_AdminPassword');
if (Auth::attempt([
'AD_AdminEmail' => $AdminEmail,
'AD_AdminPassword' => $AdminPassword
], false))
echo 200 . "OK";
else
echo 400 . "Problem Found";
}
public function Logout()
{
Session::flush();
Auth::logout();
return back();
}
}
Here are My Admin model Codes:
<?php
namespace App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
protected $fillable = ['AD_AdminEmail', 'AD_AdminPassword'];
protected $hidden = ['AD_AdminId', 'remember_token',];
protected $primaryKey = 'AD_AdminId';
protected $guarded = ['AD_AdminId'];
protected $table = 'Admins';
use Notifiable;
public function getEmailAttribute() {
return $this->AD_AdminEmail;
}
public function setEmailAttribute($Value)
{
$this->attributes['AD_AdminEmail'] = strtolower($Value);
}
public function getAuthPassword()
{
return $this->AD_AdminPassword;
}
public function setPasswordAttribute($Value)
{
$this->attributes['password'] = bcrypt($Value);
}
}
Here are My config>auth.php Codes:
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'admins',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'users' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
'passwords' => [
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
Related
I'm using laravel breeze as auth scaffolding package.I want to create Multiple Authentication using laravel guards for two different registration form for two User Types (Admin, User).
The Main Idea of what I want to achieve :
I have two tables in the database one for admins and another for users what I want to achieve is if the admins choose to register an account as admin it will display a register form with specified fields for admin. after that I want to check if the user is logged in as admin or user if is logged in as admin is will redirect him/her to specified dashboard made only for admins.
It works fine for registration, but can't login as a admin here is a simple explanation of what I want to achieve:
app\Models\Admin.php
<?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 Admin extends Authenticatable
{
use HasFactory, Notifiable;
protected $table = 'admins';
protected $fillable = [
'name',
'email',
'password',
];
config\auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
// Admin guards
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
app\Http\Middleware\RedirectIfAuthenticated.php
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
// dd($guards);
foreach ($guards as $guard) {
switch ($guard) {
case 'admin':
if (Auth::guard($guard)->check()) {
return redirect()->route('admin.dashboard');
}
break;
default:
if (Auth::guard($guard)->check()) {
return redirect('/dashboard');
}
break;
}
}
return $next($request);
}
}
routes\web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\RegisteredUserController;
use App\Http\Controllers\Admin\AuthenticatedSessionController;
Route::get('/', function () {
return view('welcome');
});
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth'])->name('dashboard');
require __DIR__ . '/auth.php';
Route::get('admin/dashboard', function () {
return view('backend.dashboard');
})->middleware(['auth:admin'])->name('admin.dashboard');
Route::get('/admin-register', [RegisteredUserController::class, 'create'])
->middleware('guest:admin')
->name('admin.register');
Route::post('/admin-register', [RegisteredUserController::class, 'store'])
->middleware('guest:admin');
Route::get('/admin-login', [AuthenticatedSessionController::class, 'create'])
->middleware('guest:admin')
->name('admin.login');
Route::post('/admin-login', [AuthenticatedSessionController::class, 'store'])
->middleware('guest:admin');
Route::post('/admin-logout', [AuthenticatedSessionController::class, 'destroy'])
->name('admin.logout')
->middleware('auth:admin');
app\Http\Controllers\Admin\AuthenticatedSessionController.php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthenticatedSessionController extends Controller
{
public function create()
{
return view('admin.login');
}
public function store(LoginRequest $request)
{
$request->authenticate();
$request->session()->regenerate();
return redirect('admin/dashboard');
}
public function destroy(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
app\Http\Controllers\Admin\RegisteredUserController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class RegisteredUserController extends Controller
{
public function create()
{
return view('admin.register');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|confirmed|min:8',
]);
Auth::login($user = Admin::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]));
event(new Registered($user));
return redirect('admin/dashboard');
}
}
app\Http\Requests\Admin\LoginRequest.php
<?php
namespace App\Http\Requests\Admin;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class LoginRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'email' => 'required|string|email',
'password' => 'required|string',
];
}
public function authenticate()
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->filled('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => __('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
public function ensureIsNotRateLimited()
{
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return;
}
event(new Lockout($this));
$seconds = RateLimiter::availableIn($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.throttle', [
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
public function throttleKey()
{
return Str::lower($this->input('email')).'|'.$this->ip();
}
}
After 3 days effort i found a solution myself.
In the function authenticate() in app\Http\Requests\Admin\LoginRequest.php. I have replaced Auth::attempt(...) by Auth::guard('admin')->attempt(...)
public function authenticate()
{
$this->ensureIsNotRateLimited();
if (! Auth::guard('admin')->attempt($this->only('email', 'password'), $this->filled('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => __('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
Now it works fine for admin login and register
Ok, so my project is a bit different and not gives a 100% answer but I decided to
leave these here, it may help someone
app/Http/Requests/Auth/LoginRequest.php
public function authenticate()
{
$this->ensureIsNotRateLimited();
if (!Auth::attempt($this->only('email', 'password'), $this->filled('remember')) ||
!auth()->user()->isAdmin() <------------ added
) {
Auth::logout(); <------------ added
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => __('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
I added the 'isAdmin' function to the user model, it isn't pre built
I'm trying to make an authentication in laravel with multiple tables to separate user roles, is an academic exercise, so I can't do it any other way.
BadMethodCallException
Method App\Http\Controllers\Auth\RegisterController::create does not exist.
This error comes up when I try to register a user in the database. I understand that this is when the redirection occurs.
So... these are my routes from web.php:
use Illuminate\Support\Facades\Route;
use App\Http\Controllers;
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/login/admin', [App\Http\Controllers\Auth\LoginController::class,'showAdminLoginForm']);
Route::get('/login/user', [App\Http\Controllers\Auth\LoginController::class,'showUserLoginForm']);
Route::get('/register/admin', [App\Http\Controllers\Auth\RegisterController::class,'showAdminRegisterForm']);
Route::get('/register/user', [App\Http\Controllers\Auth\RegisterController::class,'showUserRegisterForm']);
Route::post('/login/admin', [App\Http\Controllers\Auth\LoginController::class,'adminLogin']);
Route::post('/login/user', [App\Http\Controllers\Auth\LoginController::class,'userLogin']);
Route::post('/register/admin', [App\Http\Controllers\Auth\RegisterController::class,'createAdmin']);
Route::post('/register/user', [App\Http\Controllers\Auth\RegisterController::class,'createUser']);
Route::view('/home', 'home')->middleware('auth');
Route::view('/admin', 'admin');
Route::view('/user', 'user');
This is the RegisterController from App\Controllers\Auth\RegisterController:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use App\Models\Admin;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest');
$this->middleware('guest:admin');
$this->middleware('guest:user');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
//USER STUFF
protected function createUser(Request $request)
{
$this->validator($request->all())->validate();
$user = User::create([
'username' => $request['username'],
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password']),
]);
return redirect()->intended('login/user');
}
public function showUserRegisterForm()
{
return view('auth.register', ['url' => 'user']);
}
//ADMIN STUFF
protected function createAdmin(Request $request)
{
$this->validator($request->all())->validate();
$admin = Admin::create([
'username' => $request['username'],
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password']),
]);
return redirect()->intended('login/admin');
}
public function showAdminRegisterForm()
{
return view('auth.register', ['url' => 'admin']);
}
}
Also I think that this is necessary, the auth.php file, where guards are defined:
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
'hash' => false,
],
'user' => [
'driver' => 'session',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
Models for user and admin:
User:
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 User extends Authenticatable
{
use HasFactory, Notifiable;
protected $guard = 'user';
protected $fillable = [
'username',
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Admin:
<?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 User extends Authenticatable
{
use HasFactory, Notifiable;
protected $guard = 'admin';
protected $fillable = [
'username',
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
I'm not sure if I forgot something, but I've been stuck in the same error for several hours and I can't see what I'm doing wrong... In any case I will edit this with the necessary information if I have forgotten something.
In case it is necessary and to provide more information that I think is important, I'll add the link to the tutorial that I've been following, if someone knows how to fix it, or finds the bug.
https://pusher.com/tutorials/multiple-authentication-guards-laravel
I am enhancing a system with a user login present (for staffs) and I want to create another login instance for clients.
So I have set up the guards and coded the rest as follows
// config/auth.php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'client' => [
'driver' => 'session',
'provider' => 'clients',
],
'client-api' => [
'driver' => 'token',
'provider' => 'clients',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'clients' => [
'driver' => 'eloquent',
'model' => App\Client::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
// app/Client.php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Client extends Authenticatable
{
use Notifiable;
protected $guard = 'clients';
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
// routes/web.php
Route::prefix('/client')->name('client.')->namespace('Client')->group(function(){
Route::namespace('Auth')->group(function(){
//Login Routes
Route::get('/login','LoginController#showLoginForm')->name('login');
Route::post('/login','LoginController#login');
Route::post('/logout','LoginController#logout')->name('logout');
});
Route::get('/', 'HomeController#index')->name('home');
});
// app/Http/Controllers/Client/Auth/LoginController.php
namespace App\Http\Controllers\Client\Auth;
use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
public function showLoginForm() {
return view('auth.client.login');
}
public function login(Request $request) {
$this->validator($request);
if(Auth::guard('client')->attempt(['CustomerNo' => $request->username, 'password' => $request->password],$request->filled('remember'))) {
return redirect()
->intended(route('client.home'))
->with('status','You are Logged in as Admin!');
}
return $this->loginFailed();
}
private function validator(Request $request)
{
$rules = [
'username' => 'required|exists:clients,CustomerNo',
'password' => 'required',
];
$messages = [
'username.exists' => 'These credentials do not match our records.',
];
$request->validate($rules,$messages);
}
private function loginFailed(){
return redirect()
->back()
->withInput()
->with('error','Login failed, please try again!');
}
public function logout()
{
Auth::guard('client')->logout();
return redirect()
->route('client.login')
->with('status','You are logged out!');
}
}
// app/Http/Middleware/Authenticate.php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
protected function redirectTo($request)
{
if (Auth::guard('client')->check()) {
return redirect('/client');
} else {
return redirect('/home');
}
if (! $request->expectsJson()) {
return route('login');
}
}
}
// app/Http/Middleware/RedirectIfAuthenticated.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if ($guard == "client" && Auth::guard($guard)->check()) {
return redirect(route('client.home'));
}
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
}
// app/Http/Controllers/Client/HomeController.php
namespace App\Http\Controllers\Client;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth:client');
}
public function index()
{
return view('client.home');
}
}
I have tried to login after finishing all this but it seems to keep redirecting me back to staff's (default user login) login page and a quick check at the session dd
#session: Store {#195 ▼
#id: "wQTohtl4aNaSZvYZ9ru3oqltcSqs4VhWb4SV42t2"
#name: "portal_session"
#attributes: array:5 [▼
"_token" => "R6EyBlq0iNyfDh1V8Ogmta6U3uOhvJ0gcj7a2RMb"
"url" => array:1 [▼
"intended" => "https://mywebsite.com/home"
]
"_flash" => array:2 [▼
"old" => []
"new" => []
]
"_previous" => array:1 [▼
"url" => "https://mywebsite.com/client/login"
]
"login_client_59ba36addc2b2f9401580f014c7f58ea4e30989d" => 1
]
#handler: FileSessionHandler {#194 ▼
#files: Filesystem {#95}
#path: "/home/mywebsite/storage/framework/sessions"
#minutes: 1440
}
#started: true
}
Is there any part where i did wrongly? Any advice is appreciated. Thanks in advance.
I use Lavarel 5.2 framework with jwt for authorization
jwt takes user info form token just with one model,
now how can i parse user token with jwt on multiple model?
For sample when i use customer token in a api jwt parse that token from customer model , default guard should be customer
auth.php :
'defaults' => [
'guard' => 'operator',
'passwords' => 'operators',
],
'guards' => [
'operator' => [
'driver' => 'session',
'provider' => 'operators',
],
'customer' => [
'driver' => 'session',
'provider' => 'customers',
],
'biker' => [
'driver' => 'session',
'provider' => 'bikers',
]
],
'providers' => [
'operators' => [
'driver' => 'eloquent',
'model' => App\Http\Services\Auth\Model\User::class,
],
'customers' => [
'driver' => 'eloquent',
'model' => App\Http\Aggregate\Customer\Model\Customer::class,
],
'bikers' => [
'driver' => 'eloquent',
'model' => App\Http\Aggregate\Biker\Model\Biker::class,
]
],
You can create a separate middleware like AuthModel. In that you can set the config to take which providers like the below,
Config::set('auth.providers.users.model',\App\Models\Customer::class);
If you want to use multiple models, then need to use if conditions to check which url can access which models. It can be like,
if(url == '/customer/api/') {
Config::set('auth.providers.users.model',\App\Models\Customer::class);
} else if(url == '/biker/api/') {
Config::set('auth.providers.users.model',\App\Models\Biker::class);
}
In the above example, I have used url just for example, so get it from the request.
You can change the __construct function in each of your controllers as follows. So that jwt know which model to authenticate.
BikerController
function __construct()
{
Config::set('jwt.user', Biker::class);
Config::set('auth.providers', ['users' => [
'driver' => 'eloquent',
'model' => Biker::class,
]]);
}
CustomerController
function __construct()
{
Config::set('jwt.user', Customer::class);
Config::set('auth.providers', ['users' => [
'driver' => 'eloquent',
'model' => Customer::class,
]]);
}
This is my solution. Tested on Laravel 6
User Model
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use SoftDeletes;
use Notifiable;
public $incrementing = false;
protected $keyType = 'string';
protected $fillable =
[
];
protected $hidden =
[
'password',
'created_at',
'updated_at',
'deleted_at'
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
}
}
Teacher Model
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Tymon\JWTAuth\Contracts\JWTSubject;
class Teacher extends Authenticatable implements JWTSubject
{
use SoftDeletes;
use Notifiable;
public $incrementing = false;
protected $keyType = 'string';
protected $fillable =
[
];
protected $hidden =
[
'password',
'oldpassword',
'created_at',
'updated_at',
'deleted_at'
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
}
}
config/auth.php
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users'
],
'teacher-api' => [
'driver' => 'jwt',
'provider' => 'teachers'
],
],
AuthController function :
if (
$request->getRequestUri() ===
'OTHER_AUTH_ROUTE'
) {
$credentials = $request->only('username', 'password']);
$token = Auth::shouldUse('teacher-api');
$token = Auth::attempt($credentials);
if (!$token) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
$credentials = $request->only([USERNAME, 'password']);
$token = Auth::attempt($credentials);
if (!$token) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
Hope this can help you all at future
Laravel 8 compatible
For others still looking for a clean solution:
I would suggest manually configure the providers and guards in config/auth.php and not programmatically change any providers.
The next thing to make sure the right JWTSubject auth model is used, is to create different Middleware (don't forget to specify it in Kernel.php under $routeMiddleware) for a group of routes that has to be only accessible by a specific guard/auth model. Then a middleware handle function could look like this for a Manager model:
public function handle(Request $request, Closure $next) {
if (!($request->user('managers'))) abort(401);
Auth::shouldUse('managers');
return $next($request);
}
Then create another middleware for, let's say an Employee model and change the 'managers' guard value to 'employees' which you configured in config/auth.php.
In your routes/api.php you can specify a route group using (e.g.):
Route::group(['middleware' => 'management'], function() { });
In order to make this all work correctly, specify the guard when the auth()->attempt() function is called, e.g. auth('managers')->attempt($credentials)).
I am pretty new to laravel 5.2. Right now I am trying to create a custom login. I created the login html. And on submit, the function shows error
App\User cannot use Illuminate\Foundation\Auth\User - it is not a trait
I couldn't find what is the error. The codes are below
Routes.php
Route::post('/', 'Admin\LoginController#postLogin');
LoginController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Auth;
use Request;
class LoginController extends Controller {
public function index() {
return view('admin.login');
}
public function register() {
return view('admin.register');
}
public function postLogin() {
$email = Request::input('email');
$password = Request::input('password');
if (Auth::attempt(['email' => $email, 'password' => $password])) {
//echo "success";
return redirect('admin/dashboard');
} else {
return redirect('/');
}
}
}
User.php
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable,
CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['keyword', 'remember_token'];
}
Auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'users' => [
'driver' => 'eloquent',
'model' => 'App\User',
'table' => 'users',
'password' => [
'email' => 'emails.password',
'expire' => 60,
],
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
I am following the tutorial from here
Please help me. I am stuck here from last few hours
You should use this namespace:
use Illuminate\Auth\Authenticatable;
It's a trait you should use. Now, you're trying to use a class as a trait:
use Illuminate\Foundation\Auth\User as Authenticatable;
class User {
use Authenticatable ...