Common.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace app\api\controller;
  3. use ba\Random;
  4. use Throwable;
  5. use ba\Captcha;
  6. use think\Response;
  7. use ba\ClickCaptcha;
  8. use think\facade\Config;
  9. use app\common\facade\Token;
  10. use app\common\controller\Api;
  11. use app\admin\library\Auth as AdminAuth;
  12. use app\common\library\Auth as UserAuth;
  13. class Common extends Api
  14. {
  15. /**
  16. * 图形验证码
  17. * @throws Throwable
  18. */
  19. public function captcha(): Response
  20. {
  21. $captchaId = $this->request->request('id');
  22. $config = array(
  23. 'codeSet' => '123456789', // 验证码字符集合
  24. 'fontSize' => 22, // 验证码字体大小(px)
  25. 'useCurve' => false, // 是否画混淆曲线
  26. 'useNoise' => true, // 是否添加杂点
  27. 'length' => 4, // 验证码位数
  28. 'bg' => array(255, 255, 255), // 背景颜色
  29. );
  30. $captcha = new Captcha($config);
  31. return $captcha->entry($captchaId);
  32. }
  33. /**
  34. * 点选验证码
  35. */
  36. public function clickCaptcha(): void
  37. {
  38. $id = $this->request->request('id/s');
  39. $captcha = new ClickCaptcha();
  40. $this->success('', $captcha->creat($id));
  41. }
  42. /**
  43. * 点选验证码检查
  44. * @throws Throwable
  45. */
  46. public function checkClickCaptcha(): void
  47. {
  48. $id = $this->request->post('id/s');
  49. $info = $this->request->post('info/s');
  50. $unset = $this->request->post('unset/b', false);
  51. $captcha = new ClickCaptcha();
  52. if ($captcha->check($id, $info, $unset)) $this->success();
  53. $this->error();
  54. }
  55. public function refreshToken(): void
  56. {
  57. $refreshToken = $this->request->post('refreshToken');
  58. $refreshToken = Token::get($refreshToken);
  59. if (!$refreshToken || $refreshToken['expire_time'] < time()) {
  60. $this->error(__('Login expired, please login again.'));
  61. }
  62. $newToken = Random::uuid();
  63. // 管理员token刷新
  64. if ($refreshToken['type'] == AdminAuth::TOKEN_TYPE . '-refresh') {
  65. $baToken = get_auth_token();
  66. if (!$baToken) {
  67. $this->error(__('Invalid token'));
  68. }
  69. Token::delete($baToken);
  70. Token::set($newToken, AdminAuth::TOKEN_TYPE, $refreshToken['user_id'], (int)Config::get('buildadmin.admin_token_keep_time'));
  71. }
  72. // 会员token刷新
  73. if ($refreshToken['type'] == UserAuth::TOKEN_TYPE . '-refresh') {
  74. $baUserToken = get_auth_token(['ba', 'user', 'token']);
  75. if (!$baUserToken) {
  76. $this->error(__('Invalid token'));
  77. }
  78. Token::delete($baUserToken);
  79. Token::set($newToken, UserAuth::TOKEN_TYPE, $refreshToken['user_id'], (int)Config::get('buildadmin.user_token_keep_time'));
  80. }
  81. $this->success('', [
  82. 'type' => $refreshToken['type'],
  83. 'token' => $newToken
  84. ]);
  85. }
  86. }