common.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. use think\Db;
  3. /**
  4. * @param $account
  5. * @return string
  6. * @throws \think\db\exception\DataNotFoundException
  7. * @throws \think\db\exception\DbException
  8. * @throws \think\db\exception\ModelNotFoundException
  9. * @throws \think\exception\DbException
  10. */
  11. function makeToken($account){
  12. $now=time();
  13. $str = $account['username'].$account['salt'].$now;
  14. $token = base64_encode($str);
  15. $has = Db::name("account_token")->where(["accountid"=>$account['id']])->find();
  16. if($has){
  17. Db::name("account_token")->where(["accountid"=>$account['id']])->update(["token"=>$token,"expiretime"=>date("Y-m-d H:i:s",$now+1800)]);
  18. }else{
  19. Db::name("account_token")->insert(["token"=>$token,"expiretime"=>date("Y-m-d H:i:s",$now+1800),
  20. "accountid"=>$account['id']]);
  21. }
  22. return $token;
  23. }
  24. /**
  25. * @param $token
  26. */
  27. function verifyToken($token){
  28. $has = Db::name("account_token")->where(["token"=>$token])->find();
  29. if(!$has){
  30. return ["code"=>101,"msg"=>"token不存在"];
  31. }
  32. if(strtotime($has['expiretime'])<=time()){
  33. return ["code"=>102,"msg"=>"token已失效"];
  34. }
  35. $account = Db::name("account")->where(["id"=>$has['accountid'],"is_del"=>0])->find();
  36. if(!$account){
  37. return ["code"=>103,"msg"=>"未找到账户"];
  38. }
  39. if(strtotime($account['expiretime'])<=time()){
  40. return ["code"=>104,"msg"=>"账户已失效"];
  41. }
  42. $token_str = base64_decode($token);
  43. $account_str= substr($token_str,0,-10);
  44. if($account_str==$account['username'].$account['salt']){
  45. Db::name("account_token")->where(["token"=>$token])->update(["expiretime"=>date("Y-m-d H:i:s",time()+1800)]);
  46. return ["code"=>0,"msg"=>"账户有效"];
  47. }else{
  48. return ["code"=>105,"msg"=>"账户token无效"];
  49. }
  50. }