Monday, March 7, 2022

[FIXED] Laravel login as another user

Issue

I am currently developing a laravel app where there are 3 user_roles

  1. Superadmin
  2. Admin
  3. Normal

So each role can access the roles below him.

e.g

Superadmins can access admins and normal users account.

How do I allow a authenticated superadmin user to log in as an admin or normal user with a click of a button?

USER_ROLES TABLE
id      name
 1      superadmin
 2      admin
 3      normal

----------------------------
USERS TABLE
id      first_name        last_name        user_role_id    password
 1      john              doe              1               *******
 2      jane              doe              2               *******
 3      cassie            snow             3               *******
 4      sansa             stark            3               *******

Solution

Reading the comments I think you want to do the following:

  • Editing anothers profile (or anything else)
  • your rights have to be higher than the ones of the other account
  • everything should be logged by the user that changed the entries, not by the owner

The following solutions are build in ones, maybe there are some packages for laravel to solve this kind of problem.

Auth::loginById($otherUserId) could be one solution:

  • you have to check if the user is allowed to log in in this profile
  • you have to remember your own user id (in a session) to add it for the log
  • you can access only the pages the user can see (not the admin pages)

Another approach would be to use Policies

e.g. you are user 1 and want to edit the profile of user 3. in the update function user/3/profile. You call a policy function where you check if your user_role_id is smaller than the other ones. Then the record will be saved and the logger will log it away with your user id.

Both ways have pros and cons. Login with the id will give you exact the view of the other user. But you have to modify your logger (instead of Auth::id() use something with a session). Then you can implement a little button with (jump back to own profile) to login back in your own account. Using polices will be easier for the logger, but at every part you have to implement the check with the policy.

Not knowing the size and complexity of your project I would suggest the first solution. I implemented it by myself in one project but without the logger function.



Answered By - cre8

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.