Login.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace app\controller\common;
  3. use app\model\system\SystemConfig;
  4. use app\model\system\SystemUser;
  5. use app\validate\system\LoginValidate;
  6. use Shopwwi\WebmanAuth\Auth;
  7. use support\Request;
  8. use support\Response;
  9. use think\exception\ValidateException;
  10. use think\facade\Db;
  11. use Tinywan\Captcha\Captcha;
  12. class Login
  13. {
  14. protected array $noNeedLogin = ["getSystemData","setLogin"];
  15. public function setLogin(Request $request): Response
  16. {
  17. try {
  18. $param = $request->post();
  19. validate(LoginValidate::class)->scene("login")->check($param);
  20. if (Captcha::check($param['code'],$param['key']) === false) return errorTrans("error.captcha");
  21. $map = ["is_deleted" => 0,"username" => $param['username']];
  22. [$state,$msg,$user] = $this->checkLogin($map,$param);
  23. if (!$state) return error($msg);
  24. return successTrans("success.login",get_object_vars((new Auth)->guard("admin")->login($user)));
  25. } catch (ValidateException $th) {
  26. return error($th->getError());
  27. } catch (\Throwable $throwable) {
  28. return error($throwable->getMessage());
  29. }
  30. }
  31. protected function checkLogin(array $map = [],array $param = []): array
  32. {
  33. $user = (new SystemUser)->where($map)->findOrEmpty();
  34. if ($user->isEmpty()) return [0,trans("error.user-empty"),[]];
  35. if ($user['status'] <> 1) return [0,trans("error.user-status"),[]];
  36. if (md5($param['password'].$user['salt']) <> $user['password']) return [0,trans("error.passwd"),[]];
  37. $user->login_at = getDateFull();
  38. $user->login_ip = request()->getRealIp();
  39. $user->login_num = Db::raw("login_num+1");
  40. $user->save();
  41. return [1,'success',$user->toArray()];
  42. }
  43. public function getLoginUser(): Response
  44. {
  45. try {
  46. $userData = (new Auth)->guard("admin")->user()->toArray();
  47. if (isset($userData['password'])) unset($userData['password']);
  48. return successTrans("success.data",[
  49. "username" => $userData['username'],
  50. "userId" => $userData['id'],
  51. "name" => $userData['truename'],
  52. "super" => $userData['is_super'],
  53. "type" => $userData['type'],
  54. ]);
  55. } catch (\Throwable $throwable) {
  56. return error($throwable->getMessage());
  57. }
  58. }
  59. public function getSystemData(): Response
  60. {
  61. try {
  62. $captcha = Captcha::base64();
  63. $service = (new SystemConfig)->where("type","service")->column("value","name");
  64. return successTrans("success.data",compact("captcha",'service'));
  65. } catch (\Throwable $throwable) {
  66. return error($throwable->getMessage());
  67. }
  68. }
  69. }