Ad

Laravel 5: Apache Php Http Authentication

- 1 answer

I need some help and advice on the following topic.

My boos has a simple Apache server setup and has a simple php auth setup as well. As soon as the user is validated using a panel like this.

enter image description here

He/she have than access to all the applications running behind it. So in other words this panel serves as a 'gate', if you are over the gate then you have access (of course there is permission table running on the web server).

Problem

The App I am building using Laravel 5 needs to run behind the gate, so it means the app needs to know who the user is.

Using $_SERVER['PHP_AUTH_USER']; I can fetch the username whose currently logged in.

But what if I want to track the user's actions on my app? I need something like $this->user_id right?

So I was thinking as soon as the user passes the 'gate' I fetch his username and create a user out of it saving it in my database running behind Laravel by doing so.

  if(isset($_SERVER))
  {
    if ( array_key_exists( 'PHP_AUTH_USER', $_SERVER ) ) {
        $agent = $_SERVER['PHP_AUTH_USER']; //Request::server('PHP_AUTH_USER')

    }

    $user = User::create([
      'username' => $agent,

      ]);
  }

But this makes user every time the user refreshes the page! But without going further what is the best way to do this?

  1. Do I need a separate provider (I tested the code above in AppServiceProvider)?

  2. How can I do something like this $this->user_id after saving the username?

Note: I know Laravel has basic auth out of box, but this won't work because the user are not yet in my database. I need to create them first just like above.

Ad

Answer

First, you should check if a user with the provided username already exists in your database. This way you don't create a new user on every refresh. You then can use Auth::login($user); to login the user which allows you to use the auth middleware provided by Laravel (not auth.basic!). This way you can access the user over your entire App with the Auth facade and store additional information about the user:

if(isset($_SERVER))
{
    if ( array_key_exists( 'PHP_AUTH_USER', $_SERVER ) ) {
        $agent = $_SERVER['PHP_AUTH_USER']; //Request::server('PHP_AUTH_USER')

        // Try to find an existing user, or create a new one if the user does not exist
        $user = User::firstOrCreate([
            'username' => $agent,
        ]);

        // Authenticate the user
        \Auth::loginUsingId($user->id);
    }
}
Ad
source: stackoverflow.com
Ad