1.?首先在數(shù)據(jù)庫的 users 表中添加兩個字段token、time_out
token 用于存儲用戶的 token
time_out 用于設(shè)置用戶 token 的過期時間
2.創(chuàng)建函數(shù)
checkToekn($token)
函數(shù)用于檢驗?token 是否存在, 并且更新 token。
public?function?checkToken($token) ????{ ????????$user?=?new?appindexmodelUsers(); ????????$res?=?$user->field('time_out')->where('token',?$token)->select(); ? ????????if?(!empty($res))?{ ????????????//dump(time()?-?$res[0]['time_out']); ????????????if?(time()?-?$res[0]['time_out']?>?0)?{ ????? ????????????????return?90003;?//token長時間未使用而過期,需重新登陸 ????????????} ????????????$new_time_out?=?time()?+?604800;?//604800是七天 ????????????$res?=?$user->isUpdate(true) ????????????????->where('token',?$token) ????????????????->update(['time_out'?=>?$new_time_out]); ????????????if?($res)?{ ????? ????????????????return?90001;?//token驗證成功,time_out刷新成功,可以獲取接口信息 ????????????} ????????} ? ????????return?90002;?//token錯誤驗證失敗 }
3.創(chuàng)建函數(shù)
douserLogin($username,$password)
用于驗證用戶名密碼, 并登陸, 返回 token 信息。
??public?function?douserLogin() ????{ ????????$user?=?new?appindexmodelUsers(); ????????$userisset?=?$user->where('username',?$username)->find(); ????????if?($userisset?==?null)?{ ????????????return?json_decode('{"user":"'?.?$username?.?'","code":"400","msg":"用戶不存在"}'); ????????}?else?{ ????????????$userpsisset?=?$user ????????????????->where('username',?$username) ????????????????->where('password',?sha1(md5($password)))->find(); ? ????????????if?($userpsisset?==?null)?{ ????????????????return?json_decode('{"user":"'?.?$username?.?'","code":"401","msg":"密碼錯誤"}'); ????????????}?else?{ ????????????????//session('user',?$username); ????????????????$token?=?$this->makeToken(); ????????????????$time_out?=?strtotime("+7?days"); ????????????????$userinfo?=?['time_out'?=>?$new_time_out, ????????????????????'token'?=>?$token]; ????????????????$res?=?$user->isUpdate(true) ????????????????????->where('username',?$username) ????????????????????->update($userinfo); ????????????????if?($res)?{ ????????????????????return?json_decode('{"user":"'?.?$username?.?'","toekn":'.$token.'?"code":"0","msg":"登錄成功"}'); ????????????????} ????????????} ????????} }
二、Token的概念
token是客戶端頻繁向服務(wù)器端請求數(shù)據(jù),服務(wù)器頻繁的去數(shù)據(jù)庫查詢用戶名和密碼判斷用戶名和密碼正確與否,并作出相應(yīng)的提示,在這樣的背景下,token便應(yīng)運而生了。
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載。
THE END