Laravel5: Best practice for global Auth::check on - php

i'm new to Laravel5, i wrote a little login function for my Web, here's my home function:
public function home()
{
if (Auth::check()) {
return view('start/dashboard');
}else{
return Redirect::to('login');
}
}
The problem is that i will need Auth::check() for each function in my Controllers, so i was wondering: what's the best practice for implementing a global check to my web? i was thinking about implementing it into my header view which would be like #if(!Auth::check()) redirect to login or something ..
any ideas what's the easiest solution?
thanks

The way to achieve this is middleware.
Laravel provides one out of the box that checks if the user is authenticated. It's called auth.
In your routes.php, the easiest way would be wrapping all the routes you want to protect with:
Route::group(['middleware'=>'auth'], function($router){
Route::controller("posts","PostsController");
//or:
$router->controller("posts","PostsController");
// And so on.
});
Further reading
If you want to dive into that specific middleware, it's in app/Http/Middleware/Authenticate.php if I remember right.
You can create new middleware with php artisan make:middleware <name>. Remember to register your new middleware in app/Http/Kernel.php under the $routeMiddleware-property. Alternatively, if you want to run your middleware every single time, (almost) no exceptions, you can put it in $middleware which applies to all requests.

Related

Laravel 8 Auth middleware protected route failing

