How to store into database on page Refresh with Laravel? - php

I want to check if users are using the system.
I know have a last_login, with the standard laravel class UpdateLastLoggedInAt.
public function handle(Login $event)
{
$event->user->last_login = Carbon::now();
$event->user->save();
}
This doesn't work if users let their browser window stay open.
Is there a way to have it so that on every page refresh or route change (users navigates through the website), change the last_login to that time?
Thanks in advance.

I created a middleware for this and wrapper it around all routes.
class LogLastSeen
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = User::find(Auth()->user()->id);
$user->last_login = Carbon::now();
$user->save();
return $next($request);
}

Related

Integrating a PHP function In Node.js

I am new to Node.js, and I am trying to integrate a function I was able to do in PHP in some other project, creating an admin route so that when a regular user logs in, it takes the user to the user dashboard. When the admin logs in, it takes the user to the admin dashboard.
class AdminRouteProtect
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if(Auth::user()){
if(Auth::user()->hasRole('admin')){
return $next($request);
} else{
return redirect()->back();
}
}
return $next($request);
}
}

Laravel Entrust - add support for guest role

I am using Entrust middleware from here. Everything goes fine except when I want to expose a certain page to admin when logged in and to any user who is NOT logged in .
With the help from here , I added the following middleware, but when I hit the url , it says, too many redirections.
namespace App\Http\Middleware;
use App\Models\User;
use App\Models\Role;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Database\Eloquent\Collection;
class CheckPermission {
/**
* The Guard implementation.
*
* #var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* #param Guard $auth
* #return void
*/
public function __construct( Guard $auth )
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle( $request, Closure $next )
{
if ( $this->auth->guest() )
{
$user = new User;
$user->id = 0;
$user->username = 'Guest';
$role = Role::find(9);// EXPLANATION OF 9 IS GIVEN BELOW UNDER CODE
$user->roles = new Collection;
$user->roles->add( $role );
}
else
{
$user = $this->auth->user();
}
// Automatically check permission based on route name
/*
if ( !$user->can( $request->route()->getName() ) )
{
// Handle denied permission, e.g. abort(401)
}
*/
return $next( $request );
}
}
Database change : in roles table I added a row with id 9 and name guest.
How can I add a guest support in Entrust so that any user who is not logged-in will be considered as a guest and he will be allowed to visit certain routes as well.
I'd personally avoid any global middleware dealing with authorization as to not block your application from having publicly accessible pages. Use route groups to assign middleware to protected routes.
While it may not fit into Entrust's design, you could also write a custom middleware to only allow guests and admins. Something like this:
class AdminOrGuestMiddleware {
/**
* 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 = null)
{
if ($request->user() && !$request->user()->hasRole('admin')) {
return redirect('/home');
}
return $next($request);
}

Preload a view in laravel with different data

I am using Laravel and sentinel to develop a permission system however it was designed so that the user can select and deselect which permissions the role has from a checkbox form. I have already coded the part where they can assign permissions however I need that the checkboxes that have already been assigned are marked when the user request the page. How do you recommend approaching this? I am using a middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Cartalyst\Sentinel\Laravel\Facades\Sentinel;
class PermissionsMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = Sentinel::findById(1);
$permisos = array(array_keys($user['permissions']))
return $next($request);
}
}
However, I don't know how to pass data from the middleware to the view.
I don't think it's recommended using the middleware for this purpose, but if you still want to do it that way you can try using:
View::share ( 'permisos', $permisos );
To share the 'permisos' variable with the view that's coming after the middleware.
So your code is going to look like this:
<?php
namespace App\Http\Middleware;
use Closure;
use Cartalyst\Sentinel\Laravel\Facades\Sentinel;
class PermissionsMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = Sentinel::findById(1);
$permisos = array(array_keys($user['permissions']))
View::share ( 'permisos', $permisos );
return $next($request);
}
}

Laravel looses Session ( Authentication)

I have a problem with a specific route on Laravel. Every second time (and sometimes on the first time) when ill call a specific route, ill get an 401 error, returned from the Authentication Middleware.
File Middleware/Authenticate.php
class Authenticate
{
/**
* 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 = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401); // THIS IS CALLED
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
From that route:
Route::group(['middleware' => 'auth'], function () {
.........
Route::get('events', 'TaskController#events');
});
TaskController.php
public function events(Request $request) {
$time_from = $request->start;
$time_to = $request->end;
$events = array();
$user_id = Auth::user()->id;
.....
return response()->json($events, 200);
}
All called from a JQuery $.get Request. I dont know why Laravel thinks i am a guest, and then looses the Session?
When you are doing ajax/api requests laravel thinks you're guest because session based authentications doesn't apply to this type of calls. Whenever you use auth middleware you'll get 401 on ajax, even if you're authenticated.
You need some type of token based authentication for the ajax/api calls, that sends Authentications header on requests and new middleware that handles authentications for it.

Multiple dynamic url redirect in Laravel

I have looked at many similar questions bu they don't approach the real problem. I would like to redirect a user to a certain url just after login depending on a condition about the user.
I know this can be archieved with a middleware so I have tried this in app\Http\Middleware\RedirectIfAuthenticated.php
class RedirectIfAuthenticated
{
/**
* 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 = null)
{
if (Auth::User()->check()) {
$redirect = '/client';
if (Auth::user()->hasRole('admin')){
$redirect = '/admin';
}
return redirect($redirect);
}
return $next($request);
}
}
I realise now this will not work just after login. I'd like to redirect a user depending whether he/she is an admin or a client. I know I could use: protected $redirectPath = '/url/to/redirect'; but I have multiple pages to redirect to.
What is the best way to do this?
You could over-write the redirect method offered up by the trait in app/Http/Controllers/Auth/AuthController.php
public function redirectPath()
{
if (Auth::user()->hasRole('admin')){
return '/admin';
}
return '/client';
}
Put that in your AuthController.php.

Categories