Common.php 2.8 KB

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