在advanced
模板中,进入frontend/index.php?r=site%2Fsignup
页面,能够看到框架的注册页面php
填写完Username
、Email
和Password
后点击Signup
后,若是格式不对,frontend/models/SignuForm
中的rules()
函数会进行初步验证,全部格式正确后,数据传输到 frontend/controllers /SiteController
中的 actionSignup()
函数中,函数加载用户输入的注册信息,在frontend/models/SignupForm
中的signup()
函数,web
如下引用的文字为解释函数中的具体细节,不阅读不影响总体,由于没有折叠文字功能,故采用引用的方法,下同if (!$this->validate()) { return null; }
signup()
函数首先调用yii2/base/Model
中的validate()
函数进行验证
第一步,清除使用frontend/models/SignuForm
中的rules()
函数在用户输入时的错误信息数据库if ($clearErrors) { $this->clearErrors(); }第二步,
beforeValidate()
函数触发beforeValidate
事件并返回true
第三步,设置scenario
,默认是default
第四步,由于这里的$attributeNames
为null
,windows$attributeNames = $this->activeAttributes();执行后返回yii2
array(3) { [0]=> string(8) "username" [1]=> string(5) "email" [2]=> string(8) >"password" }第五步,
$this->getActiveValidators()
会获得frontend/models/SignuForm
中的rules()
中11条验证规则给validateAttributes()
进行验证
第六步,执行afterValidate()
函数触发afterValidate
事件
最后 若是全部验证都经过,$this->hasErrors()
为false
,因此函数最后返回true
cookie
咱们看一下数据表user
的字段session
用户输入了username
、password
和email
,Yii2
框架是如何生成其余的字段的呢,先看password_hash
,在SignupFrom
中的signup
函数中的密码生成是setPassword
函数,该函数在common/models/User
中,setPassword
函数调用了yii2/base/Security
中的每一条规则generatePasswordHash
函数。app
if (function_exists('password_hash')) { /** @noinspection PhpUndefinedConstantInspection */ return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]); }
若是有,就使用password_hash
函数进行加密,若是PHP
没有password_hash
函数,就使用crypt
函数加密,初步判断应该是为了兼容PHP
低于5.5的版本,毕竟大于5.5的版本才开始有password_hash
函数框架
common/models/User
的signup()
函数在对password
加密后,就会继续生成一个auth key
,auth key
是当用户在登陆的时候点击 remember me
的时候的验证信息,frontend
auth key
生成的方法也是在yii2/base/Security
中的generateRandomString
,generateRandomString
调用generateRandomKey
函数,若是你的PHP
版本为是5.2~5.6或者是7,那就是用random_bytes
生成一个32个字节的字符串,若是不是,当你用的系统时windows
而且安装了OpenSSL
,就会调用openssl_random_pseudo_bytes
函数生成,若是你未安装OpenSSL
,就会使用mcrypt_create_iv
生成。
若是你使用的系统不是windows
,就须要调用/dev/urandom
,FreeBSD
系统特殊,会调用/dev/random
,而后调用stream_set_read_buffer
方法生成8字节的字符文件,生成后,经过fread
函数读取该文件中的32个字节,而后返回该数据。
password_reset_token
在用户注册的时候是为空的,当用户忘记密码在登陆页面点击reset it
后生成的,用来给用法发送邮件后重置密码时进行验证。status
在common/models/User
中定义的
const STATUS_DELETED = 0; const STATUS_ACTIVE = 10;
用户注册时rules
中的status
默认为为10,created_time
和updated_time
也是在common/models/User
中的behaviors()
函数中生成
用户的数据验证合格,加上框架生成的数据,而后存储进数据的user
表里。
关于frontend/controllers/SiteController
中的actionSignup()
中的
if (Yii::$app->getUser()->login($user)) { return $this->goHome(); }
就是用户注册后,这时该用户的数据已经写入数据库了,开始登陆的过程了
登陆的过程在yii2/web/User
里的login()
函数中
第一步,执行beforeLogin()
函数触发beforeLogin
事件
第二步,switchIdentity()
函数把我的信息换成当前用户的信息,把全部的cookie
都销毁,而后把当前用户的信息都存入到session
和cookie
中
第三步,获取当前用户的id
和用户登陆的ip
,并写入到log
中
第四步,执行afterLogin()
函数触发afterLogin
事件
最后 返回true
判断登陆成功后,return $this->goHome();
跳转到主页。
若有错误,不吝赐教。