laravel: how to stay login until a condition becomes false? - laravel

I have a field (can_login) in my users table.
normally,users can login. and logout with this code:
Auth::logout();
I want, when each time a logged-in user refresh a page,
laravel check can_login in user table.
if can_login is false, then auto logout.
I try this in RouteServiceProvider
public function boot()
{
parent::boot();
if(auth()->user()->can_login){
return route('logout');
}
}
but auth()->user() is always empty.

You can use a middleware or add a check to your existing authentication middleware.
On each request it passes through a middleware to check if user is authenticated and after that auth()->user() will not be empty.
Simplest solution would be to create a middleware in app/Http/Middlewares/CheckUserCanLoginMiddleware.php
class CheckUserCanLoginMiddleware
{
public function handle(Request $request, Closure $next)
) {
if ($request->user()->can_login ?? false) {
Auth::logout();
return $this->sendUnauthorizedResponse();
}
return $next($request);
}
}
And then register it as a routeMiddleware` in your bootstrap/app.php file.
The last thing you need is to use it to our routes middlewares after authentication middleware.

Related

Can't access user model in middleware

I created a custom middleware for checking if request is submitted by user who owns the resource or owned by admin.
Route::middleware(['web', 'selforadmin'])->group(function () {
Route::post('users/update-account/{id}', 'UsersController#UpdateAccount');
Route::post('users/update-email/{id}', 'UsersController#UpdateEmail');
Route::post('users/update-password/{id}', 'UsersController#UpdatePassword');
});
and then the middleware handler:
public function handle($request, Closure $next)
{
print_r($request->all());
print_r($request->user());
dd();
return $next($request);
}
But I don't know why user model is not accessible here. I read that request needs to pass from web middleware first so I did but still can't access this middleware.
It gives null on $request->user() or Auth::user()
I am using Laravel 5.4
EDIT:
Middleware is being called as I see other inputs. Only Auth is empty. And User is logged.
You can't access using models directly in middleware. You need to define a terminate method in your middleware to perform some processing after response has been sent to browser.
public function terminate($request, $response)
{
// Your code ...
}
If user is not logged in it will always return null.
There are two solution for this.
First is, check if $request->user() is not null.
public function handle($request, Closure $next)
{
if($request->user())
{
// do your stuff
}
else
{
// do otherwise
}
return $next($request);
}
Second is, add auth middleware before your middleware to assure that only logged in users are allowed.
Route::middleware(['web', 'auth', 'selforadmin'])->group(function () {
// .....
}

Laravel: Create middleware for Sociailite Auth

I'm using JavaScript to receive an access token to the user facebook account.
When I get the token, I send a request to the server with the token to get information about the user using Socialite.
$user = Socialite::driver('facebook')->userFromToken($request->token);
return $user->getName();
Now I'm trying to group API calls that only authenticated user can make, for example /my-profile, my-data, etc...
The middleware purpose is to check if the user is authenticated for a group of API calls instead typing the same condition in all methods:
if ($user->getName()) {
...Execute...
}
Any idea how I can place the following condition for a list of routes for autehnticated users?
My condition is simple:
$user = Socialite::driver('facebook')->userFromToken($request->token);
if ($user->getName()) {
return true;
}
else { return false; }
Okay,
First create the middleware:
php artisan make:middleware name_of_your_middleware
After that, inside the middleware file that has been created:
public function handle($request, Closure $next)
{
$user = Socialite::driver('facebook')->userFromToken($request->token);
if ($user->getName()) {
return $next($request);
}
return redirect('some_other_route_for_error');
}
Then assign the middleware to the routes middelware in app/Http/Kernel.php
protected $routeMiddleware = [
//.......
'name_of_your_middleware' => \Illuminate\Auth\Middleware\Authenticate::class,
];
In your Route file (api.php):
Route::group(['middleware'=>['name_of_your_middleware']],function(){
//your routes
});
Hope it helps :)

Role-based routing in LoginController (Auth)

In my Laravel 5.3 setup, I am using Bouncer package, and I defined two roles, admin and customer. When logged in, customers are redirected to /home, as specified in protected $redirectTo = '/home'; under App\Http\Controllers\Auth\LoginController.php. Now, if a user with the role of an admin logs in, he is also redirected to /home because $redirectTo does not make any distinction between user roles. My goal here is to redirect admin users to /admin/home instead.
What is the best solution to handle this? Here is my attempt.
In web.php routes, outside of any middleware groups:
Route::get('/home', function(Illuminate\Http\Request $request) { // http://myapp.dev/home
if (Auth::user()->isA('customer')) // -> goto HomeController#index
return app()->make('\App\Http\Controllers\HomeController')->index($request);
else if (Auth::user()->isAn('admin')) // -> redirect
return redirect('/admin/home');
else
abort(403);
})->middleware('auth');
Route::group(['prefix' => 'admin','middleware' => 'auth'], function () {
Route::get('/home', 'Admin\HomeController#index');
});
Alternatively, this can can be done in a middleware, as well:
Route::get('/home', 'HomeController#index')->middleware('auth', 'role');
// in VerifyRole.php middleware...
public function handle($request, Closure $next, $guard = null)
{
if (Auth::user()->isAn('admin')) {
return redirect('/admin/home');
}
return $next($request);
}
This would work, but it's not scalable if more roles are added. I am sure there must be an elegant built-in way to accomplish this. So the question is, how do I route users to their proper dashboard (i.e. home) based on their role?
You can override the authenticated() method in your class App\Http\Controllers\Auth\LoginController as:
protected function authenticated(Request $request, $user)
{
if ($user->isA('customer'))
return redirect('/home');
else if ($user->isAn('admin'))
return redirect('/admin/home');
}
Or
You can override the redirectPath() method as:
public function redirectPath()
{
if (auth()->user()->isA('customer'))
return '/home';
else if (auth()->user()->isAn('admin'))
return '/admin/home';
}
In Laravel 5.3, you can override sendLoginResponse() method in AuthController.php to be able to redirect users to a different routes after login.

Laravel 5 restrict access to pages using middleware

I am working on a laravel project and i need to restrict access to some pages such that only authenticated users can view that page.
To do this, created a middleware: php artisan make:middleware OnlyRegisteredUser
and registered it in the $routemiddleware inside App\Http\kernel.php as
'onlyregistereduser' => \App\Http\Middleware\OnlyRegisteredUser::class,
and this is the class. it redirects user to auth/login if not logged in
public function handle($request, Closure $next, $right=null)
{
$user = $request->user();
if ($user && $user->onlyregistereduser()) {
return $next($request);
}
return redirect('auth/login');
}
Here is my route:
Route::get('admin/poem', ['middleware' => 'onlyregistereduser:admin', 'uses'=>'PoemsController#poem']);
admin is a parameter passed to my middleware. It is taken from my user model which has an `enum' column as follows:
public function up()
{
Schema::create('users', function (Blueprint $table) {
//...
$table->enum('rights', ['admin', 'guest'])->nullable();
// ...
});
}
Now to restrict access to some of my controller methods, e.g create, i added a constructor to my PoemsController as shown:
public function __construct()
{
$this->middleware('onlyregistereduser');
}
My problem now is that this caused every single route to the PoemsController to redirect me to the login page. And again after login in, it doesn't take me to the page i intended to visit. it takes me instead to the home page. What i want is to restrict access to only some of the controller methods and not all of them and to be able to redirect to the intended page after user login.
I hope you understand my problem.
Any help will be greatly appreciated.
Remove the middleware from constructor, you don't have to add middleware to both route and costructor. That should solve your ". What i want is to restrict access to only some of the controller methods and not all of them" issue.
For othe issue modify your middleware like this
public function handle($request, Closure $next, $right=null)
{
$user = $request->user();
if ($user && $user->onlyregistereduser()) {
return $next($request);
}
$request_url = $request->path();
session()->put('login_refferrer', $request_url);
return redirect('auth/login');
}
and before redirect user after login
if(session()->has('login_refferrer')){
$url = session()->pull('login_refferrer');
return redirect($url);
}

