Laravel authentication for register - laravel

laravel authentication model
Is there any possible to make /register only you logged
How to make it with : (Auth::check()) ??

By default in construct of \app\Http\Controllers\Auth\AuthController.php we have middleware guest for all except logout:
public function __construct()
{
$this->middleware('guest', ['except' => [
'logout',
]
]);
}
Middleware guest link for:
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
And use handle method:
public function handle($request, Closure $next)
{
if ($this->auth->check())
{
return new RedirectResponse(url('/'));
}
return $next($request);
}
It's mean that everybody who try access all Auth method except logout will be redirected to main page.

You should look at middleware if your are at laravel 5: https://laravel.com/docs/master/middleware
And filters for laravel 4: https://laravel.com/docs/4.2/routing

Related

How can i register multiple middleware permissions in routegroup?-Laravel

I have 3 roles roles, admin, tutor and student. i want to place them in 3 different goups, i however want the admin to be in all the groups. I have tried different methods to add the admin to other routes but it's not working. How can i make admin use all routes in tutor's middleware? Here is my code
AdminMiddleware, similar to all the others
class AdminMiddleware
{
public function handle($request, Closure $next)
{
if(Auth::check() && Auth::user()->isRole()=="admin") {
return $next($request);
}
return redirect('login');
}
}
routesmiddleware - in web.php
Route::group(['middleware'=>['auth'=>'admin']], function (){
//admin routes
}
Route::group(['middleware'=>['auth'=>'tutor']], function (){
//tutor routes
}
in the Kernel.php
'admin' => \App\Http\Middleware\AdminMiddleware::class,
'tutor' => \App\Http\Middleware\TutorMiddleware::class,
'student' => \App\Http\Middleware\StudentMiddleware::class,
in user model
public function isRole(){
return $this->role;
}
What you can do is define a middleware that takes the supported roles as argument:
class HasRoleMiddleware
{
public function handle($request, Closure $next, ...$roles)
{
if(Auth::check() && in_array(Auth::user()->getRole(), $roles)) {
return $next($request);
}
return redirect('login');
}
}
This middleware expects that User::getRole() returns the role as string, i.e. admin or tutor. Then you need to define the middleware in Kernel.php as you have already done:
'any_role' => \App\Http\Middleware\HasRoleMiddleware::class,
And finally you can use the middleware like this:
Route::group(['middleware' => 'auth'], function () {
Route::group(['middleware' => 'any_role:admin'], function () {
// admin routes
}
Route::group(['middleware' => 'any_role:admin,tutor'], function () {
// tutor routes
}
}
As you can see, I've also nested the route groups which perform role checks inside another route group which checks for authentication. This makes it more readable and reduces the risk you forget an authentication check in a future extension of your routes.

Laravel 5.4 Route [login] not defined

Hi I have following route and constructor in my controller i want to check if user is authenticated or not if not then redirect to /warehouse/login page. but for some reasons i am getting Route [login] not defined error.
I am migrating my functions from Laravel 4.2 to Laravel 5.4
Constructor:
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
if (!Auth::check()) {
$url = URL::current();
$routeName = Route::currentRouteName();
if ($routeName != "AdminLogin" && $routeName != 'admin') {
Session::put('pre_admin_login_url', $url);
}
return redirect('/warehouse/login');
}
return $next($request);
}, array('except' => array('WarehouseAdminLogin', 'WarehouseAdminVerify')));
}
Routes:
Route::get('/warehouse', 'WarehouseController#index');
Route::get('/warehouse/login', array('as' => 'WarehouseAdminLogin', 'uses' => 'WarehouseController#login'));
You didnt define your login function.
make a function
public function login()
{'your code'}
in your WarehouseController
Edited: the problem is that you have not a route named login. This error is caused by:
$this->middleware('auth');
because this code in the auth middleware:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
So what to do is remove auth middleware and try again or make a route with login name.

Auth::user() returns null on Module __construct()

I created a new Module named Article using laravel-modules. Some backend routes needed authentication and i added auth middleware and an additional permission view_backend. I am using https://github.com/spatie/laravel-permission package for role-permissions.
the issue is when i try to access the route admin/article/posts it prompts me the login as expected. But after login it show null on __construct() method for Auth::user();
I added web middleware as mentioned on #204 but it did not solve the issue. Can you please guide me to resolve this? My project is on Laravel 5.6 and using the latest version of Laravel-Modules
Route::group(['namespace' => 'Modules\Article\Http\Controllers\Backend', 'as' => 'backend.article.', 'middleware' => ['web', 'auth', 'can:view_backend'], 'prefix' => 'admin/article'], function () {
Route::resource("posts", "PostsController");
});
My project is hosted at Github, https://github.com/nasirkhan/laravel-starter/tree/module
First of all, add Spatie Middleware to your kernel:
protected $routeMiddleware = [
// ...
'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
];
Then in your controller check for permission or roles:
public function __construct(Request $request)
{
$this->middleware(['permission: order.index']);
}
Now you can access to your authenticated with $request->user() like:
public function create(Request $request)
{
if ($request->user()->hasRole('admin')) {
// return view("carmodel.create", ["manufacturers"=>$manufacturers]);
} else {
return view("admin.error", ['code'=>'001','msg'=>'err']);
}
}
According to the docs:
In previous versions of Laravel, you could access session variables or the authenticated user in your controller's constructor. This was never intended to be an explicit feature of the framework. In Laravel 5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.
As an alternative, you may define a Closure based middleware directly
in your controller's constructor. Before using this feature, make sure
that your application is running Laravel 5.3.4 or above:
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->projects = Auth::user()->projects;
return $next($request);
});
}
Or you could typehint it:
public function index(Request $request)
{
$projects = $request->user()->projects;
$value = $request->session()->get('key');
}
Docs

