I am trying to authenticate admin in Laravel project. my auth.php as shown below:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
AdminController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function adminLogin(){
return view('auth.adminLogin');
}
public function cheackAdminLogin(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('admin')->attempt(['email' => $request->email,
'password' => $request->password])) {
return redirect()->intended('/admin');
}
return back()->withInput($request->only('email')); */
}
}
AdminDashboardController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AdminDasboardController extends Controller
{
public function adminPanel()
{
return view('adminPanel');
}
}
The problem that I encountered that when I want to check the admin login, the attempt() function when I wrote it, I get an error message in the editor "Undefined Method".
I tried to using auth()->guard('admin')->attempt() instead of Auth::guard('admin')->attempt but the problem is same.
please help
It may be a problem of type hint
use Illuminate\Auth\SessionGuard;
/** #var SessionGuard $adminGuard */
$adminGuard = Auth::guard("admin");
if ($adminGuard->attempt($credentials)) {
...
Related
I use JWT for API authentication in Laravel 8.
When I use auth()-> in my controller , for factory() or attemp() or anything, Laravel does not know it and says:
Undefined method 'attempt'.intelephense(1013)
I don't know what I forgot to include
my AuthController :
namespace App\Http\Controllers\Api\Admin;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
public function __construct() {
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
public function login(Request $request){
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
if (! $token = auth()->attempt($validator->validated())) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->createNewToken($token);
}
.
.
.
.
.
and my config/auth.php file :
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// Following array is newly added to config
'otp-user' => [
'driver' => 'otp-based-auth-provider'
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
Intelephense has some trouble dealing with some methods in Laravel. You can either ignore it, as it should work or you can call it by:
JWTAuth::attempt($validator->validated)
It should make the error go away.
I'm trying to implement auth in Laravel via Sanctum. I did all steps from documentation. Generation of Token works fine but when I try to use auth:sanctum middleware it returns the error Auth guard [sanctum] is not defined.
Here are my files:
/routes/api.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Dashboard;
Route::middleware('auth:sanctum')->get('/dashboard/get_current_client/', [Dashboard::class, 'get_current_client']);
Route::get('/dashboard/client_data/', [Dashboard::class, 'client_data']);
/config/auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\Client::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
/app/Models/Client.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Client extends Authenticatable
{
use HasFactory, HasApiTokens, Notifiable;
protected $table = 'client';
protected $primaryKey = 'client_id';
public $timestamps = false;
}
/app/Http/Controllers/Dashboard.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Client;
class Dashboard extends Controller
{
public function client_data () {
$user = Client::where('client_id', 1)->first();
return $user->client_id;
}
public function get_current_client(Request $request) {
var_dump($request->user());
}
}
I found the problem. For some reason cache in /bootstrap/cache has not updated. After manual removing it, everything started working.
to fix it add the below code to file "/bootstrap/cache/packages.php"
'laravel/sanctum' => array (
'providers' =>
array (
0 => 'Laravel\\Sanctum\\SanctumServiceProvider',
), ),
I hope my english is good enough to explain my problem. I'm working with laravel 7, and I'm trying to implement my own AuthController, because I can't use migrations and I can't use a table 'users' because I have a db implemented. I've read all the documentation of laravel about authentication and spent days reading a lot of posts with this problem, and I tried everything but still does not work. The problem is with the attempt method. My register method is working fine, but I can't login, actually I tried to put manually the data(that's why credentials are commented) to find the problem but I don't know why is not working
My Regsiter method.
public function storeUser(Request $request)
{
//dd($request);
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:administradores,ADMIN_Correo',
'password' => 'required|string|min:8|confirmed',
'password_confirmation' => 'required',
]);
Administrador::create([
'ADMIN_Nombre' => $request->name,
'ADMIN_Correo' => $request->email,
'ADMIN_Contrasena' => Hash::make($request->password),
]);
//return redirect('home');
}
My Login method.
public function authenticate(Request $request)
{
/*$request->validate([
'ADMIN_Correo' => 'required|string|email',
'ADMIN_Contrasena' => 'required|string',
]);*/
//$credentials = $request->only('ADMIN_Correo', 'ADMIN_Contrasena');
if (Auth::guard('admin')->attempt(['ADMIN_Correo' => 'edwin2#gmail.com
','ADMIN_Contrasena' => '12345678'])) {
return redirect()->intended('home');
}else{
echo 'error';
}
//return redirect('login')->with('error', 'Oppes! You have entered invalid credentials');
}
My config/auth.php file
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
]
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Administrador::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Administrador::class,
],
],
My Model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Administrador extends Authenticatable
{
use Notifiable;
protected $table = 'administradores';
protected $primaryKey = 'ADMIN_Id';
public $timestamps = false;
public $incrementing = true;
protected $fillable = ['ADMIN_Nombre','ADMIN_Correo','ADMIN_Contrasena'];
protected $guard = 'admin';
public function getAuthPassword()
{
return $this->ADMIN_Contrasena;
}
}
NOTES The field for password:(ADMIN_Contrasena) is varchar 255
I'm having some problems with Laravel 5.7 multi-auth implementation.
I have created a new table for backend login: "AdminUsers".
So, I modified auth.php file:
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => Ecommerce\User::class,
],
'admins' => [
'driver' => 'eloquent',
'table' => Ecommerce\AdminUser::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Then, I create the AdminLoginController class:
<?php
namespace Ecommerce\Http\Controllers\Admin\Auth;
use Illuminate\Http\Request;
use Ecommerce\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class AdminLoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/index';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function showLoginForm()
{
return view('admin.auth.login');
}
protected function attemptLogin(Request $request)
{
return $this->guard('admin')->attempt(
$this->credentials($request), $request->filled('remember')
);
}
protected function authenticated(Request $request, $user)
{
dd('authenticated!');
}
public function username()
{
return 'username';
}
}
I setted this routes in routes file:
Route::get ('/login', ['uses'=>'Auth\AdminLoginController#showLoginForm'])->name('login_page');
Route::post('/login', ['uses'=>'Auth\AdminLoginController#login' ])->name('do_login' );
The problem is, that when I do login, Laravel tries to use "users" guard instead of the defined "admin" guard. So that throw a SQL error (because I have not created the "Users" table in the DB).
Even if I do var_dump($this->guard('admin')) inside AdminLoginController::attemptLogin method, the response gives me a SessionGuard object with "Ecommerce\User" instead of "Ecommerce\AdminUser" that is the one defined as "admin" in auth.php guard array.
Anyone knows where else can I look to solve this?
Thanks!
The problem lies in your auth.php providers section.
'table' => Ecommerce\AdminUser::class
'table' should be replaced with 'model'.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
Does anyone know how to use multi authenticate in laravel 5.2 ! I want to use It but I don't know how ?
does anyone has a tutorial or project setting up multi authentication?
You need two tables users and admins
Run command following command to create built in auth
php artisan make:auth
Two models Users(Already exist) and Admin
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
}
Now open config/auth.php and make the following changes
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
Create a new Middleware RedirectIfNotAdmin
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfNotAdmin
{
/**
* 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 = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/admin/login');
}
return $next($request);
}
}
Changes in Kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
//\Illuminate\Session\Middleware\StartSession::class,
//\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
Create a new folder Http/Controller/Adminauth and copy the files from Http/Controller/Auth folder
Open the file Http/Controller/Adminauth/AuthController.php and make the following changes
<?php
namespace App\Http\Controllers\Adminauth;
use App\Admin;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Auth;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (Auth::guard('admin')->check())
{
return redirect('/admin');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
public function resetPassword()
{
return view('admin.auth.passwords.email');
}
public function logout(){
Auth::guard('admin')->logout();
return redirect('/admin/login');
}
}
Create new folder Http/Controller/admin, copy Controller.php file in the folder from Http/Controller/
create new file Http/Controller/admin/employee.php
<?php
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Auth;
use App\Admin;
class Employee extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.home');
}
}
move to resources/views create new folder resources/views/admin
copy
resources/views/auth, resources/views/layouts & resources/views/home.blade.php
and post into resources/views/admin and open the each file in admin folder and add admin before each path, Now the path should look like
#extends('admin.layouts.app')
and your Http/routes.php look like
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/admin/login','Adminauth\AuthController#showLoginForm');
Route::post('/admin/login','Adminauth\AuthController#login');
Route::get('/admin/password/reset','Adminauth\PasswordController#resetPassword');
Route::group(['middleware' => ['admin']], function () {
//Login Routes...
Route::get('/admin/logout','Adminauth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'Adminauth\AuthController#showRegistrationForm');
Route::post('admin/register', 'Adminauth\AuthController#register');
Route::get('/admin', 'Admin\Employee#index');
});
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/home', 'HomeController#index');
});
Thats it open your site in browser and check
and for admin yoursiteurl/admin
Enjoy....
First, we create two models: user and admin
Then, we update the config/auth.php file:
return [
'defaults' => [
'guard' => 'user',
'passwords' => 'user',
],
'guards' => [
'user' => [
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => 'App\User',
],
'admin' => [
'driver' => 'eloquent',
'model' => 'App\Admin',
],
],
'passwords' => [
'user' => [
'provider' => 'user',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admin' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
]
]
];
Now, modify the app/Http/kernel.php file:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class
],
'api' => [
'throttle:60,1',
],
];
Create LoginController and set the following code in it.
Note: You have to create login pages for 'user' as well as 'admin'. You then have to submit login form requests to the appropriate controller function i.e. userLogin() or adminLogin().
namespace App\Http\Controllers;
use Auth, Input;
use App\User;
use App\Admin;
class LoginController extends Controller
{
public function userLogin(){
$input = Input::all();
if(count($input) > 0){
$auth = auth()->guard('user');
$credentials = [
'email' => $input['email'],
'password' => $input['password'],
];
if ($auth->attempt($credentials)) {
return redirect()->action('LoginController#profile');
} else {
echo 'Error';
}
} else {
return view('user.login');
}
}
public function adminLogin(){
$input = Input::all();
if(count($input) > 0){
$auth = auth()->guard('admin');
$credentials = [
'email' => $input['email'],
'password' => $input['password'],
];
if ($auth->attempt($credentials)) {
return redirect()->action('LoginController#profile');
} else {
echo 'Error';
}
} else {
return view('admin.login');
}
}
public function profile(){
if(auth()->guard('admin')->check()){
pr(auth()->guard('admin')->user()->toArray());
}
if(auth()->guard('user')->check()){
pr(auth()->guard('user')->user()->toArray());
}
}
}
In most cases I just add a field to the user table called usertype and pass appropriate values like 0=admin, 1=user etc.
This approach helps in avoiding the unnecessary headache of creating different user roles or types.
Though this may not sound ideal, but helps in saving lots of time.