I have an issue with authentication in laravel web, I only what to use the JWT authentication for the api only, I notice whenever I change guard in defaults to web 'guard' => 'web' and I try to login with postman using my api it will not work and this error show("message": "Method Illuminate\Auth\SessionGuard::factory does not exist.") but the web will work, if I change it to 'guard' => 'api' I will not be able to login in the web but the api postman login will work.
Only web will work
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Only api will work
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Route
Route::group([
'prefix' => 'auth'
], function () {
Route::post('login', [AuthController::class, 'login']);
Route::post('logout', [AuthController::class, 'logout']);
Route::post('refresh', [AuthController::class, 'refresh']);
Route::post('me', [AuthController::class, 'me']);
});
Controller
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if ($token = $this->guard()->attempt($credentials)) {
return $this->respondWithToken($token);
}
return response()->json(['error' => 'Unauthorized'], 401);
}
public function me()
{
return response()->json($this->guard()->user());
}
public function logout()
{
$this->guard()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
public function refresh()
{
return $this->respondWithToken($this->guard()->refresh());
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => $this->guard()->factory()->getTTL() * 60
]);
}
public function guard()
{
return Auth::guard();
}
}
I just want to use JWT authentication for only the api without affecting the web, Thanks
What defaults.guard config does is setting the default guard to be used if none specified.
If you want 2 different authentication methods and guards you should specify each by name in your middlewares.
So instead of Route::middleware('auth')->get(...);
you should write Route::middleware('auth:api')->get(...);
If you want to protect all routes in a group you can do it in app/Http/Kernel.php by adding this lines:
protected $middlewareGroups = [
'web' => [
...
'auth:web'
],
'api' => [
...
'auth:api'
],
];
you can use this
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
and in controller where you need api guard use this
auth('api')
for example in login controller
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('api')->attempt($validator->validated())) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$token = auth('api')->claims(['user' => auth('api')->user()])->attempt($validator->validated());
return $this->createNewToken($token);
}
i use this controller and works for me
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
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('api')->attempt($validator->validated())) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$token = auth('api')->claims(['user' => auth('api')->user()])->attempt($validator->validated());
return $this->createNewToken($token);
// return response()->json([
// 'token' => $this->createNewToken($token),
// ]);
}
/**
* Register a User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|between:2,100',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create(array_merge(
$validator->validated(),
['password' => bcrypt($request->password)]
));
return response()->json([
'message' => 'User successfully registered',
'user' => $user,
], 201);
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout()
{
Auth::logout();
return response()->json(['message' => 'User successfully signed out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->createNewToken(auth::refresh());
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function userProfile()
{
return response()->json(auth::user());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function createNewToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60,
'user' => auth('api')->user(),
]);
}
}
and routes
Route::prefix('user')->middleware('api')->group(function () {
Route::post('/login', [UserController::class, 'login']);
Route::post('/logout', [UserController::class, 'logout']);
Route::post('/refresh', [UserController::class, 'refresh']);
Route::get('/user-profile', [UserController::class, 'userProfile']);
Route::post('/register', [UserController::class, 'register']);
});
Related
Why does this error appears when the guard exists in auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'manager' => [
'driver' => 'jwt',
'provider' => 'managers',
],
'admin' => [
'driver' => 'jwt',
'provider' => 'admins',
],
],
And the providers also sets with right format. In the controller the register function is down below:
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'username' => 'required|string|max:255',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
$user = new Manager();
$user->username = $request->username;
$user->password = bcrypt($request->password);
$user->save();
$token = JWTAuth::guard('manager')->attempt($request->only('username', 'password'));
return response()->json(compact('user', 'token'));
}
The JWTMiddleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class JWTAuth
{
public function handle($request, Closure $next, $guard)
{
try {
$user = JWTAuth::parseToken()->authenticate($guard);
if (!$user) {
throw new \Exception('User not found');
}
} catch (\Exception $e) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $next($request);
}
}
In kernel.php I have included these inside aliases array:
'jwt.manager' => \App\Http\Middleware\JWTManagerMiddleware::class,
'jwt.admin' => \App\Http\Middleware\JWTAdminMiddleware::class,
'jwt.auth' => \App\Http\Middleware\JWTAuth::class,
What am I doing wrong and how can I solve this?
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 have used JWT in Laravel for user Authentication
Auth Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Auth\Events\Verified;
use Validator;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
class AuthController extends Controller
{
public function __construct() {
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
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(['status'=>true,'error_message' => 'Invalid Credentials'], 401);
}
return $this->createNewToken($token);
}
/**
* Register a User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function register(Request $request) {
$messages = [
'password.confirmed' => 'Password Confirmation should match the Password',
'password.min' => ' Password should be minimum 6 digits',
];
$validator = Validator::make($request->all(), [
'name' => 'required|string|between:2,100',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
],$messages);
if($validator->fails()){
return response()->json($validator->errors(), 422);
}
$user = User::create(array_merge(
$validator->validated(),
['password' => bcrypt($request->password)]
));
return response()->json([
'message' => 'Successfully registered',
], 201);
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout() {
auth()->logout();
return response()->json(['message' => 'User successfully signed out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh() {
return $this->createNewToken(auth()->refresh());
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function userProfile() {
return response()->json(auth()->user());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function createNewToken($token){
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'user' => auth()->user()
]);
}
}
routes :
Route::group([
'middleware' => ['api'],
'prefix' => 'auth'
], function ($router) {
Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);
Route::post('/logout', [AuthController::class, 'logout']);
Route::post('/refresh', [AuthController::class, 'refresh']);
Route::get('/user-profile', [AuthController::class, 'userProfile']);
Login and register is working
but when i access user-profile route getting this error :
Symfony\Component\Routing\Exception\RouteNotFoundException: Route
[login] not defined. in file
C:\wamp64\www\project\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php
on line 420
and i cannot get id of user if some user is logged in using : auth()->user()->id
auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
'admin' => [
'driver' => 'session',
'provider' => 'users',
],
],
Model :
<?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;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{ #HasFactory,
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
'otp',
'user_verification_token',
'verified',
'token',
'email_verified_at'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getJWTIdentifier() {
return $this->getKey();
}
public function getJWTCustomClaims() {
return [];
}
}
Any suggestion is highly appreciated
Thanks
Error message says there is no route that named as 'login'
Route::post('/login', [AuthController::class, 'login'])->name('login');
As the title says CreateFreshApiToken doesnt create any cookies. So I cant use it to auth a logged in user for other requests related to the user.
I tried to set a cookie on the response and it works perfectly fine. So this has to do something with CreateFreshApiToken not working.
AuthController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
class AuthController extends Controller
{
public function signup(Request $request)
{
$request->validate([
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string'
]);
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$user->save();
return response()->json([
'message' => 'Successfully created user!'
], 201);
}
public function signin(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string'
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
$token->save();
return response()->json([
'message' => 'Successfully signed in!'
]);
}
public function signout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([
'message' => 'Successfully signed out!'
]);
}
public function user(Request $request)
{
return response()->json($request->user());
}
public function test()
{
return response()->json([
'message' => 'test'
]);
}
public function test2(Request $request)
{
return response()->json([
'laravel_token' => $request->cookie('laravel_token')
]);
}
}
Kernel.php
protected $middlewareGroups = [
'web' => [
//...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
'api' => [
'throttle:60,1',
'bindings',
\Barryvdh\Cors\HandleCors::class,
],
];
api.php
Route::group([
'prefix' => 'auth'
], function () {
Route::post('signin', 'AuthController#signin');
Route::post('signup', 'AuthController#signup');
Route::get('test', 'AuthController#test');
Route::get('test2', 'AuthController#test2');
Route::group([
'middleware' => ['auth:api']
], function() {
Route::get('signout', 'AuthController#signout');
Route::get('user', 'AuthController#user');
});
});
And this is my angular code:
test() {
return this.http.get('http://homestead.test/api/auth/test', {withCredentials: true})
.subscribe(response => {
console.log(response);
});
}
test2() {
return this.http.get('http://homestead.test/api/auth/test2', {withCredentials: true})
.subscribe(response => {
console.log(response);
});
}
I've also setup cors with https://github.com/barryvdh/laravel-cors successfully with 'supportsCredentials' enabled. I am also sending a useless GET request to see if any laravel_token is set in the cookie but no success.
CreateFreshApiToken is part of the web middleware group, so in order for it to set cookies you need your login page to be a web route (instead of an api route).
I resolved this part of the problem by replicating CreateFreshApiToken::handler in my login controller:
$response = response()->json([], 200);
// ADD THIS LINE:
$response->cookie(\Laravel\Passport\Passport::cookie(),$request->session()->token();
return $response;
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,
];