Laravel 5.4 redirect to specific page if user is not authenticated using middleware

I want to redirect user, if not authenticated, to my index page (which is the login page)
Can't seem to make it work and i really got confused with the routing.
HomeController
class HomeController extends Controller
{
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return redirect()->guest('/');
}
}
Routing
// Index
Route::get('/', [
'as' => 'index',
'uses' => 'UserController#index'
]);
UserController
The routing as you see redirects to a User Controller at index function, which is the below :
*has __construct() so it uses the middleware 'auth'.
public function __construct()
{
$this->middleware('auth');
}
public function index(){
// If user is logged
if(Auth::check()) {
// If user has NOT submitted information form redirect there, otherwise to categories
if(!Auth::user()->submitted_information)
return redirect()->route('information');
else
return redirect()->route('categories');
}
else
return view('index', ['body_class' => 'template-home']);
}
Handler.php
And the unauthenticated function inside middleware of auth (Exceptions/Handler.php)
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->route('index');
}
The error i get right now is the below :
InvalidArgumentException in UrlGenerator.php line 304:
Route [index] not defined.
This error happens because of the line of
return redirect()->route('index'); in the above unauthenticated function.
What am i missing here? If you need any more information please feel free to ask.
EDIT : Until now, if i remove from UserController the __construct() method, and insert in web.php to all the routes what middleware to use, it works.
For example
Route::get('/categories', [
'as' => 'categories',
'uses' => 'UserController#showCategories'
])->middleware('auth');
But i am trying to find, without specifying there what middleware to use, to use it automatically.
Build your route like below code:
Route::group(['middleware' => ['auth']], function() {
// uses 'auth' middleware
Route::resource('blog','BlogController');
});
Route::get('/mypage', 'HomeController#mypage');
Open your middleware class named RedirectIfAuthenticated and then in handle fucntion
you write below code:
if (!Auth::check()) {
return redirect('/mypage'); // redirect to your specific page which is public for all
}
Hope it will work for you.
Your route should be like
// Index
Route::get('/','UserController#index')->name('index);
see here for more about routing.
Try
Route::get('/','UserController#index',['middleware'=>'auth'])->name('index);

Laravel login redirected you too many times

I have been struggling with this from quiet a time now, what i am trying is to redirect all the url's hit by non-logged in users to login page and it gives me this error, which I am sure is because it is creating a loop on /login URL. authentication is checking for authorized user in login page also. however I wish the login page should be an exception when checking the auth. I may be doing something wrong which I am not able to get. here goes my code.
routes.php
Route::post('login', 'Auth\AuthController#login');
Route::get('login' , 'Auth\AuthController#showLoginForm');
Route::get('/' , 'Auth\AuthController#showLoginForm');
kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Auth\Access\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'acl' => \App\Http\Middleware\CheckPermission::class,
];
Authenticate class
class Authenticate
{
public function handle($request, Closure $next, $guard = null) {
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
}
AuthController class
class AuthController extends Controller {
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/dashboard';
protected $loginPath = '/login';
protected $redirectPath = '/dashboard';
public function __construct(){
$this->middleware('auth', ['except' =>'login']);
/* I have been trying these many things to fix this, all in loss.
// $this->middleware('acl'); // To all methods
// $this->middleware('acl', ['only' => ['create', 'update']]);
// $this->middleware('guest', ['only' => ['/login']]);
// echo "Message"; exit;
// $this->middleware('auth');
// $this->middleware('auth', ['only' => ['login']]);
// $this->middleware('auth', ['only' => ['/login']]);
// $this->middleware('auth', ['except' => 'login']);
// $this->middleware('guest');
// $this->middleware('guest', ['only' => ['logout' , 'login', '/login', '/']]);
}
Please help me, It going all above my head, seems some sort of rocket science to me. well btw I am new to laravel and may be doing some silly thing around, apologies for that. Thanks in Advance.
You need add route login outside Laravel group:
routes.php
Route::auth();
Route::group(['middleware' => 'auth'], function () {
// All route your need authenticated
});
Aditionally, you can see yours route list using:
php artisan route:list
Why you are doing all this just to redirect every non-logged in user to login form?
i think you can just do this
Routes.php
Route::post('login', 'Auth\AuthController#login');
Route::get('login' , 'Auth\AuthController#showLoginForm');
Route::get('/' , 'Auth\AuthController#showLoginForm');
Route::group(['middleware' => 'auth'], function () {
// any route here will only be accessible for logged in users
});
and auth controller construct should be like this
AuthController
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
The problem is with your routes.
When I enter and I am not logged out you send me to login(get) route. And as you are specifying the middleware in the construct function in the AuthController, every time a method of the AuthController is called, construct function is called again and sends you back at login.. and it repeats indefinitely.
like #mkmnstr say
The problem is with your routes.
When I enter and I am not logged out you send me to login(get) route. And as you are specifying the middleware in the construct function in the AuthController, every time a method of the AuthController is called, construct function is called again and sends you back at login.. and it repeats indefinitely.
to fix that u should add
Auth::logout();
Here
...
} else {
Auth::logout(); // user must logout before redirect them
return redirect()->guest('login');
}
...
If your working with custom middleware you must follow it's all rules
in my case, I have to define a custom route class in the web middleware group.
In the world of copy-paste sometime we make mistakes.
Middleware :
public function handle($request, Closure $next)
{
if(!isset(session('user'))){
return redirect('login');
}
return $next($request);
}
}
My Mistake in Kernel.php
if custom middleware class present in web $middlewareGroups will check condition 2 times so it will give error as: redirected you too many times
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\webUser::class, //Remove
],
protected $routeMiddleware = [
'webUser'=> \App\Http\Middleware\webUser::class //Keepit
]
I had same problem after creating my own route service provider. The problem was that when I tried to login, in first time login page showed and after entering credentials I encountered "redirected too many times" and redirected to my admin dashboard and login route!
the solution was: adding middleware "web" into my routes:
Route::middleware('web')->group(base_path('Admin/routes.php'));

Resources