How to set default user for guest users in laravel 5? - php

Is it possible to create some user which will automatically included if user is not authenticated? For example, if I call $request->user() in controller I will get NULL. I want to get some default user model in this case (maybe instance of App\User with id == 0). I need it because I want to attach some roles and permissions to guest users via entrust module.

You could add a simple middleware that would authenticate users as Guest user if they aren't authenticated. The code below should do the trick:
class LoginAsGuest {
public function handle($request, Closure $next)
{
if (!Auth::id()) {
Auth::loginUsingId($guestUserId);
}
}
}
Make sure this middleware runs last so that user has a chance to be authenticated using their session/cookie data.

Related

Laravel: Check if User is an admin using isAdmin column?

I'm really new to laravel and have been reading the documentations and tutorials. I'm planning on making an app that has 2 roles, admin and user. I modified my User model to have the column 'isAdmin' with boolean value since I only need 2 roles. How do I perform a check on this attribute during auth? Thank you.
TO answer your question, first of all to make protect any route using the auth middleware which ensures a user is authenticated (logged in) before they can access the route, you simply need to add the auth middleware.
e.g
web.php
<?php
Route::middleware('auth')->group(function(){
//All Routes which needs user to be logged in
});
or
//Individiual Route Middleware
Route::get('/path/to', 'controller#instance')->middleware('auth');
As for checking user role, you can basically create a middleware for this using the following steps:
run your php artisan make:middleware IsAdminMiddleware
open your IsAdminMiddleware and add this code inside the handle function:
public function handle($request, Closure $next)
{
if(!Auth::check()){
return redirect()->route('login');
}
if(Auth::user()->isAdmin == true){
return $next($request);
}
return redirect()->back()->with('unauthorised', 'You are
unauthorised to access this page');
}

Remove another user's session

There is possible to get another users session? Suppose, there is user with admin privilegies and I need that admin have functionality, to access another user's session and remove it. (So that another user will automatically logged out).
Is there some tools in laravel for this? or I need do same things, as I would do for native PHP application ?
Have an admin panel and have the setting to block the user.
Have a column in your database table, say is_blocked with datatype as tinyint, with 1 meaning the user is blocked.
In your application, have an additional check of whether the current logged in user is blocked in a custom made middleware. If yes, log them out, else continue with request target.
Middleware Snippet:
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
use Session;
class IsBlockedMiddleware{
public function handle($request, Closure $next){
Auth::user()->refresh();
if(Auth::user()->blocked === 1){
Auth::logout();
Session::flash('error','Your account is blocked'); // show the flash message in your blade file
return redirect()->route('login');
}
return $next($request);
}
}

how to block Url to all user except super admin

it should forbid that the user grabs this url:
?main_title=banner
?main_title=law
?main_title=faq
with this
if(\Auth::user()->hasRole(['super_admin']))
I am going to assume that you are using spatie/laravel-permission based on your example code.
Laravel Permission comes with built-in role middlewares
One of the ways you could use them is by grouping the routes you want to be accessible only by super admins
Route::group(['middleware' => ['role:super_admin']], function () {
// YOUR ROUTES HERE
});
It's always good to using the middlewares ,
So in your case first create a Trait for roles
public function isSuperadmin(){
return Auth::user()->role->role=='superadmin';
}
After that create a middlewar like superadmin for the superuser and in that first include your trait
use App\Traits\Roles;
after that
use Roles;
public function handle($request, Closure $next)
{
if(!$this->isSuperadmin())
{
return back();
}
return $next($request);
}
and just register the middleware in the app/http/kernal.php in protected $routeMiddleware function
'superadmin' => \App\Http\Middleware\superadmin::class,
so it's make your life very easy now you don't need to check the url or role every time , for any url you want to block for other users just use
Route::get('/?main_title=law', 'HomeController#function')->middleware('superadmin')->name('admin-dashboard-home');
so if the user role is superadmin then he is allow to assess the url you can redirect the other users or show the error message :)

How can restrict a user to access some section of my application in laravel 5.4

I have different type of users in my application. Ex: Super Admin, Client, Staff and HR.
Now I want to give all access to Super Admin and some for Client and some for Staff and some for HR also.
Lets say I have 3 section
a) Manage Staff
b) Manage Clients
c) Manage Projects
d) Manage Designation
Now I want to give access super admin a,b,c & d And for Client only C And For Staff Only c & d And for HR only a.
I have done it by checking the User type form my user table. (Not Right Way)
Lets Say I have a URL localhost/myApp/staff [ this can be access by Super Admin]
But when I logged in as Client and I hit the above URL then He/She is able to get the list of staffs, Which I want to restrict and redirect back him with some message.
How can I achive this in Laravel 5.4. Thanks in advance.
You need to use middleware for that.
See in the doc:
https://laravel.com/docs/5.4/middleware
A little example
public function handle($request, Closure $next)
{
$user = $request->user();
if ($user && $user->isAdmin())
{
return $next($request);
}
return new RedirectResponse(url('/home'));
}
}
With a middleware like that , if the user is Admin he can go on the page if not it will be redirect on the homepage.
The isAdmin is a function , you gonna need to create in your user Model like that.
public function isAdmin()
{
return $this->groups->name =='Admin';
}
In the function for the staff url check the type of user:
function staff(){
if(Auth::user ! = 'super-admin')
return redirect('/')
}
else{
//show the staff
}
You need check this page out Authenticate A User Instance.
Authenticate A User Instance
If you need to log an existing user instance into your application, you may call the login method with the user instance. The given object must be an implementation of the Illuminate\Contracts\Auth\Authenticatable contract.
Auth::login($user);
// Login and "remember" the given user...
Auth::login($user, true);`
Of course, you may specify the guard instance you would like to use:
Auth::guard('admin')->login($user);
You can follow the Laravel documentation or add a new field called 'role' or what ever to authenticate.

separate the view in type of user with laravel

I am making a project and the table Users haver a column called "tipo de usuario" (type of user in spanish) so I need that one kind of user (client) can't acces to some views that the other user (staff) does, in laravel I am using this in my controllers:
public function __construct(){
$this->middleware('auth');
}
That is working so only logged users can acces, but then if a client try to acces to a view that should be only for my staff then he can do it because they both are logged users.
Assuming that you have different roles for the users.
You can create another middleware using the artisan command:
php artisan make:middleware <name>
Then, on the handle method, you can check the role of the user
Something like this:
public function handle($request, Closure $next)
{
if (auth()->user()->role !== 'staff') {
// Response if not staff
}
return $next($request);
}
Don't forget to register the middleware on the kernel (app/http/)

Categories