I want to implement Impersonate functionality into Laravel-8 without using any package.
- Only super-admin can use this functionality.
- I used laravel sanctum to authenticate.
- to access impersonate functionality user should be super-admin. (is_admin(boolean) flag is set into users table).
Here is my middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ImpersonateUser
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$impersonateId = $request->cookie('x-impersonate-id');
if($request->user()->is_admin && $impersonateId) {
$user = User::findOrFail($impersonateId);
if($user->is_admin) {
return response()->json(["message" => trans("You cannot impersonate an admin account.")], 400);
}
Auth::setUser($user);
}
return $next($request);
}
}
My route file:
// Impersonate routes.
Route::middleware(['auth:sanctum', 'impersonate'])->group(function () {
// checklist routes
Route::get('checklists', [ChecklistController::class, "index"]);
});
Whether use Auth::setUser($user) is safe or I have to use Auth::onceUsingId($userId); ?
Auth::onceUsingId($userId); not working with auth::sanctum
middleware. So Auth::setUser($user) is safe or not?
I used laravel to develop backend API only.(SPA)
CodePudding user response:
They should be the same in terms of safety. OnceUsingId()
calls setUser()
in the background.
From the Illuminate\Auth\SessionGuard class
/** * Log the given user ID into the application without sessions or cookies. * * @param mixed $id * @return \Illuminate\Contracts\Auth\Authenticatable|false */ public function onceUsingId($id) { if (! is_null($user = $this->provider->retrieveById($id))) { $this->setUser($user); return $user; } return false; } /** * Set the current user. * * @param \Illuminate\Contracts\Auth\Authenticatable $user * @return $this */ public function setUser(AuthenticatableContract $user) { $this->user = $user; $this->loggedOut = false; $this->fireAuthenticatedEvent($user); return $this; }
Both of these methods come from the SessionGuard though. I don't know if Sanctum implements its own version.