注册
在advanced
模板中,进入frontend/index.php?r=site%2Fsignup
页面,可以看到框架的注册页面
填写完Username
、Email
和Password
后点击Signup
后,如果格式不对,frontend/models/SignuForm
中的rules()
函数会进行初步验证,所有格式正确后,数据传输到 frontend/controllers /SiteController
中的 actionSignup()
函数中,函数加载用户输入的注册信息,在frontend/models/SignupForm
中的signup()
函数,
以下引用的文字为解释函数中的具体细节,不阅读不影响整体,因为没有折叠文字功能,故采用引用的方法,下同
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
,$attributeNames = $this->activeAttributes();
执行后返回
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
我们看一下数据表user
的字段
用户输入了username
、password
和email
,Yii2
框架是如何生成其他的字段的呢,先看password_hash
,在SignupFrom
中的signup
函数中的密码生成是setPassword
函数,该函数在common/models/User
中,setPassword
函数调用了yii2/base/Security
中的每一条规则generatePasswordHash
函数。
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
的时候的验证信息,
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();
跳转到主页。
如有错误,不吝赐教。