Laravel 5.2 Redirect admin page after login as admin

Laravel 5.2 has been out for some time now. Yes, it has new auth function which is very good. Specially for beginners.
My question,
How to check if user is admin and then redirect safely to admin/dashboard properly? I know one way is to use admin flag in database but can any of you show some example?
go to AuthController.php and add this method
where role is the user role as defined in the database.
protected function authenticated($request,$user){
if($user->role === 'admin'){
return redirect()->intended('admin'); //redirect to admin panel
}
return redirect()->intended('/'); //redirect to standard user homepage
}
As in Laravel 5.3 / 5.4
Add following line to create_users_table migration.
$table->boolean('is_admin');
Add following method to LoginController.
protected function authenticated(Request $request, $user)
{
if ( $user->is_admin ) {
return redirect('/admin/home');
}
return redirect('/home');
}
Additional note don't forget to add the following lines to RedirectIfAuthenticated middleware:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
// the following 3 lines
if (Auth::user()->is_admin) {
return redirect('/admin/home');
}
return redirect('/home');
}
return $next($request);
}
Otherwise if you e.g. type yourdomain/login and your logged in as admin it would be redirected to home instead of admin/home.
AuthController extends the AuthenticatesAndRegistersUsers trait, which has a public method named redirectPath. In my case I would extend that method on the AuthController and I'd put my logic there:
public function redirectPath()
{
if (Auth::user->myMethodToCheckIfUserHasAnAdminRoleLikeAnEmailOrSomethingLikeThat()) {
redirect('admin/dashboard');
}
redirect('home');
}
in Auth/LoginController there is protected $redirectTo = '/home';
change '/home' to '/loginin' for example, and create a new controller and in the controller get the information of the user and check if he is a admin or not and then redirect him to the proper page

Resources