Creating the user model
First of all, we need to define the model that is going to be used to represent the
users of our application. Laravel already provides you with sensible defaults inside
app/config/auth.php, where you change the model or table that is used to store
your user accounts.

It also comes with an existing User model inside app/models/User.php. For the
purposes of this application, we are going to simplify it slightly, remove certain
class variables, and add new methods so that it can interact with the Cat model:

use Illuminate\Auth\UserInterface;
class User extends Eloquent implements UserInterface {
public function getAuthIdentifier() {
return $this->getKey();
}
public function getAuthPassword() {
return $this->password;
}
public function cats(){
return $this->hasMany('Cat');
}
public function owns(Cat $cat){
return $this->id == $cat->owner;
}
public function canEdit(Cat $cat){
return $this->is_admin or $this->owns($cat);
}
}

Remember that an interface does not give any implementation details. It is nothing
more than a contract that specifies the names of the methods that a class should
define when it implements the interface, in this case, getAuthIdentifier()
and getAuthPassword(). These methods are used internally by Laravel when
authenticating a user. The next method, cats(), simply defines the has many
relationship with the Cat model. The last two methods will be used to check
whether a given Cat instance is owned or editable by the current User instance.

Creating the necessary database schema
Now that we have defined a User model, we need to create the database schema
for it and alter the existing cats table to add information about the owner. Start by
creating a new migration:

$ php artisan migrate:make create_users
And then define the up method with the necessary database columns:

Authentication routes and views
Let's now look at the new routes and views. We will start by making some amends to
the master layout (app/views/master.blade.php) to display the login link to guests
and the logout link to users who are logged in. To check whether a visitor is logged
in, we use the Auth::check() method:

<div class="container">
<div class="page-header">
<div class="text-right">
@if(Auth::check())
Logged in as
<strong>{{{Auth::user()->username}}}</strong>
{{link_to('logout', 'Log Out')}}
@else
{{link_to('login', 'Log In')}}
@endif
</div>
@yield('header')
</div>
@if(Session::has('message'))
<div class="alert alert-success">
{{Session::get('message')}}
</div>
@endif
@if(Session::has('error'))
<div class="alert alert-warning">
{{Session::get('error')}}
</div>
@endif
@yield('content')
</div>

This code replaces the contents of the <body> tag in our previous template file.
A section for any error messages was also included below the header.
The route to display this login form could not be easier:
Route::get('login', function(){
return View::make('login');
});
If you were curious as to where and why Laravel uses the make methods
in various places, it is only there to maintain PHP 5.3 compatibility, which
does not support class member access on instantiation, and therefore, does
not let you write return new View('login');.

The route that handles login attempts will simply pass the username and password
input values to the Auth::attempt method. When this method returns true, we
simply redirect the visitor to the intended location. If this fails, we redirect the user
back to where he came from with Redirect::back() with the input values and an
error message.
Route::post('login', function(){
if(Auth::attempt(Input::only('username', 'password'))) {
return Redirect::intended('/');
} else {
return Redirect::back()
->withInput()
->with('error', "Invalid credentials");
}
});

But how does Laravel know what our intended location was? If you open
app/filters.php and look at the auth filter, you will see that it redirects guests
to the login route with the Redirect::guest() method. This method stores the
requested path in a session variable, which is then used by the intended() method.
The parameter passed to this method is the fallback route to which users should be
redirected if there is no request path in the session information.
Note also that there is a filter called guest that does the opposite of
auth; you could use it on the login route if you wanted to prevent
logged-in users from accessing it. With this filter in place, logged-in users
will be redirected to the home page instead. You can change this behavior
inside app/filters.php.

