Laravel 5 framework learning-user authentication, laravel5 framework Authentication

Source: Internet
Author: User

Laravel 5 framework learning-user authentication, laravel5 framework Authentication

Laravel already has a user authentication system. Let's take a look at routes. php. If it is deleted, add the following:

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

You can use php artisan route: list to view details. Access/auth/login in the browser and you can see the login interface. It is best to comment out the google-related items in the default app. blade. php, or else you will go crazy.

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

Actually registering a user fails after submission, but it does not actually fail, but larave automatically jumps to/home and we have deleted this controller. You can use tinker to check whether the user has created the SDK.

Trait is actually used in Auth \ AuthController. What is triat? Well, php only supports single inheritance. With trait added in php5.4, a trait is actually a group of methods, and you can include it in another class. Such as an abstract class. You cannot instantiate it directly.

Reference trait in Auth \ AuthController:

Copy codeThe Code is as follows:
Use AuthenticatesAndRegistersUsers;

Let's find him and see how he jumps after registration. It is quite hidden, 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 attribute, this will jump to the property set by the user. Otherwise, go to home return property_exists ($ this, 'redirectto ')? $ This-> redirectTo: '/home ';}

OK. Now we know that you can set the redirectTo attribute to customize the redirection after registration. In Auth \ AuthContotroller, modify:

Copy codeThe Code is as follows:
Protected $ redirectTo = 'articles ';

We should first use/auth/logout to ensure that we exit. If something goes wrong, don't be afraid. We don't have the default home page. Re-Access: auth/register to create a new user. This time it should be OK.

Logout again, and then use login to log on.

Now we can delete the hidden field temporarily set in form_partial, and then 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 the external key Association Auth: user ()-> articles ()-> save ($ article ); return redirect ('articles ');}

Add an article and use tinker to view it.

Middleware
Of course, we do not want anyone to post articles, at least for login. We add protection in 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 handle it in every method that requires protection. This is too silly. Fortunately, we have middleware.

The middleware can be understood as a processing pipeline. The middleware can process at a certain time point in the pipeline, which can be a request or a response. Requests may be redirected or passed based on the processing rules of the middleware.

The app/http/middleware contains three middleware components. You can see what the middleware is doing by name. Check them carefully. Note that Closure $ next represents the next middleware.

Register the middleware in app/http/kernel. php. $ Middleware declares the middleware that processes all http requests. $ routeMiddleware only processes routes, and the declaration that you must display must use one or more of these middleware.

If we want to protect the entire ArticlesController, we can directly add the middleware to the constructor:

  public function __construct() {    $this->middleware('auth');  }

Now, all methods are protected.

But we may not want the entire controller to be protected. What if it is only one or two of them? We can handle it like this:

Public function _ construct () {$ this-> middleware ('auth', ['only' => 'create']); // Of course, this can be reversed. // $ this-> middleware ('auth', ['couldn't '=> 'index']);}

We do not necessarily introduce middleware in the Controller constructor. We can directly declare in the routing:

Copy codeThe Code is as follows:
Route: get ('about', ['middleware '=> 'auth', 'uses' => 'pagescontroller @ about']);

In. system Middleware provided in php, such as 'illuminate \ Foundation \ Http \ Middleware \ checkformaintenancemode', enables us to enter the maintenance mode. For example, the system is online, but now we need to temporarily close it for a period of time. We can process it in the command line and take a look at the work of this middleware:

Copy codeThe Code is as follows:
Php artisan down

Visit the website and you can see that any url request is immediately back. Website launch:

Copy codeThe Code is as follows:
Php artisan up

Let's make our own middleware:

Copy codeThe Code is as follows:
Php artisan make: middleware Demo

Then add the Code:

Public function handle ($ request, Closure $ next) {// if the request contains foo, we will return to the Controller homepage if ($ request-> has ('foo ')) {return redirect ('articles ');} return $ next ($ request );}

If you want to use middleware in all requests, You need to register in $ middleware in kernel. php:

 protected $middleware = [ ... 'App\Http\Middleware\Demo', ];

Now let's test it. Suppose we access/articles/create? Foo = bar. We are redirected to the homepage.

Let's remove this display middleware and create a truly useful middleware. Suppose we want to protect a page, which must be accessible by managers.

Copy codeThe Code is 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); }

Modify our model as follows:

  public function isATeamManager() {    return false;  }

For simplicity, false is returned directly. This time we place the middleware in $ routeMiddleware in kernel. php.

 protected $routeMiddleware = [ ... 'manager' => 'App\Http\Middleware\RedirectIfNotAManager', ];

Let's test the route:

Route::get('foo', ['middleware' => 'manager', function() {  return 'This page may only be viewed by manager';}]);

The home page is returned for access by guest identity or logon identity. However, if isATeamManager () is modified, true is returned.

The above is all the content described in this article. I hope you will be familiar with the Laravel5 framework.

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.