I am building my first Laravel app with the Metronic 8 Laravel theme. It uses Breeze for authentication. I changed a couple of things around - created a welcome page for non-logged-in users, and moved the main template that was the index to an auth protected "/dashboard". The problem is that it still tries to load the dashboard Blade template, regardless of authentication, resulting in an error.
Route
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth'])->name('dashboard');
Here's Authenticate, where it should redirect non-authenticated users to the login page.
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
When I'm not logged in and navigate to the dashboard URL, it attempts to load the dashboard Blade template, which calls a menu function that checks the user permissions for menu items. Unfortunately, since there is no user, the application blows up from passing a null value to a method expecting a user array/object.
Any ideas on where to look for the problem? It seems to me that the auth middleware should redirect to the login page before trying to load the Blade template when not logged in.
I would put the middleware at the beginning of the route like this, though I'm sure it's not causing the problem-
Route::middleware(['auth'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Aside from that, please provide some information on the error itself like what the error is about/what is says..etc...
First of all, make sure you have a login named route defined in your routes/web.php file. It should look something like:
Route::get('/login', '<controller>#<method>')->name('login');
The important bit is ->name('login') so that the Authenticate middleware can correctly identify the route to redirect to. Change <controller>#<method> appropriately to route to the login method of your app.
Wakil's answer is irrelevant and actually opposite of the documentation. Your syntax is correct.
I figured out the issue. Keen Themes put a call to a method to build an array of menu items in the web routes file. That was making the call to the offending code. After I wrapped that in an auth check the error was fixed, and everything works as expected.

How to integrate other pages into laravel pre-built authentication

After reading some tutorials on laravel 5.4 authentication (including the doc),I don't know how to work with it in my file.
I have been able to run the artisan command.. php artisan make:auth. Have seen the the controller, views etc that was created and even have accessed it by going to http://localhost/blogsite/public/register (don't worry about, its on my local disk) but how do I integrate it with with the pages that needs authentication? That I don't know..
Who can put me through how to integrate it with other pages
Many way you can use for this solution.
First Way:
If you load views file from controller just use the following line to your controller.
Suppose my controller name is DashBoardController
public function __construct()
{
$this->middleware('auth');
}
So all of the view you return from DashboardController it will make you auth for you. That means if you return any of view from this controller you must need to log in.
So you need to put this constructor function to all of your Controller from where you return view and need to authenticate the user.
To avoid this constructor funtion to all controller you can use the following
Way using route:
Route::group(['middleware' => 'auth'], function () {
Route::Your_Request_Method('your_url1', 'YourController1');
Route::Your_Request_Method('your_url2', 'YourController2');
});
You can get more way at laravel authentication documentation
Hope you will understand.

How can we redirect a page to another if a session is not found using route in Laravel 5.3

I am using a session separately other than the default authentication sessions. If an user try to access my secured page, he should have the session set. If anyone without that session try to access means, they will be redirected to error page. I am using Laravel 5.3
The user can view the below two pages only if the session variable named 'secured_user' is set. Otherwise they will be redirect to the error page
Route::get('/secured-page1', 'ValidationController#CheckSecuredLogin_1');
Route::get('/secured-page2', 'ValidationController#CheckSecuredLogin_2');
The best option would be a policy.
You can create certain constrains and couple it with your models. Policies are especially suitable for changing your logic later on.
See here: Create Policy
Within you PagesPolicy, you can add this function:
public function before(User $user, $ability)
{
if ($user->isSuperAdmin()) {
return true;
}
}
public function seeSecurePage(User $user)
{
// Your custom Code and session handling
if(session("secured_user")) return true;
return false;
}
and in your controller.
$user->can("seeSecurePage","Pages");
If "can" fails, it will automatically redirect to error 403.
P.S.: Another possibility are Gates
You should use Laravel Middlewares to achieve this, I think middlewares are made for the work you need:
First create a new middleware by running the artisan command:
php artisan make:middleware CheckSesison
Then the CheckSession would look like this:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckSession
{
public function handle($request, Closure $next)
{
if ($session_value != 'YOUR_DESIRED_VALUE') {
return redirect('home');
}
return $next($request);
}
}
Now in your routes file you can use laravel's route middleware() method to implement it like this:
Route::get('/secured-page1', 'ValidationController#CheckSecuredLogin_1')
->middleware(CheckSession::class);
Hope this helps!
In addition to the awnser above, you could also use middleware that's used on the routes and even group them if required. It is a simple, quick and clean solution. Inside the middelware you simple check if the session you require is there and depending on the result you take any action necessary.
Laravel middleware docs

Laravel 5.2 : Do something after user has logged in?

(I'm a beginner of Laravel)
I'm using Laravel 5.2. I have successfully enabled the Authentication; by doing the php artisan make:auth and stuffs.
So my login is working.
Now i need to do something once someone has logged in. For an simple example:
LOGIN:
Once a user has logged in, write a value into Session.
For example: $request->session()->put('UserAgent', $ClientUserAgent);
LOGOUT:
Same thing to do, once a user has logged out, delete the custom Session value.
For example: $request->session()->forget('UserAgent');
I'm not sure whether there are (things like) hooks or Event Listeners, Event Handlers, or something like that.
How can i do it please?
For newer versions of Laravel
If you are only doing something very simple then creating an event handler seems overkill to me. Laravel has an empty method included in the AuthenticatesUsers class for this purpose.
Just place the following method inside app\Http\Controllers\LoginController (overriding it):
protected function authenticated(Request $request, $user)
{
// stuff to do after user logs in
}
For the post login, you can do that by modifying App/Http/Controllers/Auth/AuthController.php
Add authenticated() into that class to override the default one:
use Illuminate\Http\Request;
protected function authenticated(Request $request, User $user) {
// put your thing in here
return redirect()->intended($this->redirectPath());
}
For the logout, add this function into the same class:
use Auth;
protected function getLogout()
{
Auth::logout();
// do something here
return redirect('/');
}
You could try setting up event listeners for the Auth events that are fired.
You can setup a listener that listens for Illuminate\Auth\Events\Login to handle what you need post login and Illuminate\Auth\Events\Logout for post logout.
Laravel Docs - Authentication - Events
Alief's Answer below works fine as expected. But as i googled through, using the Event Handlers is probably the more preferred way. (It works like custom hooks).
So without any less respects to Alief's Answer below, let me choose --> this Event Handers approach i just found out.
Thanks all with regards!
If you are testing, with authenticated(Request $request, User $user) method dont use alert inside this method to test, it will not show any result, so better put some insert query or something like that to test this method.
Why not simple check for
if(Auth::check()){
//your code
}
Make sure you include use Auth;

Laravel 5 Post-login actions/hooks

In Laravel 5, I want to add some custom user-specific data to a session variable after the user has logged in. I understand there may be a way to do this by overriding postLogin() in the Authentication controller, however I think there may also be a way to do it using Middleware?
However, I am not sure where I would place the Middleware so that it is executed straight after authentication has succeeded.
You can place it in Middleware/RedirectIfAuthenticated.php
if ($this->auth->check())
{
//place your code here
return new RedirectResponse(url('/home'));
}

Categories