'AuthAuthController', 'password' => '" />

国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
中間件
Home Backend Development PHP Tutorial Laravel 五 基礎(chǔ)(十二)- 認(rèn)證

Laravel 五 基礎(chǔ)(十二)- 認(rèn)證

Jun 13, 2016 pm 12:17 PM
auth middleware request return

Laravel 5 基礎(chǔ)(十二)- 認(rèn)證

Laravel 出廠已經(jīng)帶有了用戶認(rèn)證系統(tǒng),我們來看一下 routes.php,如果刪除了,添加上:

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

可以使用 php artisan route:list 查看一下。瀏覽器中訪問 /auth/login,可以看到登陸界面,最好把系統(tǒng)默認(rèn)的 app.blade.php 中關(guān)于 google 的東西注釋起來,要不然你會瘋掉的。

你可以使用 register、login甚至 forget password。

實際注冊一個用戶,提交后失敗了,實際上沒有失敗,只是larave自動跳轉(zhuǎn)到了 /home,我們已經(jīng)刪除了這個控制器。你可以使用 tinker 看一下,用戶已經(jīng)建立了。

Auth\AuthController 中實際上使用了 trait,什么是 triat?well,php只支持單繼承,在php5.4中添加了trait,一個trait實際上是一組方法的封裝,你可以把它包含在另一個類中。像是抽象類,你不能直接實例化他。

Auth\AuthController 中有對 trait 的引用:

<code>use AuthenticatesAndRegistersUsers;</code>

讓我們找到他,看一下注冊后是怎么跳轉(zhuǎn)的。他隱藏的挺深的,在 vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesAndregistersUsers.php,wow。

