Auth.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace app\controller\api;
  3. use app\extra\basic\Base;
  4. use app\extra\dyLife\Crypt;
  5. use app\extra\tools\CodeExtend;
  6. use app\middleware\AuthMiddleware;
  7. use app\model\saas\SaasUserOpen;
  8. use DI\Attribute\Inject;
  9. use LinFly\Annotation\Attributes\Route\Controller;
  10. use LinFly\Annotation\Attributes\Route\GetMapping;
  11. use LinFly\Annotation\Attributes\Route\Middleware;
  12. use LinFly\Annotation\Attributes\Route\PostMapping;
  13. use support\Request;
  14. use Shopwwi\WebmanAuth\Facade\Auth as AuthFacade;
  15. use support\Response;
  16. #[Controller("/dy/auth"),Middleware(AuthMiddleware::class)]
  17. class Auth extends Base
  18. {
  19. protected array $noNeedLogin = ["log2mobile"];
  20. #[Inject]
  21. protected SaasUserOpen $model;
  22. #[PostMapping("mobile")]
  23. public function log2mobile(Request $request): Response
  24. {
  25. try {
  26. $param = $request->post();
  27. $sessionKey = (new Crypt)->config($this->getDyConfig())->getSessionKey($param['login']);
  28. if (empty($sessionKey)) return error("授权登录失败");
  29. $mobile = [];
  30. if (!empty($param['code'])) {
  31. $mobileStr = (new Crypt)->config($this->getDyConfig())->token()->getMobile($param['code']);
  32. if (!empty($mobileStr)) {
  33. $mobile = $this->decrypt2code(sConf('wechat.min_private_key'), $mobileStr);
  34. }
  35. }
  36. $userInfo = [
  37. "openid" => $sessionKey['openid'],
  38. "nickname" => "DY-".strtoupper(CodeExtend::random(5,3)),
  39. "create_ip" => $request->getRealIp()
  40. ];
  41. $map = ["openid" => $sessionKey['openid']];
  42. if (!empty($mobile['purePhoneNumber'])) {
  43. $userInfo['mobile'] = $mobile['purePhoneNumber'];
  44. }
  45. $user = $this->model->where($map)->findOrEmpty();
  46. if ($user->isEmpty()) {
  47. $user->insertGetId($userInfo);
  48. }
  49. $userAuth = get_object_vars(AuthFacade::guard("user")->login(['openid' => $sessionKey['openid']]));
  50. return success("ok",$userAuth);
  51. } catch (\Throwable $th) {
  52. return error($th->getMessage());
  53. }
  54. }
  55. protected function decrypt2code($private_key, $ciphertext_str) {
  56. // 解码 base64 密文
  57. $ciphertext = base64_decode($ciphertext_str);
  58. // 使用私钥解密
  59. openssl_private_decrypt($ciphertext, $plaintext, $private_key, OPENSSL_PKCS1_PADDING);
  60. if ($plaintext === false) {
  61. return [];
  62. }
  63. return json_decode($plaintext,true);
  64. }
  65. protected function decrypt($encrypted_data, $session_key, $iv) {
  66. $data = base64_decode($encrypted_data);
  67. $key = base64_decode($session_key);
  68. $iv_decoded = base64_decode($iv);
  69. // 使用 AES-256-CBC 模式解密
  70. $decrypted = openssl_decrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv_decoded);
  71. return $decrypted;
  72. }
  73. }