LoginService.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Niucloud-admin 企业快速开发的saas管理平台
  4. // +----------------------------------------------------------------------
  5. // | 官方网址:https://www.niucloud.com
  6. // +----------------------------------------------------------------------
  7. // | niucloud团队 版权所有 开源版本可自由商用
  8. // +----------------------------------------------------------------------
  9. // | Author: Niucloud Team
  10. // +----------------------------------------------------------------------
  11. namespace app\service\api\login;
  12. use app\dict\member\MemberLoginTypeDict;
  13. use app\dict\member\MemberRegisterTypeDict;
  14. use app\dict\sys\AppTypeDict;
  15. use app\dict\sys\SmsDict;
  16. use app\model\member\Member;
  17. use app\service\api\captcha\CaptchaService;
  18. use app\service\api\member\MemberConfigService;
  19. use app\service\api\member\MemberService;
  20. use app\service\api\notice\NoticeService;
  21. use core\base\BaseApiService;
  22. use core\exception\ApiException;
  23. use core\exception\AuthException;
  24. use core\util\TokenAuth;
  25. use Exception;
  26. use think\facade\Cache;
  27. use think\facade\Log;
  28. use Throwable;
  29. /**
  30. * 登录服务层
  31. * Class BaseService
  32. * @package app\service
  33. */
  34. class LoginService extends BaseApiService
  35. {
  36. public function __construct()
  37. {
  38. parent::__construct();
  39. $this->model = new Member();
  40. }
  41. /**
  42. * 会员注册
  43. * @param $data
  44. */
  45. public function register($data)
  46. {
  47. //检测设置是否自动注册
  48. //自动注册检测授权信息
  49. //注册登录
  50. }
  51. /**
  52. * 登录操作
  53. * @param Member $member_info
  54. * @param string $login_type
  55. * @return array
  56. */
  57. public function login(Member $member_info, string $login_type)
  58. {
  59. //绑定第三方授权
  60. $this->bingOpenid($member_info);
  61. if (!$member_info->status) throw new ApiException('MEMBER_LOCK');
  62. $member_info->login_time = time();
  63. $member_info->login_ip = $this->request->ip();
  64. $member_info->login_channel = $this->channel;
  65. $member_info->login_type = $login_type;
  66. $member_info->login_count++;
  67. $member_info->last_visit_time = time();
  68. $member_info->save();
  69. $token_info = $this->createToken($member_info);
  70. event("MemberLogin", $member_info);
  71. return [
  72. 'token' => $token_info['token'],
  73. 'expires_time' => $token_info['params']['exp'],
  74. 'mobile' => $member_info->mobile
  75. ];
  76. }
  77. /**
  78. * 账号登录
  79. * @param string $username
  80. * @param string $password
  81. * @return array|false
  82. */
  83. public function account(string $username, string $password)
  84. {
  85. $member_service = new MemberService();
  86. $member_info = $member_service->findMemberInfo(['username|mobile' => $username]);
  87. if ($member_info->isEmpty()) throw new AuthException('MEMBER_NOT_EXIST');//账号不存在
  88. if (!check_password($password, $member_info->password)) return false;//密码与账号不匹配
  89. return $this->login($member_info, MemberLoginTypeDict::USERNAME);
  90. }
  91. /**
  92. * 手机号登录
  93. * @param string $mobile
  94. * @return array
  95. */
  96. public function mobile(string $mobile){
  97. //校验手机验证码
  98. $this->checkMobileCode($mobile);
  99. //登录注册配置
  100. $config = (new MemberConfigService())->getLoginConfig();
  101. $is_mobile = $config['is_mobile'];
  102. $is_bind_mobile = $config[ 'is_bind_mobile' ];
  103. if ($is_mobile != 1 && $is_bind_mobile != 1) throw new AuthException('MOBILE_LOGIN_UNOPENED');
  104. $member_service = new MemberService();
  105. $member_info = $member_service->findMemberInfo(['mobile' => $mobile]);
  106. if ($member_info->isEmpty()) {
  107. //开启强制绑定手机号,登录会自动注册并绑定手机号
  108. if ($is_bind_mobile == 1) {
  109. $data = array (
  110. 'mobile' => $mobile,
  111. );
  112. return (new RegisterService())->register($mobile, $data, MemberRegisterTypeDict::MOBILE, false);
  113. } else {
  114. throw new AuthException('MEMBER_NOT_EXIST');//账号不存在
  115. }
  116. }
  117. return $this->login($member_info, MemberLoginTypeDict::MOBILE);
  118. }
  119. /**
  120. * 生成token
  121. * @param $member_info
  122. * @return array|null
  123. */
  124. public function createToken($member_info): ?array
  125. {
  126. $expire_time = env('system.api_token_expire_time') ?? 3600;//todo 不一定和管理端合用这个token时限
  127. return TokenAuth::createToken($member_info->member_id, AppTypeDict::API, ['member_id' => $member_info->member_id, 'username' => $member_info->username], $expire_time);
  128. }
  129. /**
  130. * 登陆退出(当前账户)
  131. */
  132. public function logout(): ?bool
  133. {
  134. self::clearToken($this->member_id, $this->request->apiToken());
  135. return true;
  136. }
  137. /**
  138. * 清理token
  139. * @param int $member_id
  140. * @param string|null $token
  141. * @return bool|null
  142. */
  143. public static function clearToken(int $member_id, ?string $token = ''): ?bool
  144. {
  145. TokenAuth::clearToken($member_id, AppTypeDict::API, $token);
  146. return true;
  147. }
  148. /**
  149. * 解析token
  150. * @param string|null $token
  151. * @return array
  152. */
  153. public function parseToken(?string $token){
  154. if(empty($token))
  155. {
  156. //定义专属于授权认证机制的错误响应, 定义专属语言包
  157. throw new AuthException('MUST_LOGIN', 401);
  158. }
  159. try {
  160. $token_info = TokenAuth::parseToken($token, AppTypeDict::API);
  161. } catch ( Throwable $e ) {
  162. // if(env('app_debug', false)){
  163. // throw new AuthException($e->getMessage(), 401);
  164. // }else{
  165. throw new AuthException('LOGIN_EXPIRE', 401);
  166. // }
  167. }
  168. if(!$token_info)
  169. {
  170. throw new AuthException('MUST_LOGIN', 401);
  171. }
  172. //验证有效次数或过期时间
  173. return $token_info;
  174. }
  175. /**
  176. * 手机发送验证码
  177. * @param $mobile
  178. * @param string $type 发送短信的业务场景
  179. * @return array
  180. * @throws Exception
  181. */
  182. public function sendMobileCode($mobile, string $type = ''){
  183. (new CaptchaService())->check();
  184. if(empty($mobile)) throw new AuthException('MOBILE_NEEDED');
  185. //发送
  186. if(!in_array($type, SmsDict::SCENE_TYPE)) throw new AuthException('MEMBER_MOBILE_CAPTCHA_ERROR');
  187. $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);// 生成4位随机数,左侧补0
  188. (new NoticeService())->send('member_verify_code', ['code' => $code, 'mobile' => $mobile]);
  189. //将验证码存入缓存
  190. $key = md5(uniqid("", true));
  191. $cache_tag_name = "mobile_key".$mobile.$type;
  192. $this->clearMobileCode($mobile, $type);
  193. Cache::tag($cache_tag_name)->set($key, [ 'mobile' => $mobile, 'code' => $code, 'type' => $type], 600);
  194. return ['key' => $key];
  195. }
  196. public function getMobileCodeCacheName(){
  197. }
  198. public function clearMobileCode($mobile, $type){
  199. $cache_tag_name = "mobile_key".$mobile.$type;
  200. Cache::tag($cache_tag_name)->clear();
  201. }
  202. /**
  203. * 校验手机验证码
  204. * @param string $mobile
  205. * @return true
  206. */
  207. public function checkMobileCode(string $mobile){
  208. if(empty($mobile)) throw new AuthException('MOBILE_NEEDED');
  209. $mobile_key = request()->param('mobile_key', '');
  210. $mobile_code = request()->param('mobile_code', '');
  211. if(empty($mobile_key) || empty($mobile_code)) throw new AuthException('MOBILE_CAPTCHA_ERROR');
  212. $cache = Cache::get($mobile_key);
  213. if(empty($cache)) throw new AuthException('MOBILE_CAPTCHA_ERROR');
  214. $temp_mobile = $cache['mobile'];
  215. $temp_code = $cache['code'];
  216. $temp_type = $cache['type'];
  217. if($temp_mobile != $mobile || $temp_code != $mobile_code) throw new AuthException('MOBILE_CAPTCHA_ERROR');
  218. $this->clearMobileCode($temp_mobile, $temp_type);
  219. return true;
  220. }
  221. /**
  222. * 绑定openid
  223. * @param $member
  224. * @return true
  225. */
  226. public function bingOpenid($member){
  227. $config = (new MemberConfigService())->getLoginConfig();
  228. $is_auth_register = $config['is_auth_register'];
  229. $open_id = $this->request->param('openid');
  230. if(!empty($open_id)){
  231. Log::write('channel_1'.$this->channel);
  232. if(!empty($this->channel)){
  233. $openid_field = match($this->channel){
  234. 'wechat' => 'wx_openid',
  235. 'weapp' => 'weapp_openid',
  236. default => ''
  237. };
  238. if(!empty($openid_field)){
  239. if(!$member->isEmpty()){
  240. if(empty($member->$openid_field)){
  241. //todo 定义当前第三方授权方没有退出登录功能,故这儿不做openid是否存在账号验证
  242. // $member_service = new MemberService();
  243. // $open_member = $member_service->findMemberInfo([$openid_field => $open_id]);
  244. $member->$openid_field = $open_id;
  245. $member->save();
  246. }else{
  247. if( $member->$openid_field != $open_id){
  248. throw new AuthException('MEMBER_IS_BIND_AUTH');
  249. }
  250. }
  251. }
  252. }
  253. }
  254. }
  255. return true;
  256. }
  257. /**
  258. * 重置密码
  259. * @param string $mobile
  260. * @param string $password
  261. */
  262. public function resetPassword(string $mobile, string $password){
  263. $member_service = new MemberService();
  264. //校验手机验证码
  265. $this->checkMobileCode($mobile);
  266. $member_info = $member_service->findMemberInfo(['mobile' => $mobile]);
  267. if ($member_info->isEmpty()) throw new AuthException('MOBILE_NOT_EXIST_MEMBER');//账号不存在
  268. //todo 需要考虑一下,新的密码和原密码一样能否通过验证
  269. $password_hash = create_password($password);
  270. $data = [
  271. 'password' => $password_hash,
  272. ];
  273. $member_service->editByFind($member_info, $data);
  274. self::clearToken($member_info['member_id'], $this->request->apiToken());
  275. return true;
  276. }
  277. public function loginScanCode(){
  278. }
  279. public function loginByScanCode(){
  280. }
  281. public function checkScanCode(){
  282. }
  283. }