Laravel 5框架学习之用户认证_PHP
Laravel 出厂已经带有了用户认证系统,我们来看一下 routes.php,如果删除了,添加上:
Route::controllers([ 'auth' => 'Auth\AuthController', 'password' => 'Auth\PasswordController' ]);
可以使用 php artisan route:list 查看一下。浏览器中访问 /auth/login,可以看到登陆界面,最好把系统默认的 app.blade.php 中关于 google 的东西注释起来,要不然你会疯掉的。
你可以使用 register、login甚至 forget password。
实际注册一个用户,提交后失败了,实际上没有失败,只是larave自动跳转到了 /home,我们已经删除了这个控制器。你可以使用 tinker 看一下,用户已经建立了。
在 Auth\AuthController 中实际上使用了 trait,什么是 triat?well,php只支持单继承,在php5.4中添加了trait,一个trait实际上是一组方法的封装,你可以把它包含在另一个类中。像是抽象类,你不能直接实例化他。
在 Auth\AuthController 中有对 trait 的引用:
代码如下:
use AuthenticatesAndRegistersUsers;
让我们找到他,看一下注册后是怎么跳转的。他隐藏的挺深的,在 vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesAndregistersUsers.php,wow。
public function redirectPath() { if (property_exists($this, 'redirectPath')) { return $this->redirectPath; } //如果用户设置了 redirectTo 属性,则跳转到用户设置的属性,否则到home return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home'; }
OK,我们知道了,只要设定 redirectTo 这个属性就可以自定义注册后的跳转了。我们在 Auth\AuthContotroller 中修改:
代码如下:
protected $redirectTo = 'articles';
我们先使用 /auth/logout 确保我们退出,如果出错了不要害怕,我们没有默认的主页,重新访问:auth/register 新建一个用户,这次应该ok了。
再次logout,然后使用 login 登陆一下。
现在我们可以删除 form_partial 中临时设置的隐藏字段了,然后修改控制器:
public function store(Requests\ArticleRequest $request) { //你可以这样 //$request = $request->all(); //$request['user_id'] = Auth::id(); //更简单的方法 $article = Article::create($request->all()); //laravel 自动完成外键关联 Auth::user()->articles()->save($article); return redirect('articles'); }
添加一个文章,然后使用 tinker 查看一下。
中间件
我们当然不希望任何人都能发布文章,至少是登陆用才可以。我们在控制器中添加保护:
public function create() { if (Auth::guest()) { return redirect('articles'); } return view('articles.create'); }
上面的代码可以工作,有一个问题,我们需要在每一个需要保护的方法中都进行上面的处理,这样做太傻了,幸好我们有中间件。
中间件可以理解为一个处理管道,中间件在管道中的某一时刻进行处理,这个时刻可以是请求也可以是响应。依据中间件的处理规则,可能将请求重定向,也可能通过请求。
在 app/http/middleware 中包含了三个中间件,名字就可以看出是干什么,好好查看一下,注意,Closure $next 代表了下一个中间件。
在 app/http/kernel.php 中对中间件进行登记。$middleware 段声明了对所有http都进行处理的中间件,$routeMiddleware 仅仅对路由进行处理,而且你必须显示的声明要使用这其中的某一个或几个中间件。
假设我们想对整个的 ArticlesController 进行保护,我们直接在构造函数中添加中间件:
public function __construct() { $this->middleware('auth'); }
现在,任何方法都收到了保护。
但我们可能不想整个控制器都受到保护,如果只是其中的一两个方法呢?我们可以这样处理:
public function __construct() { $this->middleware('auth', ['only' => 'create']); //当然可以反过来 //$this->middleware('auth', ['except' => 'index']); }
我们不一定在控制器的构造函数中引入中间件,我们可以直接在路由中声明:
代码如下:
Route::get('about', ['middleware' => 'auth', 'uses' => 'PagesController@about']);
在 kernel.php 中提供的系统中间件,比如 'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode' 是可以让我们进入到维护模式,比如系统上线了,但现在需要临时关闭一段时间进行处理,我们可以在命令行进行处理,看一下这个中间件的工作:
代码如下:
php artisan down
访问一下网站,可以看到任何 url 的请求都是马上回来。网站上线:
代码如下:
php artisan up
我们来做一个自己的中间件:
代码如下:
php artisan make:middleware Demo
然后添加代码:
public function handle($request, Closure $next) { //如果请求中含有 foo,我们就回到控制器首页 if ($request->has('foo')) { return redirect('articles'); } return $next($request); }
如果希望在全部的请求使用中间件,需要在 kernel.php 中的 $middleware 中登记:
protected $middleware = [ ... 'App\Http\Middleware\Demo', ];
现在我们可以测试一下,假设我们访问 /articles/create?foo=bar ,我们被重定向到了首页。
让我们去除这个显示中间件,我们来创建一个真正有用的中间件。假设我们想保护某个页面,这个页面必须是管理者才能访问的。
代码如下:
php artisan make:middleware RedirectIfNotAManager
我们来添加处理代码:
public function handle($request, Closure $next) { if (!$request->user() || !$request->user()->isATeamManager()) { return redirect('articles'); } return $next($request); }
下面修改我们的模型:
public function isATeamManager() { return false; }
简单起见,我们直接返回false。这次我们把中间件放置在 kernel.php 中的$routeMiddleware 中。
protected $routeMiddleware = [ ... 'manager' => 'App\Http\Middleware\RedirectIfNotAManager', ];
我们做一个测试路由测试一下:
Route::get('foo', ['middleware' => 'manager', function() { return 'This page may only be viewed by manager'; }]);
guest身份访问或者登录身份访问都会返回主页,但是如果修改 isATeamManager() 返回 true,登录身份访问可以看到返回的信息。
以上就是本文所述的全部内容,希望对大家熟悉Laravel5框架能够有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
