User.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * Created by PhpStorm
  4. * User:林志杰
  5. * Email:[email protected]
  6. * Motto:纵有疾风起,人生不言弃!
  7. * Time:2020/2/8 1:24
  8. */
  9. declare(strict_types=1);
  10. namespace app\common\business;
  11. use app\common\lib\Str;
  12. use app\common\lib\Time;
  13. use app\common\model\mysql\User as UserModel;
  14. class User
  15. {
  16. public $userObj = null;
  17. public function __construct()
  18. {
  19. $this->userObj = new UserModel();
  20. }
  21. public function login(array $data)
  22. {
  23. $redisCode = cache(config('redis.code_pre') . $data['phoneNumber']);
  24. if (empty($redisCode) || $redisCode !== $data['code']) {
  25. throw new \think\Exception('验证码不存在', -1009);
  26. }
  27. // 需要去判断表 是否有 用户记录phoneNumber
  28. // 生成token
  29. $user = $this->userObj->getUserByPhoneNumber($data['phoneNumber']);
  30. if (!$user) {
  31. $username = "singewa粉-{$data['phoneNumber']}";
  32. $userData = [
  33. 'username' => $username,
  34. 'phone_number' => $data['phoneNumber'],
  35. 'type' => $data['type'],
  36. 'status' => config('status.mysql.table_normal'),
  37. ];
  38. try {
  39. $this->userObj->save($userData);
  40. $userId = $this->userObj->id;
  41. } catch (\Exception $e) {
  42. throw new \think\Exception('数据库内部异常');
  43. }
  44. } else {
  45. // 用户存在,更新表数据
  46. $userId = $user->id;
  47. $username = $user->username;
  48. }
  49. $token = Str::getLoginToken($data['phoneNumber']);
  50. $redisData = [
  51. 'id' => $userId,
  52. 'username' => $username,
  53. ];
  54. $res = cache(config('redis.token_pre') . $token, $redisData, Time::userLoginExpiresTime($data['type']));
  55. return $res ? ['token' => $token, 'username' => $username] : false;
  56. }
  57. }