Logs not working inside AuthController - php

I am trying to log Auth activity using Laravel 5.2 built-in Logs API.
The code would be like
\Log::info("Message here");
It works inside HomeController. However, it does not work inside AuthController.
Sample code inside logout method:
public function getLogout()
{
\Log::info('User has logged out.', ['email' => \Auth::user()->email]);
\Auth::logout();
return redirect('/');
}

If you are using Route::auth() to register your Auth related routes, it does not use that method, getLogout. It uses logout.
Check your routes with php artisan route:list to see what controller methods those Auth routes are using.

Related

Laravel 7: Why when I'm logged I can access route for reset password?

I realized can access to reset password route even when I'm logged. I want to can access only if user is logout.
How can I change this?
I suppose you are using the default Laravel Auth routes (Auth::routes() in web routes file). In there, the reset password routes are protected behind the web middleware only. You can check the route list alongwith their middleware using the command: php artisan route:list.
What you have to do here is to add guest middleware to those reset password routes. For Laravel 7, it can be done by following code:
Auth::routes()
Route::middleware('guest')
->group(function () {
app()->make('router')->resetPassword();
});
Note: the above code must be placed below Auth::routes() call
add the following in Reset Controller
public function __construct()
{
$this->middleware('guest');
}

Declare same route twice but expect different behaviour according to a middleware

I started creating a REST API using the lumen framework and wanted to set up a particular behaviour for my GET /user route. Behaviour is the following:
If the request come from an authenticated user (using auth middleware), the method getAllFields from UserController is called and return all the data from the user
If it's not the case, the method get from UserController is called and return some of the data from the user
It seems logic to me to just write it like that in my web.php using a simple middleware:
<?php
$router->group(['middleware' => 'auth'], function () use ($router) {
$router->get('/user/{id}', [
'uses' => 'UserController#getAllFields'
]);
});
$router->get('/user/{id}', [
'uses' => 'UserController#get'
]);
But for some reason, even if the middleware is correct, I always get the response of the second route declaration (that call get()). I precise that if I remove the second route declaration, the one in the middleware work as expected.
Have someone an idea how I can achieve something similar that work?
Router will check if your request matches to any declared route. Middleware will run AFTER that match, so You cannot just return to router and try to find another match.
To fallow Laravel and Routes pattern - You should have single route that will point to method inside controller. Then inside that You can check if user is logged or not and execute getAllFields() from that controller. It will be not much to rewrite since You are currently using UserController in both routes anyway.
web.php
$router->get('/user/{id}', 'UserController#get');
UserController.php
public function get()
{
return auth()->check() ? YourMethodForLogged() : YourMethodForNotLogged();
}
Or if there is not much logic You can keep this in single method.
Also it is good idea to fallow Laravels REST standards (so use show instead of get, "users" instead of "user" etc - read more https://laravel.com/docs/7.x/controllers)
web.php
$router->get('/users/{user}', 'UserController#show');
UserController.php
public function show(User $user)
{
if (auth()->check()) {
//
} else {
//
}
}
To summary - for your needs use Auth inside controller instead of middleware.
To check if user is logged You can use Facade Auth::check() or helper auth()->check(), or opposite Auth::guest() or auth()->guest().
If you are actually using Lumen instead of full Laravel then there is not auth helper by default (You can make own or use package like lumen-helpers) or just keep it simple and use just Facades instead (if You have then enabled in Lumen).
Read more https://laravel.com/docs/7.x/authentication and https://lumen.laravel.com/docs/7.x/authentication
This pattern is against the idea of Laravel's routing. Each route should be defined once.
You can define your route without auth middleware enabled and then define your logic in the controller.

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

How to ensure user is authenticated before he publishes an article in Laravel in the below scenario?

I am developing a simple web blogging application in Laravel 5.1. The application contains two controllers, a UsersController and an ArticlesController.
The authenticate() and check() functions that validate whether the user is authorized to carry out the operation are in the UsersController, and the store(), update() etc. features related to articles are in the ArticlesController.
How am I supposed to call the authenticate() or check() function from ArticlesController before say, store()ing an article to the database?
Laravel uses middleware, in your controller you need to put this
public function __construct(){
$this->middleware('auth'); //Requires auth
}
and in your routes you need to add the code for use middleware in your needed controllers like this
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});
Read the documentation of Laravel about Middleware you can create more middleware http://laravel.com/docs/master/middleware
You're question is not very clear, but I suppose that you want check if an user is authenticated before storing an article. There are many ways to do it:
Set a middleware in the routing rules of your ArticleController.
Check the authentication in the store method using the "standard" Auth class.
Example:
function store()
{
if (Auth::check())
{
// The user is logged in...
}
}

Categories