_php example of user authentication for Laravel 5 Framework Learning

Source: Internet
Author: User
Tags auth closure

Laravel Factory has a user authentication system, we look at the routes.php, if deleted, add on:

Route::controllers ([
  ' auth ' => ' auth\authcontroller ',
  ' password ' => ' Auth\passwordcontroller '
)] ;

You can use the PHP artisan route:list to view it. Browser access to/auth/login, you can see the login interface, it is best to the system default app.blade.php in the comments about Google things, or you will be crazy.

You can use register, login, or even forget password.

Actually registered a user, submitted failed, actually did not fail, just larave automatically jump to the/home, we have removed this controller. You can use tinker to look at the user has been established.

In the Auth\authcontroller actually used trait, what is Triat? Well,php only supports single inheritance, adding trait in php5.4, a trait is actually a package of methods that you can include in another class. Like an abstract class, you can't instantiate him directly.

There are references to trait in Auth\authcontroller:

Copy Code code as follows:

Use Authenticatesandregistersusers;

Let's find him and see how it jumps after registering. He hides quite deep, in the Vendor/laravel/framework/src/illuminate/foundation/auth/authenticatesandregistersusers.php,wow.

 Public Function Redirectpath ()
 {
 if (property_exists ($this, ' Redirectpath ')
 } {return
  $this-> Redirectpath;
 }
    
    If the user sets the Redirectto property, jumps to the user-set property, or to the home return
 property_exists ($this, ' Redirectto ')? $this->redirectto: ' /home ';
 }

OK, we know, as long as the set Redirectto this property can be customized after the registration of the jump. We modified in the Auth\authcontotroller:

Copy Code code as follows:

protected $redirectTo = ' articles ';

We first use/auth/logout to ensure that we exit, if there is a mistake do not be afraid, we do not have the default home page, re-access: auth/register New user, this time should be OK.

Logout again, then use login login.

Now we can remove the temporarily hidden field from the Form_partial and modify the controller:

  Public function Store (requests\articlerequest $request) {
    //You can do this
    //$request = $request->all ();
    $request [' user_id '] = Auth::id ();

    Simpler method
    $article = Article::create ($request->all ());
    Laravel automatically completes foreign key Association
    Auth::user ()->articles ()->save ($article);

    Return redirect (' articles ');
  }

Add an article, and then use Tinker to view it.

Middleware
We certainly do not want anyone to be able to post articles, at least for landing purposes. We add protection to the controller:

  Public Function Create () {
    if (auth::guest ()) {return
      redirect (' articles ');
    }
    Return view (' Articles.create ');
  }

The above code can work, there is a problem, we need to be in every way to protect the above processing, this is silly, fortunately we have middleware.

Middleware can be understood as a processing pipeline, the middleware in the pipeline at a time to process, this moment can be a request or a response. Depending on the processing rules of the middleware, the request may be redirected or may be requested.

App/http/middleware contains three middleware, name can see what is doing, take a good look, note that Closure $next represents the next middleware.

The middleware is registered in the app/http/kernel.php. $middleware section declares the middleware that handles all HTTP, $routeMiddleware only the routing process, and you must display a declaration to use one or more of these middleware.

Assuming that we want to protect the entire articlescontroller, we add the middleware directly to the constructor:

  Public Function __construct () {
    $this->middleware (' auth ');
  }

Now, any method has been protected.

But we may not want the entire controller to be protected, if only one or two of these methods? We can handle this:

  Public Function __construct () {
    $this->middleware (' auth ', [' Only ' => ' create ']);
    Of course it can be reversed
    //$this->middleware (' auth ', [' except ' => ' Index ']);
  }

We do not necessarily introduce middleware into the constructor of the controller, we can declare it directly in the route:

Copy Code code as follows:

Route::get (' About ', [' Middleware ' => ' auth ', ' uses ' => ' pagescontroller@about ']);

The system middleware provided in kernel.php, such as ' Illuminate\foundation\http\middleware\checkformaintenancemode ', allows us to enter the maintenance mode, such as the system on-line, But now we need to temporarily shut down for a while, we can do it at the command line and look at the work of this middleware:

Copy Code code as follows:

PHP Artisan Down

Visit the website and you can see any URL requests are coming back immediately. Website online:

Copy Code code as follows:

PHP Artisan up

Let's do one of our own middleware:

Copy Code code as follows:

PHP Artisan Make:middleware Demo

Then add the code:

 Public function handle ($request, Closure $next)
 {
    //If the request contains Foo, we go back to the controller home
    if ($request->has (' foo ')) { return
      Redirect (' articles ');
    }

 Return $next ($request);
 

If you want to use middleware for all requests, you need to enlist in the $middleware in the kernel.php:

 protected $middleware = [
 ...
 ] App\http\middleware\demo ',

 ];

Now we can test, assuming we visit/articles/create?foo=bar, we are redirected to the home page.

Let's get rid of this display middleware and we'll create a really useful middleware. If we want to protect a page, this page must be a manager to access.

Copy Code code as follows:

PHP Artisan Make:middleware Redirectifnotamanager

Let's add the processing code:

 Public function handle ($request, Closure $next)
 {
    if (! $request->user () | |! $request->user ()-> Isateammanager ()) {return
      redirect (' articles ');
    }

 Return $next ($request);
 

Here's how to modify our model:

  Public Function Isateammanager () {return
    false;
  }

For the sake of simplicity, we return false directly. This time we put the middleware in the $routemiddleware of the kernel.php.

 protected $routeMiddleware = [
 ...
 ] Manager ' => ' App\http\middleware\redirectifnotamanager ',
 ];

Let's do a test route test:

Route::get (' foo ', [' Middleware ' => ' manager '), function () {return ' the ' this page ' is
  viewed by manager ';
}]);

Either guest identity access or logon identity access will return to the home page, but if the Modify Isateammanager () returns True, logon identity access can see the returned information.

The above is the entire content described in this article, I hope to be familiar with the LARAVEL5 framework can be helpful.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.