laravel Authentication and Security的更多相关文章

  1. [PHP] 浅谈 Laravel Authentication 的 auth:api

    auth:api 在 Laravel 的 Routing , Middleware , API Authentication 主题中都有出现. 一. 在 Routing 部分可以知道 auth:api ...

  2. [PHP] 浅谈 Laravel Authentication 的 guards 与 providers

    从文档的简单介绍上来讲,有一些抽象. 个人感觉,对于概念上的大多数不理解主要还是来自于 文档不是讲设计思路,而是实际操作. 查看英文文档,通常来说可以给你最准确的直觉,而本地翻译一般比较字面或者带有理 ...

  3. [转]The NTLM Authentication Protocol and Security Support Provider

    本文转自:http://davenport.sourceforge.net/ntlm.html#ntlmHttpAuthentication The NTLM Authentication Proto ...

  4. [不错]A step-by-step guide to enabling security, TLS/SSL, and PKI authentication in Elasticsearch

    Now posted on the Elastic blog December 12, 2018 update: This article has been published on Elastic’ ...

  5. How-to: Enable User Authentication and Authorization in Apache HBase

    With the default Apache HBase configuration, everyone is allowed to read from and write to all table ...

  6. 【Spring】关于Boot应用中集成Spring Security你必须了解的那些事

    Spring Security Spring Security是Spring社区的一个顶级项目,也是Spring Boot官方推荐使用的Security框架.除了常规的Authentication和A ...

  7. HttpClient(4.3.5) - HTTP Authentication

    HttpClient provides full support for authentication schemes defined by the HTTP standard specificati ...

  8. cloud computing platform,virtual authentication encryption

    Distributed Management Task Forcevirtual Ethernet port aggregator encryption,authenticating,local ac ...

  9. 一个HTTP Basic Authentication引发的异常

    这几天在做一个功能,其实很简单.就是调用几个外部的API,返回数据后进行组装然后成为新的接口.其中一个API是一个很奇葩的API,虽然是基于HTTP的,但既没有基于SOAP规范,也不是Restful风 ...

随机推荐

  1. 使用MySQL数据库将汉字转换成拼音的一个C语言小程序

    环境: mysql:mysql-5.1.65 centos:centos 6.5 编译命令: gcc -o chinesetopinyin chinesetopinyin.c -L/usr/lib/m ...

  2. vs2013编译qt程序后中文出现乱码

    我的vs是2013版的,qt是5.4.2,在使用vc将程序编译好后并运行时在界面上输出的中文出现了乱码,在网上找了很长时间终于找到了解决方法: QString str = QStringLiteral ...

  3. struts2中的常量

    struts2中的常量: 在:struts2-core-2.1.8.1\org\apache\struts2\default.properties 文件里 <!-- 配制i18n国际化--> ...

  4. SQL Server 2008 R2密钥序列号

    SQL Server 2008 R2密钥序列号 序列号: 开发版(Developer): PTTFM-X467G-P7RH2-3Q6CG-4DMYB 企业版(Enterprise): JD8Y6-HQ ...

  5. PHP发起get post put delete请求

    <?php class commonFunction{ function callInterfaceCommon($URL,$type,$params,$headers){ $ch = curl ...

  6. php安装libevent

    libevent扩展安装 libevent-2.0.16-stable.tar http://libevent.org/ [plain] view plaincopy cd libevent-2.0. ...

  7. Node.js 【使用npm安装一些包失败之笔记】

    镜像使用方法(三种办法任意一种都能解决问题,建议使用第三种,将配置写死,下次用的时候配置还在): 1.通过config命令 npm config set registry https://regist ...

  8. Python遍历路径下所有文件

    开始学Python,这篇文章来自于应用需求. os.walk很方便,下面写了两个版本的函数进行遍历,分别是不使用walk和使用walk的. import sys import string impor ...

  9. Android中获取应用程序(包)的信息-----PackageManager的使用(一)

    本节内容是如何获取Android系统中应用程序的信息,主要包括packagename.label.icon.占用大小等.具体分为两个 部分,计划如下:  第一部分: 获取应用程序的packagenam ...

  10. mysql 的 存储结构(储存引擎)

    1 MyISAM:这种引擎是mysql最早提供的.这种引擎又可以分为静态MyISAM.动态MyISAM 和压缩MyISAM三种:    静态MyISAM:如果数据表中的各数据列的长度都是预先固定好的, ...