123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469 |
- <?php
- namespace app\api\controller;
- use app\admin\model\sms\SmsRecord;
- use app\http\validates\user\RegisterValidates;
- use app\models\user\User;
- use app\models\user\UserToken;
- use app\models\user\WechatUser;
- use app\Request;
- use crmeb\jobs\TestJob;
- use crmeb\repositories\ShortLetterRepositories;
- use crmeb\services\CacheService;
- use crmeb\services\UtilService;
- use think\db\exception\DataNotFoundException;
- use think\db\exception\DbException;
- use think\db\exception\ModelNotFoundException;
- use think\facade\Cache;
- use think\exception\ValidateException;
- use think\facade\Config;
- use think\facade\Queue;
- use think\facade\Session;
- /**微信小程序授权类
- * Class AuthController
- * @package app\api\controller
- */
- class AuthController
- {
- /**
- * H5账号登陆
- * @param Request $request
- * @return mixed
- * @throws DataNotFoundException
- * @throws ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function login(Request $request)
- {
- $user = User::where('account', $request->param('account'))->where('site_id', $request->site_id())->find();
- if ($user) {
- if ($user->pwd !== md5($request->param('password')))
- return app('json')->fail('账号或密码错误');
- if ($user->pwd === md5(123456))
- return app('json')->fail('请修改您的初始密码,再尝试登陆!');
- } else {
- return app('json')->fail('账号或密码错误');
- }
- if (!$user['status'])
- return app('json')->fail('已被禁止,请联系管理员');
- // 设置推广关系
- User::setSpread(intval($request->param('spread')), $user->uid);
- $token = UserToken::createToken($user, 'user');
- if ($token) {
- event('UserLogin', [$user, $token]);
- return app('json')->success('登录成功', ['token' => $token->token, 'expires_time' => $token->expires_time]);
- } else
- return app('json')->fail('登录失败');
- }
- /**
- * 退出登录
- * @param Request $request
- */
- public function logout(Request $request)
- {
- $request->tokenData()->delete();
- return app('json')->success('成功');
- }
- public function verifyCode()
- {
- $unique = password_hash(uniqid(true), PASSWORD_BCRYPT);
- Cache::set('sms.key.' . $unique, 0, 300);
- return app('json')->success(['key' => $unique]);
- }
- public function captcha(Request $request)
- {
- ob_clean();
- $rep = captcha();
- $key = app('session')->get('captcha.key');
- $uni = $request->get('key');
- if ($uni)
- Cache::set('sms.key.cap.' . $uni, $key, 300);
- return $rep;
- }
- /**
- * 验证验证码是否正确
- *
- * @param $uni
- * @param string $code
- * @return bool
- * @throws \Psr\SimpleCache\InvalidArgumentException
- */
- protected function checkCaptcha($uni, string $code): bool
- {
- $cacheName = 'sms.key.cap.' . $uni;
- if (!Cache::has($cacheName)) {
- return false;
- }
- $key = Cache::get($cacheName);
- $code = mb_strtolower($code, 'UTF-8');
- $res = password_verify($code, $key);
- if ($res) {
- Cache::delete($cacheName);
- }
- return $res;
- }
- /**
- * 验证码发送
- * @param Request $request
- * @return mixed
- */
- public function verify(Request $request)
- {
- list($phone, $type
- // , $key, $code
- ) = UtilService::postMore([['phone', 0], ['type', ''],
- // ['key', ''], ['code', '']
- ], $request, true);
- // $keyName = 'sms.key.' . $key;
- $nowKey = 'sms.' . date('YmdHi');
- // if (!Cache::has($keyName))
- // return app('json')->make(401, '发送验证码失败');
- //
- // if (($num = Cache::get($keyName)) > 2) {
- // if (!$code)
- // return app('json')->make(402, '请输入验证码');
- //
- // if (!$this->checkCaptcha($key, $code))
- // return app('json')->fail('验证码输入有误');
- // }
- $total = 1;
- if ($has = Cache::has($nowKey)) {
- $total = Cache::get($nowKey);
- if ($total > Config::get('sms.maxMinuteCount', 20))
- return app('json')->success('已发送');
- }
- if ($type != 'register' && $type != 'login' && $type != 'reset' && $type != 'BDING_CODE') {
- $phone = $request->user()['account'];
- }
- try {
- validate(RegisterValidates::class)->scene('code')->check([(mobile_check($phone) ? 'phone' : 'email') => $phone]);
- } catch (ValidateException $e) {
- return app('json')->fail($e->getError());
- }
- if (User::checkPhone($phone, $request->site_id()) && ($type == 'register')) return app('json')->fail('帐号已注册');
- if (!User::checkPhone($phone, $request->site_id()) && ($type == 'login' || $type == 'reset')) return app('json')->fail('账号不存在!');
- if (mobile_check($phone))
- $default = Config::get('sms.default', 'aliyun');
- else
- $default = Config::get('sms.default_email', 'email');
- $defaultMaxPhoneCount = Config::get('sms.maxPhoneCount', 10);
- $defaultMaxIpCount = Config::get('sms.maxIpCount', 50);
- $maxPhoneCount = Config::get('sms.stores.' . $default . '.maxPhoneCount', $defaultMaxPhoneCount);
- $maxIpCount = Config::get('sms.stores.' . $default . '.maxIpCount', $defaultMaxIpCount);
- if (SmsRecord::where('phone', $phone)->where('add_ip', $request->ip())->whereDay('add_time')->count() >= $maxPhoneCount) {
- return app('json')->fail('您今日发送验证码次数已经达到上限');
- }
- if (SmsRecord::where('add_ip', $request->ip())->whereDay('add_time')->count() >= $maxIpCount) {
- return app('json')->fail('此IP今日发送次数已经达到上限');
- }
- $time = mobile_check($phone) ? 300 : 300;
- if (CacheService::get('code_' . $phone))
- return app('json')->fail($time . '秒内有效');
- $code = rand(100000, 999999);
- $data['code'] = $code;
- if (mobile_check($phone)) {
- //发短信
- $temp = function ($item) {
- switch ($item) {
- case "register":
- return 'REGISTER';
- case "login":
- return 'LOGIN';
- case "reset":
- return 'RESET';
- case "reset_2":
- return 'RESET_2';
- case "trade":
- return 'TRADE';
- default:
- return 'DEFAULT';
- }
- };
- $res = ShortLetterRepositories::NewSmsSend($phone, $data, $temp($type), $request->site_id());
- } else {
- //发邮件
- $res = ShortLetterRepositories::EmailSend($phone, $data, $request->site_id());
- }
- //发短信
- if ($res !== true) {
- if (strpos($res, 'User not found') !== false)
- $res = '邮箱不存在';
- return app('json')->fail('验证码发送失败:' . $res);
- }
- CacheService::set('code_' . $phone, $code, $time);
- // Cache::set($keyName, $num + 1, 300);
- Cache::set($nowKey, $total, 61);
- return app('json')->success('发送成功');
- }
- /**
- * H5注册新用户
- * @param Request $request
- * @return mixed
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function register(Request $request)
- {
- list($account, $captcha, $password, $trade_password, $spread) = UtilService::postMore([['account', ''], ['captcha', ''], ['password', ''], ['trade_password', ''], ['spread', 0]], $request, true);
- try {
- validate(RegisterValidates::class)->scene('register')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password, 'trade_password' => $trade_password]);
- } catch (ValidateException $e) {
- return app('json')->fail($e->getError());
- }
- if (!$spread && User::count() > 0) return app('json')->fail('请输入邀请码');
- if ($spread) {
- $spread = User::where('uid|account', $spread)->where('site_id', $request->site_id())->value('uid');
- if (!$spread) return app('json')->fail('邀请码不存在');
- }
- $verifyCode = CacheService::get('code_' . $account);
- if (!$verifyCode)
- return app('json')->fail('请先获取验证码');
- $verifyCode = substr($verifyCode, 0, 6);
- if ($verifyCode != $captcha)
- return app('json')->fail('验证码错误');
- if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
- return app('json')->fail('密码必须是在6到16位之间');
- if (strlen(trim($trade_password)) < 6 || strlen(trim($trade_password)) > 6 || !is_numeric($trade_password))
- return app('json')->fail('交易密码为6位数字');
- if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
- // if (mobile_check($spread)) $spread = User::where('account', $spread)->where('site_id', $request->site_id())->value('uid');
- $registerStatus = User::register($account, $password, $trade_password, $spread, $request->site_id());
- if ($registerStatus) return app('json')->success('注册成功');
- return app('json')->fail(User::getErrorInfo('注册失败'));
- }
- /**
- * 密码修改
- * @param Request $request
- * @return mixed
- */
- public function reset(Request $request)
- {
- list($account, $captcha, $password, $password2, $type) = UtilService::postMore([['account', ''], ['captcha', ''], ['password', ''], ['password2', ''], ['type', 1]], $request, true);
- try {
- validate(RegisterValidates::class)->scene('reset')->check(['account' => $account, 'captcha' => $captcha, 'password' => $password, 'password2' => $password2]);
- } catch (ValidateException $e) {
- return app('json')->fail($e->getError());
- }
- $verifyCode = CacheService::get('code_' . $account);
- if (!$verifyCode)
- return app('json')->fail('请先获取验证码');
- $verifyCode = substr($verifyCode, 0, 6);
- if ($verifyCode != $captcha)
- return app('json')->fail('验证码错误');
- if ($password != $password2)
- return app('json')->fail('两次输入的密码不一致');
- if (strlen(trim($password)) < 6 || strlen(trim($password)) > 16)
- return app('json')->fail('密码必须是在6到16位之间');
- // if ($password == '123456') return app('json')->fail('密码太过简单,请输入较为复杂的密码');
- $resetStatus = User::reset($account, $password, $request->site_id(), $type);
- if ($resetStatus) return app('json')->success('修改成功');
- return app('json')->fail(User::getErrorInfo('修改失败'));
- }
- /**
- * 手机号登录
- * @param Request $request
- * @return mixed
- * @throws DataNotFoundException
- * @throws ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function mobile(Request $request)
- {
- list($phone, $captcha, $spread) = UtilService::postMore([['phone', ''], ['captcha', ''], ['spread', 0]], $request, true);
- //验证手机号
- try {
- validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
- } catch (ValidateException $e) {
- return app('json')->fail($e->getError());
- }
- //验证验证码
- $verifyCode = CacheService::get('code_' . $phone);
- if (!$verifyCode)
- return app('json')->fail('请先获取验证码');
- $verifyCode = substr($verifyCode, 0, 6);
- if ($verifyCode != $captcha)
- return app('json')->fail('验证码错误');
- //数据库查询
- $user = User::where('account', $phone)->where('site_id', $request->site_id())->find();
- if (!$user)
- return app('json')->fail('用户不存在');
- if (!$user->status)
- return app('json')->fail('已被禁止,请联系管理员');
- // 设置推广关系
- User::setSpread($spread, $user->uid);
- $token = UserToken::createToken($user, 'user');
- if ($token) {
- event('UserLogin', [$user, $token]);
- return app('json')->success('登录成功', ['token' => $token->token, 'expires_time' => $token->expires_time]);
- } else
- return app('json')->fail('登录失败');
- }
- /**
- * H5切换登陆
- * @param Request $request
- * @return mixed
- * @throws DataNotFoundException
- * @throws ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function switch_h5(Request $request)
- {
- $from = $request->post('from', 'wechat');
- $user = $request->user();
- if ($from === 'h5') {
- $user = User::where('phone', $user['phone'])->where('site_id', $request->site_id())->where('user_type', '<>', 'h5')->find();
- $user->login_type = 'wechat';
- $user->save();
- } else {
- //数据库查询
- $user = User::where('account|phone', $user['phone'])->where('site_id', $request->site_id())->where('user_type', 'h5')->find();
- if (!$user)
- return app('json')->fail('H5用户不存在,无法切换');
- if (!$user->status) return app('json')->fail('已被禁止,请联系管理员');
- $wechatUserInfo = WechatUser::where('uid', $request->uid())->find();//当前登陆用户信息
- $wechatH5UserInfo = WechatUser::where('uid', $user->uid)->find();//H5登陆切换用户信息
- if ($wechatH5UserInfo->unionid && $wechatUserInfo->unionid != $wechatH5UserInfo->unionid)
- return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
- if ($wechatH5UserInfo->openid && $wechatUserInfo->openid != $wechatH5UserInfo->openid)
- return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
- if ($wechatH5UserInfo->routine_openid && $wechatUserInfo->routine_openid != $wechatH5UserInfo->routine_openid)
- return app('json')->fail('您的账号已绑定特定用户无法切换到此用户上');
- switch ($from) {
- case 'wechat':
- if (!$wechatH5UserInfo->openid)
- $wechatH5UserInfo->openid = $wechatUserInfo->openid;
- if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
- $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
- break;
- case 'routine':
- if (!$wechatH5UserInfo->routine_openid)
- $wechatH5UserInfo->routine_openid = $wechatUserInfo->routine_openid;
- if (!$wechatH5UserInfo->unionid && $wechatUserInfo->unionid)
- $wechatH5UserInfo->unionid = $wechatUserInfo->unionid;
- break;
- }
- $wechatH5UserInfo->save();
- User::where('uid', $request->uid())->update(['login_type' => 'h5']);
- }
- $token = UserToken::createToken($user, 'user');
- if ($token) {
- event('UserLogin', [$user, $token]);
- return app('json')->success('登录成功', ['userInfo' => $user, 'token' => $token->token, 'expires_time' => $token->expires_time, 'time' => strtotime($token->expires_time)]);
- } else
- return app('json')->fail('登录失败');
- }
- /**
- * 绑定手机号
- * @param Request $request
- * @return mixed
- * @throws DataNotFoundException
- * @throws ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function binding_phone(Request $request)
- {
- list($phone, $captcha, $step) = UtilService::postMore([
- ['phone', ''],
- ['captcha', ''],
- ['step', 0]
- ], $request, true);
- //验证手机号
- try {
- validate(RegisterValidates::class)->scene('code')->check(['account' => $phone]);
- } catch (ValidateException $e) {
- return app('json')->fail($e->getError());
- }
- //验证验证码
- $verifyCode = CacheService::get('code_' . $phone);
- if (!$verifyCode)
- return app('json')->fail('请先获取验证码');
- $verifyCode = substr($verifyCode, 0, 6);
- if ($verifyCode != $captcha)
- return app('json')->fail('验证码错误');
- $userInfo = User::where('account', $phone)->find();
- if ($userInfo) {
- //直接绑定到老帐号
- // var_dump($request->uid());
- $wechat = WechatUser::where('uid', $userInfo['uid'])->find();
- if ($wechat['openid'] || $wechat['unionid'] || $wechat['routine_openid']) {
- if (!$userInfo) return app('json')->fail('该手机或邮箱已绑定微信账号');
- } else {
- $now = WechatUser::where('uid', $request->uid())->find()->toArray();
- unset($now['site_id']);
- unset($now['uid']);
- unset($now['add_time']);
- unset($now['stair']);
- unset($now['second']);
- unset($now['order_stair']);
- unset($now['order_second']);
- unset($now['now_money']);
- unset($now['user_type']);
- WechatUser::where('uid', $userInfo['uid'])->update($now);
- WechatUser::where('uid', $request->uid())->delete();
- User::where('uid', $request->uid())->delete();
- $request->tokenData()->delete();
- return app('json')->success('绑定成功,请重新登录');
- }
- } else {
- //账号的H5信息设置上
- $userInfo = User::where('uid', $request->uid())->find();
- $userPhone = $userInfo->account;
- if (!$userInfo) return app('json')->fail('用户不存在');
- if ($userInfo->account == $userInfo->email || $userInfo->account == $userInfo->phone) return app('json')->fail('您的账号已经绑定过手机号码或邮箱!');
- $userInfo->account = $phone;
- if (mobile_check($phone))
- $userInfo->phone = $phone;
- else
- $userInfo->email = $phone;
- if ($userInfo->save() || $userPhone == $phone)
- return app('json')->success('绑定成功');
- else
- return app('json')->fail('绑定失败');
- }
- }
- }
|