<code>	public function redirectPath()	{		if (property_exists($this, &#39;redirectPath&#39;))		{			return $this->redirectPath;		}                //如果用戶設(shè)置了 redirectTo 屬性,則跳轉(zhuǎn)到用戶設(shè)置的屬性,否則到home		return property_exists($this, &#39;redirectTo&#39;) ? $this->redirectTo : &#39;/home&#39;;	}</code>

OK,我們知道了,只要設(shè)定 redirectTo 這個屬性就可以自定義注冊后的跳轉(zhuǎn)了。我們在 Auth\AuthContotroller 中修改:

<code> protected $redirectTo = &#39;articles&#39;;</code>

我們先使用 /auth/logout 確保我們退出,如果出錯了不要害怕,我們沒有默認(rèn)的主頁,重新訪問:auth/register 新建一個用戶,這次應(yīng)該ok了。

再次logout,然后使用 login 登陸一下。

現(xiàn)在我們可以刪除 form_partial 中臨時設(shè)置的隱藏字段了,然后修改控制器:

<code>    public function store(Requests\ArticleRequest $request) {        //你可以這樣        //$request = $request->all();        //$request[&#39;user_id&#39;] = Auth::id();        //更簡單的方法        $article = Article::create($request->all());        //laravel 自動完成外鍵關(guān)聯(lián)        Auth::user()->articles()->save($article);        return redirect(&#39;articles&#39;);    }</code>

添加一個文章,然后使用 tinker 查看一下。

中間件

我們當(dāng)然不希望任何人都能發(fā)布文章,至少是登陸用才可以。我們在控制器中添加保護(hù):

<code>    public function create() {        if (Auth::guest()) {            return redirect(&#39;articles&#39;);        }        return view(&#39;articles.create&#39;);    }</code>

上面的代碼可以工作,有一個問題,我們需要在每一個需要保護(hù)的方法中都進(jìn)行上面的處理,這樣做太傻了,幸好我們有中間件。

中間件可以理解為一個處理管道,中間件在管道中的某一時刻進(jìn)行處理,這個時刻可以是請求也可以是響應(yīng)。依據(jù)中間件的處理規(guī)則,可能將請求重定向,也可能通過請求。

app/http/middleware 中包含了三個中間件,名字就可以看出是干什么,好好查看一下,注意,Closure $next 代表了下一個中間件。

app/http/kernel.php 中對中間件進(jìn)行登記。$middleware 段聲明了對所有http都進(jìn)行處理的中間件,$routeMiddleware 僅僅對路由進(jìn)行處理,而且你必須顯示的聲明要使用這其中的某一個或幾個中間件。

假設(shè)我們想對整個的 ArticlesController 進(jìn)行保護(hù),我們直接在構(gòu)造函數(shù)中添加中間件:

<code>    public function __construct() {        $this->middleware(&#39;auth&#39;);    }</code>

現(xiàn)在,任何方法都收到了保護(hù)。

但我們可能不想整個控制器都受到保護(hù),如果只是其中的一兩個方法呢?我們可以這樣處理:

<code>    public function __construct() {        $this->middleware(&#39;auth&#39;, [&#39;only&#39; => &#39;create&#39;]);        //當(dāng)然可以反過來        //$this->middleware(&#39;auth&#39;, [&#39;except&#39; => &#39;index&#39;]);    }</code>

我們不一定在控制器的構(gòu)造函數(shù)中引入中間件,我們可以直接在路由中聲明:

<code>Route::get(&#39;about&#39;, [&#39;middleware&#39; => &#39;auth&#39;, &#39;uses&#39; => &#39;[email&#160;protected]&#39;]);</code>

kernel.php 中提供的系統(tǒng)中間件,比如 'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode' 是可以讓我們進(jìn)入到維護(hù)模式,比如系統(tǒng)上線了,但現(xiàn)在需要臨時關(guān)閉一段時間進(jìn)行處理,我們可以在命令行進(jìn)行處理,看一下這個中間件的工作:

<code>php artisan down</code>

訪問一下網(wǎng)站,可以看到任何 url 的請求都是馬上回來。網(wǎng)站上線:

<code>php artisan up</code>

我們來做一個自己的中間件:

<code> php artisan make:middleware Demo</code>

然后添加代碼:

<code>	public function handle($request, Closure $next)	{        //如果請求中含有 foo,我們就回到控制器首頁        if ($request->has(&#39;foo&#39;)) {            return redirect(&#39;articles&#39;);        }		return $next($request);	}</code>

如果希望在全部的請求使用中間件,需要在 kernel.php 中的 $middleware 中登記:

<code>	protected $middleware = [		...		&#39;App\Http\Middleware\Demo&#39;,	];</code>

現(xiàn)在我們可以測試一下,假設(shè)我們訪問 /articles/create?foo=bar ,我們被重定向到了首頁。

讓我們?nèi)コ@個顯示中間件,我們來創(chuàng)建一個真正有用的中間件。假設(shè)我們想保護(hù)某個頁面,這個頁面必須是管理者才能訪問的。

<code>php artisan make:middleware RedirectIfNotAManager</code>

我們來添加處理代碼:

<code>	public function handle($request, Closure $next)	{        if (!$request->user() || !$request->user()->isATeamManager()) {            return redirect(&#39;articles&#39;);        }		return $next($request);	}</code>

下面修改我們的模型:

<code>    public function isATeamManager() {        return false;    }</code>

簡單起見,我們直接返回false。這次我們把中間件放置在 kernel.php 中的$routeMiddleware 中。

<code>	protected $routeMiddleware = [		...		&#39;manager&#39; => &#39;App\Http\Middleware\RedirectIfNotAManager&#39;,	];</code>

我們做一個測試路由測試一下:

<code>Route::get(&#39;foo&#39;, [&#39;middleware&#39; => &#39;manager&#39;, function() {    return &#39;This page may only be viewed by manager&#39;;}]);</code>

guest身份訪問或者登錄身份訪問都會返回主頁,但是如果修改 isATeamManager() 返回 true,登錄身份訪問可以看到返回的信息。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of the usage of return in C language Detailed explanation of the usage of return in C language Oct 07, 2023 am 10:58 AM

The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

What does php request mean? What does php request mean? Jul 07, 2021 pm 01:49 PM

The Chinese meaning of request is "request". It is a global variable in PHP and is an array containing "$_POST", "$_GET" and "$_COOKIE". The "$_REQUEST" variable can obtain data and COOKIE information submitted by POST or GET.

What is the execution order of return and finally statements in Java? What is the execution order of return and finally statements in Java? Apr 25, 2023 pm 07:55 PM

Source code: publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}#Output The output of the above code can simply conclude: return is executed before finally. Let's take a look at what happens at the bytecode level. The following intercepts part of the bytecode of the case1 method, and compares the source code to annotate the meaning of each instruction in

Using Auth0 for authentication in Java API development Using Auth0 for authentication in Java API development Jun 18, 2023 pm 05:30 PM

In modern software development, identity authentication is a very important security measure. Auth0 is a company that provides identity authentication services. It can help developers quickly implement multiple identity authentication methods (including OAuth2, OpenIDConnect, etc.) and provide safe and reliable authentication services. In this article, we will introduce how to use Auth0 for authentication in JavaAPI development. Step 1: Create an Auth0 account and register the application. First, we need to

How to use the urllib.request.urlopen() function to send a GET request in Python 3.x How to use the urllib.request.urlopen() function to send a GET request in Python 3.x Jul 30, 2023 am 11:28 AM

How to use the urllib.request.urlopen() function in Python3.x to send a GET request. In network programming, we often need to obtain data from a remote server by sending an HTTP request. In Python, we can use the urllib.request.urlopen() function in the urllib module to send an HTTP request and get the response returned by the server. This article will introduce how to use

How to encapsulate Vue3 Axios interceptor into request file How to encapsulate Vue3 Axios interceptor into request file May 19, 2023 am 11:49 AM

1. Create a new file called request.js and import Axios: importaxiosfrom'axios'; 2. Create a function called request and export it: This will create a function called request and export it Set up a new Axios instance with a base URL. To add timeout settings in a wrapped Axios instance, you can pass the timeout option when creating the Axios instance. exportconstrequest=axios.create({baseURL:'https://example.

What is request in PHP What is request in PHP Jun 01, 2023 am 10:12 AM

Request in PHP refers to request. It is a super global variable in PHP. It is used to collect data submitted by HTML forms and parameters in URLs. It can obtain data from GET and POST requests at the same time. Note that $_request is an associative array. , where the keys are the names of the form fields and the values ??are the values ??of the form fields. When using the $_request variable, user-entered data should always be validated and filtered to avoid security issues.

What is the Request object in PHP? What is the Request object in PHP? Feb 27, 2024 pm 09:06 PM

The Request object in PHP is an object used to handle HTTP requests sent by the client to the server. Through the Request object, we can obtain the client's request information, such as request method, request header information, request parameters, etc., so as to process and respond to the request. In PHP, you can use global variables such as $_REQUEST, $_GET, $_POST, etc. to obtain requested information, but these variables are not objects, but arrays. In order to process request information more flexibly and conveniently, you can

See all articles