I'm working in a web project using Laravel 5.2
My use case is very simple: Before rendering any page, verify if the user is authenticated. If not, provide a login form with custom authentication (not the Eloquent's default stuff)
After reading about this scenario I have:
// routes.php Route::get('/', 'HomeController@index'); Then if I want all my pages secured, I require the middleware auth in controller's constructor. All my controllers should follow the same pattern if I want to request a logged in user before serving any page.
// app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; class HomeController extends Controller { public function __construct() { $this->middleware('auth'); } public function index() { return view('home'); } } So far, so good. If I visit my app at '/' I'm redirected to a /login page.
I created the login page:
// views/auth/login.blade.php @extends('layouts.app') @section('content') <form class="form-signin" method="post" action="{{ url ('/login') }}"> {!! csrf_field() !!} <h2 class="form-signin-heading">Please sign in</h2> <label for="inputUsername" class="sr-only">Username</label> <input type="text" id="inputUsername" class="form-control" placeholder="Username" name="username" required autofocus> <label for="inputPassword" class="sr-only">Password</label> <input type="password" id="inputPassword" class="form-control" placeholder="Password" name="password" required> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> </form> @endsection Please notice the action of the form that redirects to /login. Then I update the routes.php by providing the new following routes:
// Authentication Routes... Route::get('login', 'Auth\AuthController@showLoginForm'); Route::post('login', 'Auth\AuthController@login'); Route::get('logout', 'Auth\AuthController@logout'); Route::get('/', 'HomeController@index'); With these new routes I'm catching login/logout scenarios and assigning AuthController's methods to handle them.
On the already implemented AuthController, I guess I need to define these methods.
I was not able to make this to work or maybe I'm doing this custom authentication in a wrong way.
I have:
// app/Http/Auth/AuthController.php <?php namespace App\Http\Controllers\Auth; use App\User; use Validator; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\ThrottlesLogins; use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers; class AuthController extends Controller { use AuthenticatesAndRegistersUsers, ThrottlesLogins; protected $redirectTo = '/'; public function __construct() { $this->middleware($this->guestMiddleware(), ['except' => 'logout']); } // ... lot of default stuff .. protected function login($data) { // // do custom login authentication with $data // ie: validate thru a web service or something // return redirect()->intended('/'); } } Any suggestions on how to implement this?