Laravel

God Mode - My most commonly used Laravel snippet

In web development, "God Mode" can refer to a special mode that allows developers to log in as an admin user instantly. This can be incredibly useful for quickly accessing admin features, testing permissions, and debugging issues. In this article, we’ll explore a handy Laravel snippet that enables "God Mode" in a local development environment.

Setting Up the Snippet
To begin, add the following snippet to your web.php routes file:

Route::get('godmode', function () {
    if (config('app.env') !== 'local') {
        abort(404);
    }
    Auth::loginUsingId(1);

    return redirect('dashboard');
});

The first line checks if the application is running in the local environment using config('app.env'). This ensures that the route is only accessible during development and prevents potential security risks in production.

The Auth::loginUsingId(1) method logs in the user with ID 1. Typically, this user is the super admin. This line allows you to quickly log in without needing to enter credentials.

After logging in, the snippet redirects the user to the dashboard. This provides immediate access to the admin interface. You can change this to any other route that you may have in your application.

Security Considerations
It’s crucial to restrict access to this route to the local environment only. The environment check prevents unauthorized access in production. Remember to remove or comment out this route before deploying your application.

Enhancing the Snippet
For more flexibility, you can modify the snippet to accept dynamic user IDs:

Route::get('godmode/{id}', function ($id) {
    if (config('app.env') !== 'local') {
        abort(404);
    }
    Auth::loginUsingId($id);

    return redirect('dashboard');
});

Now you can login as any user by appending the user id to the route, e.g https://localhost/godmode/12

Additionally, consider adding more conditions or middleware to enhance security. For instance, you could add a check that the request is sent from a local IP adress and deny access from external IPs.

Kontaktperson

Ola Ebesson

Ola Ebbesson
+46 (0)70-278 80 39
ola.ebbesson@caesardev.se

Fler inlägg från bloggen

SOMMARHÄLSNING

Glad Sommar!

Sommaren är äntligen här och vi på Caesar vill passa på att önska er alla en riktigt skön sommar!

JUBILEUM

10 års jubileum på Caesar

Nu har vi landat igen efter vår 10 års jubileumsfest och vi vill passa på att tacka alla som var med och firade med oss!