in my laravel project, I have two users (Admins and Users).
I got started admins' authentification.
Now when I go to a create page (http://127.0.0.1:8000/admin/posts/create) in my CRUD application, it redirects to http://127.0.0.1:8000/login.
I am glad if someone gives me a solution to go back to http://127.0.0.1:8000/admin/login page which is admin side login page.
Here is my codes.
web.php
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::resource('categories','CategoriesController');
Route::resource('posts', 'PostsController')->middleware('auth');
Route::get('trashed-posts', 'PostsController#trashed')->name('trashed-posts.index');
Route::PUT('restore-post/{post}', 'PostsController#restore')->name('restore-posts');
});
VerifyCategoriesCount.php in my middleware folder
public function handle($request, Closure $next)
{
if (Auth::check()) {
if (Auth::user()->role == 'Admin') {
return $next($request);
}
}
return redirect('/admin/');
}
kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'verifyCategoriesCount' => VerifyCategoriesCount::class
];
postsController.php
public function __construct()
{
$this->middleware('VerifyCategoriesCount')->only('store');
$this->middleware('admin')->except('index');
}
Add an admin guard in auth.php
'admin' => [
'driver' => 'session',
'provider' => 'admins', //table name
],
And add providers array
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class, //Bind your Admin Model
],
Add two middleware,
class AdminRedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::guard('admin')->check()) {
return redirect('/admin/home');
}
return $next($request);
}
}
And
class AdminRedirectIfNotAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!Auth::guard('admin')->check()) {
return redirect('/admin/login');
}
return $next($request);
}
}
Register your middlewares in kernel.php
'admin.auth' => \App\Http\Middleware\AdminRedirectIfNotAuthenticated::class,
'admin.guest' => \App\Http\Middleware\AdminRedirectIfAuthenticated::class,
In your AdminController.php add,
public function __construct()
{
$this->middleware('admin.auth');
}
And,
In your LoginController.php add,
public function __construct()
{
$this->middleware('admin.guest');
}
In web.php
Route::get('/admin/login', 'Admin\LoginController#showLoginForm')->name('admin.login');
Route::get('/admin/home', 'Admin\AdminController#home')->name('home');
Related
I'm trying to create an Admin Login in Laravel Jetstream. I've created a separate admins table to store the login data. However, I get an error saying Auth guard [ admin] is not defined when I try to access the admin login page through http://localhost:8000/admin/login.
I tried php artisan config:clear and php artisan config:cache commands, but they didn't solve the issue.
auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'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,
],
],
web.php
Route::get('/', function () {
return view('welcome');
});
Route::group(['prefix' => 'admin', 'middleware' => ['admin:admin']], function () {
Route::get('/login', [AdminController::class, 'loginForm']);
Route::post('/login', [AdminController::class, 'store'])->name('admin.login');
});
Route::middleware(['auth:sanctum, admin', config('jetstream.auth_session'), 'verified'])->group(function () {
Route::get('/admin/dashboard', function () {
return view('dashboard');
})->name('dashboard');
});
Route::middleware(['auth:sanctum, web', config('jetstream.auth_session'), 'verified'])->group(function () {
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
});
AdminController
public function loginForm()
{
return view('auth.login', ['guard' => 'admin']);
}
AdminRidirectIfAuthenticated.php
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect($guard . '/dashboard');
}
}
return $next($request);
}
LoginResponse.php
public function toResponse($request)
{
return $request->wantsJson()
? response()->json(['two_factor' => false])
: redirect()->intended('admin/dashboard');
}
Kernel.php
protected $routeMiddleware = [
'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,
'admin' => \App\Http\Middleware\AdminRedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
FortifyServiceProvider.php
use App\Http\Controllers\AdminController;
use Illuminate\Contracts\Auth\StatefulGuard;
use Illuminate\Support\Facades\Auth;
use App\Actions\Fortify\AttemptToAuthenticate;
use App\Actions\Fortify\RedirectIfTwoFactorAuthenticatable;
public function register()
{
$this->app->when([AdminController::class, AttemptToAuthenticate::class, RedirectIfTwoFactorAuthenticatable::class])
->needs(StatefulGuard::class)
->give(function () {
return Auth::guard('admin');
});
}
login.blade.php
<form method="POST" action="{{ isset($guard) ? url($guard.'/login') : route('login') }}">
#csrf
..............
</form>
AdminStatefulGuard.php
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Guard;
interface AdminStatefulGuard extends Guard
{
/**
* Attempt to authenticate a user using the given credentials.
*
* #param array $credentials
* #param bool $remember
* #return bool
*/
public function attempt(array $credentials = [], $remember = false);
/**
* Log a user into the application without sessions or cookies.
*
* #param array $credentials
* #return bool
*/
public function once(array $credentials = []);
/**
* Log a user into the application.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param bool $remember
* #return void
*/
public function login(Authenticatable $user, $remember = false);
/**
* Log the given user ID into the application.
*
* #param mixed $id
* #param bool $remember
* #return \Illuminate\Contracts\Auth\Authenticatable|bool
*/
public function loginUsingId($id, $remember = false);
/**
* Log the given user ID into the application without sessions or cookies.
*
* #param mixed $id
* #return \Illuminate\Contracts\Auth\Authenticatable|bool
*/
public function onceUsingId($id);
/**
* Determine if the user was authenticated via "remember me" cookie.
*
* #return bool
*/
public function viaRemember();
/**
* Log the user out of the application.
*
* #return void
*/
public function logout();
}
Remove space before middleware parameter at web.php
Remove space before admin at 'auth:sanctum, admin'
I was wondering if there is a way to restrict access to routes-blades at certain hours or minutes within a day ?
Any documentation about this topic ?
Create a middleware
php artisan make:middleware TimeBasedRestriction
Return a different response or redirect if time isn't appropriate
<?php
namespace App\Http\Middleware;
use Closure;
class TimeBasedRestriction
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
// if not working hours, access forbidden
if (!now()->isBetween('09:00:00', '16:00:00')) {
return response()->json([
'message' => 'Day is over, come back tomorrow'
], 403); // Status forbidden
}
return $next($request);
}
}
Add the middleware to your route middleware in app\Http\Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'restrictedToDayLight' => \App\Http\Middleware\TimeBasedRestriction::class,
];
And add it to your restricted routes in web.php for example
Route::get('/', function () {
return view('welcome');
})->middleware('restrictedToDayLight');
Something wrong with my custom middleware. It doesn't work. I have registered it in Kernel.php , the routeMiddleware array.
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
// 'jwt.auth' => Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => Tymon\JWTAuth\Middleware\RefreshToken::class,
'upload.file' => \App\Http\Middleware\Upload::class,
'admin.settings' => \App\Http\Middleware\AdminChange::class,
];
And in my middle , I used dd to print sth
class AdminChange
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
dd('i\'m here');
config(['auth.providers.users.model' => '\App\Models\Useradmin::class']);
return $next($request);
}
}
And , my api group like this.
$api = app('Dingo\Api\Routing\Router');
$api->group([
'version' => 'v1',
'namespace' => 'App\Http\Controllers\Api',
],function($api){
$api->group([
'middleware'=>['admin.settings'],
'prefix'=>'ad'
],function($api){
include_once(base_path('routes/v1/admin/notice.php'));
});
$api->group([
'middleware' => ['api.auth']
],function($api){
});
});
I tried to rename the alias admin.settings to other names ,it still did not work.
I couldn't get i am here , it seemed the middleware didn't work. Does anyone help?
I have a view which should be accessed only by the users who have "role = interviewer" in the database.I have created the middleware and registered it but it doesn't seem to work as expected. It allows all the users irrespective of their role stored in the DB.
Here is my middleware
class Interviewer
{
public function handle($request, Closure $next)
{
if($request->user()->role == "interviewer"){
return $next($request);
}
}
}
I don't know if the approach is right i Have also tried
if($request->\Auth::user()->role == "interviewer")
This one also doesn't work. admin is the view it should be restricting if the user doesn't have the role interviewer. Here is my route
Route::get('/candidates', [
'uses' => 'candidateController#showProfile',
])->middleware('auth','interviewer');
My route middlewares
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'interviewer'=> \App\Http\Middleware\Interviewer::class,
];
You need to return something in your middleware if it needs to fail, in your case an error response.
namespace App\Core\Http\Middleware;
use Tymon\JWTAuth\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
class Employee extends BaseMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, \Closure $next, $role = null)
{
$user = $request->user();
if (! ($user->authenticable instanceof \App\Core\Entities\User)) {
return response([
'title' => 'You may not call this API as a non-employee.',
'error' => 'invalid_user_type'
], 401); // <-- See? I returned an error!
}
if ($role) {
if (strtolower($user->authenticable->role->name) !== strtolower($role)) {
return response([
'title' => "You may not call this API as a \"{$user->authenticable->role->name}\".",
'error' => 'unnecessary_permissions'
], 401); // And also here!
}
}
return $next($request);
}
}
In your middleware you always needs return to next($request)
class Interviewer {
public function handle($request, Closure $next) {
if($request->user()->role != "interviewer"){
return back();
}
return $next($request);
}
}
Also modify your routes.php. Middleware needs to be in an array:
Route::get('/candidates', [
'uses' => 'candidateController#showProfile',
])->middleware(['auth','interviewer']);
I am building an API with stateless HTTP basic authentication in Laravel 5.2, as per documentation Stateless HTTP Basic Authentication , I have created following Middleware
app/Http/Middleware/AuthenticateOnceWithBasicAuth.php
<?php
namespace Illuminate\Auth\Middleware;
use Auth;
use Closure;
class AuthenticateOnceWithBasicAuth
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
return Auth::onceBasic() ?: $next($request);
}
}
And then registered it in Kernel.php
app/Http/kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'auth.basic.once' => \App\Http\Middleware\AuthenticateOnceWithBasicAuth::class,
];
I am using it in route as follows
Route::group(['prefix' => 'admin', 'middleware' => 'auth.basic.once'], function () {
Route::get('service/create', function () {
return response()->json(['name' => 'Abigail', 'state' => 'CA'], 200);
});
});
But it is giving me
ReflectionException in Container.php line 734:
Class App\Http\Middleware\AuthenticateOnceWithBasicAuth does not exist
I have run following commands but with no success
composer dump-autoload
php artisan clear-compiled
php artisan optimize
Any help would be much appreciated. Thanks in advance.
Well first of all look at the namespaces:
namespace Illuminate\Auth\Middleware;
you should rename it to:
namespace App\Http\Middleware;
in the middleware you need to do something like this:
public function handle($request, Closure $next) {
if (!Auth::onceBasic()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}