I want to implement a system where 6 types of users exist. So one is 'customer' who will login by a route like /login and rest of 5 users are admins and only they will be login using another route /system/base-admin. However, 'customer' never login with the /system/base-admin route if anyhow can known this route. And both route have different login form and if they failed to login 'customer' will be redirected /login and admins /system/base-admin.
I know about $guard and middleware check.
Question: How can i implement above scenario and how react professionals with this scenario?
Route::get('/login','CustomerLoginController#processLogin')->name('customer.login');
Route::get('/system/base-admin', 'AdminLoginController#processAdminLogin')->name('system.admin')
My Controller Looks like
public function processLogin(){ return view('customer.login');}
public function processAdminLogin(){ return view('admin.login')}
Thank you in advance.
The only reason I see to have different endpoints for login is to have different views.
Copy your Auth\LoginController, change $redirectTo to redirect to your admin panel. Overwrite AuthenticatesUsers\showLoginForm to show your admin form and update middleware in __construct.
Protect all your admin routes with admin middleware.
Now. Your users CAN login to your panel. BUT nothing will happen since they don't have access.
If you want to show them some kind of message when they try you can overwrite AuthenticatesUsers\login method with something like this
...
if ($this->attemptLogin($request)) {
if(!auth()->user()->isAdmin()){
throw ValidationException::withMessages([
$this->username() => 'You don\'t have access to this page',
]);
}
return $this->sendLoginResponse($request);
}
...
Related
I'm working on an application where some users should have access to other user accounts. For example: In a family, the mother and all 3 kids have an account. Now the mother should have access to all of the kids accounts.
Is there a possibility to setup something like this in Laravel using Passport? I thought about a "permission" database table with two columns (parent_account, child_account). Parent accounts could then switch between accounts where they have the permission.
Perfect would be something like a middleware where I can set Auth::actAs($child);and after that every Auth::user() call would be the child until I switch back to the "normal" account.
Additional information: I'm using Laravel to provide an API for my React Frontend Application. I tried the Auth::loginUsingId function, but when I use it I get logged out and I get the Method Illuminate\Auth\RequestGuard::loginUsingId does not exist. Exception.
I am using Laravel Version 6.9.0
I found a solution to my problem.
I added a middleware that contains this piece of code:
public function handle($request, Closure $next)
{
$activeChild = Auth::user()->activeChild; // id of child user
if ($activeChild) {
Auth::setUser($activeChild);
}
return $next($request);
}
After that I added this middleware to all routes:
Route::group(['middleware' => ['actAsUser']], function () {
// some routes
});
I am logging in via Laravel API.
Let's say that I am on www.domain.com/login. After login is successful, I put the token into a cookie and redirect to /admin.
Route::get('/admin', function () {
return view('admin');
})->middleware('auth');
The problem is that Laravel doesn't see that the user is logged in, thus redirects me to /login once more.
And, if I declare the route as follows
Route::get('/admin', function () {
return view('admin');
});
Everyone can access www.domain.com/admin
I appreciate any help.
Luca
You need to add auth:api middleware so it can see the auth user
//This is the middle ware
public function handle($request, Closure $next)
{
if(auth()->user()->isAdmin()) //isAdmin is a function in the User model which checks if the user is admin or not
{
return redirect('/admin');
} else {
return redirect('/home');
}
return $next($request);
}
//I already registered this middleware in kernel as well as verifyUser
Route::middleware(['auth', 'verifyUser'])->group(function() {
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/admin', 'AdminController#index')->name('admin');
Route::get('/users/profile', 'UserController#view')->name('users.view-profile');
Route::get('/users/edit_profile', 'UserController#edit')->name('users.edit-profile');
});
Th main problem here is it shows this error in the browser
The page isn’t redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept cookies.
You're telling Laravel to redirect admins to /admin, and non-admins to /home.
However, you've made /admin and /home subject to that middleware, too, so when the user gets to /home it redirect them to /home again (and again, and again, and again, forever).
You likely need two changes:
A new middleware, applied only to admin routes, that only redirects non-admins away from those routes.
Put your home/admin logic as a one-off post-login step instead of on every pageview. See the path customization section of the Authentication docs.
Does laravel provide a way to prevent multiple logins of a user from different devices / browsers at a given time? If yes then how can i force a user to logged in from a single device at a single time. I am developing a online quiz app using laravel 5.6 where users can logged in from a single place and take test.
laravel provide this method to invalidating and "logging out" a user's sessions that are active on other devices logoutOtherDevices()
to work with this method you need also to make sure that the
Illuminate\Session\Middleware\AuthenticateSession
middleware is present and un-commented in your app/Http/Kernel.php class' web middleware group:
'web' => [
// ...
\Illuminate\Session\Middleware\AuthenticateSession::class,
// ...
],
then you can use it like this
use Illuminate\Support\Facades\Auth;
Auth::logoutOtherDevices($password);
Perhaps this should get you started:
Add a column in users_table.php
$table->boolean('is_logged_in')->default(false);
When a user logs in: LoginController.php
public function postLogin()
{
// your validation
// authentication check
// if authenticated, update the is_logged_in attribute to true in users table
auth()->user()->update(['is_logged_in' => true]);
// redirect...
}
Now, whenever a user tries to login from another browser or device, it should check if that user is already logged in. So, again in LoginController.php
public function index()
{
if (auth()->check() && auth()->user()->is_logged_in == true) {
// your error logic or redirect
}
return view('path.to.login');
}
When a user logs out: LogoutController.php
public function logout()
{
auth()->user()->update(['is_logged_in' => false]);
auth()->logout();
// redirect to login page...
}
I am using laravel 5 and added Entrust for roles and permissions.
I don't know how to use the permissions. If I have a permission create-post means what will it do?
create option in the Post controller will be permit? Or we need to assign a permission name to the page?
Please suggest an example. Even I don't know where to check permissions...
The workflow of Entrust is as follows
Create roles
Role::create(['name' => $role]);
e.g admin, reader etc
Create permissions
Permission::create($permission);
e.g can_read_post, can_edit_post, can_delete_post
Assign permissions to roles
$role = Role::where('admin)->first();
$role->perms()->sync($ids); //here the ids are ids of permissons which you want to assign
e.g admin has permissions (can_read_post, ca_edit_post, can_delete_post) and reader has permissions (ca_read_post)
Assign roles to users
You can assign a role to many users.
$user->roles()->attach($roleId);
Filter content based on Role or Permission
The basic setup has been completed. Now you can filter the content of your website using different methods. Here I will discuss a few
Define a filter in filters.php and apply on route
filters.php
Route::filter('admin', function()
{
if(!Entrust::hasRole('Administrator'))
{
return Redirect::to('/');
}
});
routes.php
Route::group(['before' => ['admin']], function(){
//add some routes which will require admin role
//any user which has not admin role will be redirected to home page
}
In your views
#if(Entrust::can('can_edit_post'))
//add some html which will only be visible to users who has such a role which has this permission
#endif
In your controllers/models/repos
Similarly you can filter content in models/controllers/repos etc.
So I guess you have got the basic idea. Now you can use Entrust functions almost anywhere. Hope this helps.
Briefly what we need to done to implement Entrust Laravel Package for role based permission is as below.
Install the package as per per the instructions given in
https://github.com/Zizaco/entrust
After all, done with the above Package(GitHub) like database table creation, Middleware, Controllers and all.
When a user login in the system, then there is an array provided by Auth, that contains all the actions user can (actions ability logged in user can) take.
Let a suppose we have a Controller named as CategoryController as below.
class CategoryController extends Controller
{
public function __construct()
{
$this->middleware('permission:category_index', ['only' => ['index']]);
$this->middleware('permission:category_create', ['only' => ['create', 'store']]);
$this->middleware('permission:category_edit', ['only' => ['edit', 'update']]);
$this->middleware('permission:category_delete', ['only' => ['delete']]);
$this->middleware('permission:category_view', ['only' => ['show']]);
}
}
We generally have 5 actions in a Controller, If we have a single route (called as resource route) in our routers/web.php file for all CRUD actions of single controller.
In this example, suppose we have all these 5 methods. So we also have entry in permission for these in permission table.. like I have
Permission Table
id display_name name
5 Delete Category category_delete
4 Edit Category category_edit
3 Create Category category_create
2 List Category category_index
We just need to add these permission names in our controllers as I have done in the CategoryController, If you use hyphon in permission table's name filed, then use like
$this->middleware('permission:category-create', ['only' => ['create', 'store']]);
Write all permissions in the controller constructor.
that' it!!
It will automatically check the logged-in user ability and according to the database entry in permission_role (relation table of role and permission), It will either show the page or access denied for that user.
Hope this works !!