123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511 |
- <?php
- namespace App\Http\Controllers\Admin\Base;
- use App\Http\Controllers\Controller;
- use App\Http\Middleware\SingleLoginLimit;
- use App\Repositories\Enums\Base\AdminTypeEnum;
- use App\Repositories\Enums\ModelStatusEnum;
- use App\Repositories\Enums\ResponseCodeEnum;
- use App\Repositories\Models\Base\Admin;
- use App\Services\Base\AdminService;
- use App\Services\Base\AuthService;
- use App\Support\Traits\LoginLimit;
- use Carbon\Carbon;
- use EasyWeChat\Factory;
- use Illuminate\Http\Request;
- use Illuminate\Support\Arr;
- use Illuminate\Support\Facades\Cache;
- /**
- * 用户登录
- */
- class AuthController extends Controller
- {
- use LoginLimit;
- /**
- * @var AuthService
- */
- private $authService;
- /**
- * AdminService
- * @var
- */
- private $adminService;
- /**
- * AuthController constructor.
- *
- * @param AuthService $authService
- */
- public function __construct(AuthService $authService, AdminService $adminService)
- {
- parent::__construct();
- $this->middleware('checkUserPermission', ['except' => ['accountLogin', 'miniProgramLogin', 'miniProgramMobileLogin', 'testMobile']]);
- $this->authService = $authService;
- $this->adminService = $adminService;
- }
- /**
- * 账号密码登录
- * @must
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
- * @throws \Illuminate\Validation\ValidationException
- */
- public function accountLogin(Request $request)
- {
- $this->validate($request, [
- 'username' => 'required',
- 'password' => 'required|min:6'
- ], [], [
- 'username' => '账号',
- 'password' => '密码',
- ]);
- $credentials = $request->only(['username', 'password']);
- if (is_mobile()) {
- $credentials['type'] = AdminTypeEnum::STUDENT;
- }
- $username = $request->get('username');
- $msg = $this->isCanLogin($request, $username);
- if ($msg) {
- return $this->response->fail($msg);
- }
- $token = $this->adminService->handleAccountLogin($credentials, $request);
- if ($token) {
- $this->clearLoginLogs($request, $username);
- $expires_in = auth()->factory()->getTTL() * 60;
- $this->singleLoginSetToken(login_admin_id(), $token, 'admins');
- $token = 'Bearer ' . $token;
- $is_clear_log = true;
- return $this->response->success(compact('token', 'expires_in', 'is_clear_log'));
- }
- $this->storeLoginLog($request, $username);
- return $this->response->fail('账号或者密码错误!');
- }
- /**
- * 微信小程序绑定登录
- * @must
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
- * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
- * @throws \Illuminate\Validation\ValidationException
- * @throws \Prettus\Validator\Exceptions\ValidatorException
- */
- public function miniProgramLogin(Request $request)
- {
- $this->validate($request, [
- 'code' => 'required|string',
- 'appid' => 'required|string',
- // 'type' => 'required|in:3,4,5',
- 'phone_detail' => 'sometimes'
- ], [], [
- 'code' => 'Code',
- 'appid' => 'AppId',
- 'phone_detail' => '手机信息',
- ]);
- $auth = $this->authService->handleIsMiniProgramLogin($request);
- if (!$auth) {
- return $this->response->success(['token' => false]);
- }
- $token = $this->adminService->handleAuthLogin($auth);
- $this->singleLoginSetToken(login_admin_id(), $token, 'admins');
- $token = 'Bearer ' . $token;
- $expires_in = auth()->factory()->getTTL() * 60;
- return $this->response->success(compact('token', 'expires_in'));
- }
- /*
- * 手机号+小程序登录
- */
- public function miniProgramMobileLogin(Request $request)
- {
- $this->validateData($request, [
- 'code' => 'required|string',
- 'appid' => 'required|string',
- // 'type' => 'required',
- 'iv' => 'required',
- 'encryptedData' => 'required',
- ], [
- 'code' => 'Code',
- 'appid' => 'AppId',
- 'iv' => 'iv',
- 'encryptedData' => 'encryptedData',
- 'type' => '用户类型',
- ]);
- $iv = $request->get('iv');
- $encryptedData = $request->get('encryptedData');
- $type = 0;
- $auth = $this->authService->handleMiniProgramLogin($request);
- $session = Cache::get("cache:service:auth:session_key:api:" . $auth['id']);
- if (!$session) abort(ResponseCodeEnum::SERVICE_OPERATION_ERROR, '请重新登录');
- $miniConfig = wechat_mini_config($type);
- $miniProgram = Factory::miniProgram($miniConfig);
- try {
- $decryptedData = $miniProgram->encryptor->decryptData($session, $iv, $encryptedData);
- } catch (\Exception $exception) {
- exception($exception);
- }
- $mobile = $decryptedData['purePhoneNumber'];
- $token = $this->adminService->handleAuthMobileLogin($auth, $mobile);
- $this->singleLoginSetToken(login_admin_id(), $token, 'admins');
- $token = 'Bearer ' . $token;
- $expires_in = auth()->factory()->getTTL() * 60;
- return $this->response->success(compact('token', 'expires_in'));
- }
- /**
- * 绑定微信号
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
- * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
- * @throws \Illuminate\Validation\ValidationException
- * @throws \Prettus\Validator\Exceptions\ValidatorException
- */
- public function bindWechat(Request $request)
- {
- $this->validate($request, [
- 'code' => 'required|string',
- 'appid' => 'required|string',
- 'type' => 'required|in:3,4,5',
- 'phone_detail' => 'sometimes'
- ], [], [
- 'code' => 'Code',
- 'appid' => 'AppId',
- 'phone_detail' => '手机信息',
- ]);
- $auth = $this->authService->handleMiniProgramLogin($request);
- $this->adminService->handleBindWechat($auth);
- return $this->response->ok('绑定成功');
- }
- /**
- * 绑定微信号
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
- * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
- * @throws \Illuminate\Validation\ValidationException
- * @throws \Prettus\Validator\Exceptions\ValidatorException
- */
- public function unbindWechat()
- {
- $this->adminService->handleUnbindWechat();
- return $this->response->ok('绑定成功');
- }
- /**
- * 退出登录
- * @must
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
- */
- public function logout()
- {
- auth('admins')->logout();
- return $this->response->ok('操作成功');
- }
- /**
- * 登录用户信息
- * @must
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
- */
- public function me()
- {
- return $this->response->success($this->adminService->handleMe());
- }
- /**
- * 刷新token
- * @must
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
- */
- public function refreshToken()
- {
- $token = $this->authService->handleRefreshToken();
- $this->singleLoginSetToken(login_admin_id(), $token, 'admins');
- $token = 'Bearer ' . $token;
- $expires_in = auth()->factory()->getTTL() * 60;
- return $this->response->success(compact('token', 'expires_in'));
- }
- /**
- * 锁屏验证密码
- * @must
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
- * @throws \Illuminate\Validation\ValidationException
- */
- public function validatePassword(Request $request)
- {
- $this->validate($request, [
- 'id' => 'required',
- 'password' => 'required'
- ]);
- $username = $request->get('id');
- $msg = $this->isCanLogin($request, $username);
- if ($msg) {
- return $this->response->fail($msg);
- }
- $status = $this->adminService->handleConfirmPassword($request);
- if ($status) {
- $this->clearLoginLogs($request, $username);
- } else {
- $this->storeLoginLog($request, $username);
- }
- return $this->response->success(compact('status'));
- }
- /**
- * 微信小程序绑定用户手机号
- * @must
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\Resource|void
- * Author: Mead
- */
- public function miniBindMobile(Request $request)
- {
- $this->validate($request, [
- 'iv' => 'required',
- 'encryptedData' => 'required',
- ]);
- //微信解析手机号
- $admin = login_admin();
- $iv = $request->get('iv');
- $encryptedData = $request->get('encryptedData');
- $type = $request->get('type');
- $session = Cache::get("cache:service:auth:session_key:admins:" . $admin['wechat_auth_id']);
- if (!$session) abort(ResponseCodeEnum::SERVICE_OPERATION_ERROR, '请重新登录');
- $miniConfig = wechat_mini_config($type);
- $miniProgram = Factory::miniProgram($miniConfig);
- try {
- $decryptedData = $miniProgram->encryptor->decryptData($session, $iv, $encryptedData);
- } catch (\Exception $exception) {
- exception($exception);
- }
- $mobile = $decryptedData['purePhoneNumber'];
- $this->adminService->handleBindMobile($admin['id'], $mobile);
- return $this->response->ok('绑定成功');
- }
- /**
- * 修改密码
- * @must
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
- * @throws \Illuminate\Validation\ValidationException
- * @throws \Prettus\Validator\Exceptions\ValidatorException
- */
- public function updatePassword(Request $request)
- {
- $data = $this->validateData($request, [
- 'password' => 'required|confirmed|min:6'
- ], [
- 'password' => '密码',
- ]);
- $password = $data['password'];
- if (!check_password($password)) {
- return $this->response->fail('密码太简单', ResponseCodeEnum::SERVICE_OPERATION_ERROR);
- }
- $this->adminService->handleMeResetPassword($password);
- return $this->response->ok('修改成功');
- }
- /**
- * 更新个人信息
- * @must
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
- */
- public function updateInfo(Request $request)
- {
- $admin = login_admin();
- $fields = $this->validateData($request, [
- 'fields' => 'required|array',
- ], [
- 'fields' => '字段表',
- ])['fields'];
- $da = [
- 'name' => [
- 'rule' => 'required|string',
- 'name' => '姓名',
- 'key' => 'name',
- ],
- 'sex' => [
- 'rule' => 'required|in:1,2',
- 'name' => '性别',
- 'key' => 'sex',
- ],
- 'email' => [
- 'rule' => 'required|mail',
- 'name' => '邮箱',
- 'key' => 'email',
- ],
- 'department_id' => [
- 'rule' => 'required',
- 'name' => '部门 id',
- 'key' => 'department_id',
- ],
- 'user_no' => [
- 'rule' => 'required',
- 'name' => '学号',
- 'key' => 'user_no',
- ],
- 'grade' => [
- 'rule' => 'required',
- 'name' => '年级',
- 'key' => 'grade',
- ],
- 'class_name' => [
- 'rule' => 'required',
- 'name' => '班级',
- 'key' => 'class_name',
- ],
- 'type' => [
- 'rule' => 'required',
- 'name' => '类型',
- 'key' => 'type',
- ],
- 'extra_fields' => [
- 'rule' => 'required',
- 'name' => '签章',
- 'key' => 'extra_fields',
- ]
- ];
- $rules = Arr::only($da, $fields);
- $data = $this->validateData($request, Arr::pluck($rules, 'rule', 'key'), Arr::pluck($rules, 'name', 'key'));
- // $data['user_no'] = strtoupper($data['user_no']);
- //
- // if (User::query()->where('user_no', $data['user_no'])->where('id', '<>', $admin['id'])->exists()) {
- // return $this->response->fail('该学号已经实名,请勿重复操作');
- // }
- $this->adminService->handleMeUpdate($data);
- return $this->response->ok('更新成功');
- }
- /**
- * 更新个人信息[微信]
- * @must
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
- */
- public function miniUpdateInfo(Request $request)
- {
- $admin = login_admin();
- return $this->response->ok('更新成功');
- }
- /**
- * 发送验证码
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
- * @throws \Illuminate\Validation\ValidationException
- */
- public function sendValidateCode(Request $request)
- {
- $this->validateData($request, [
- 'mobile' => 'required|mobile'
- ], ['mobile' => '手机号']);
- $mobile = $request->get('mobile');
- $day = date('Y-m-d');
- $nums = Cache::get("controller:Admin:AuthController:sendLoginValidateCode:{$mobile}:{$day}", 0);
- if ($nums > 3) {
- return $this->response->fail('你今天请求的次数太多了,请明天再试。');
- }
- Cache::increment("controller:Admin:AuthController:sendLoginValidateCode:{$mobile}:{$day}", 1);
- $code = rand(100000, 999999);
- try {
- app('easy_sms')->send($mobile, [
- 'template' => config('sms.template.verification_code'),
- 'data' => [
- 'number' => (string)$code
- ]
- ]);
- } catch (\Exception $exception) {
- exception($exception->getException(config('sms.default.gateways')[0]));
- }
- Cache::put('controller:admin:sendValidateCode:mobile:' . $mobile, $code, Carbon::now()->addMinutes(5));
- return $this->response->ok('发送成功');
- }
- /**
- * 换绑手机号
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
- * @throws \Illuminate\Validation\ValidationException
- */
- public function updateMobile(Request $request)
- {
- $this->validateData($request, [
- 'mobile' => 'required|mobile',
- 'code' => 'required|size:6',
- ], ['mobile' => '手机号', 'code' => '验证码']);
- $mobile = $request->get('mobile');
- $code = $request->get('code');
- $yun_code = Cache::get('controller:sendLoginValidateCode:mobile:' . $mobile, false);
- if ($yun_code !== $code) abort(ResponseCodeEnum::SERVICE_OPERATION_ERROR, '验证码不对');
- $this->adminService->handleBindMobile(login_admin_id(), $mobile);
- return $this->response->ok('换绑成功');
- }
- public function testMobile(Request $request)
- {
- $this->validate($request, [
- 'mobile' => 'required|mobile',
- ], [], [
- 'mobile' => '手机号',
- ]);
- $mobile = $request->get('mobile');
- // $admin = User::query()->where('mobile', $mobile)->first();
- $admin = Admin::query()->firstOrCreate(['mobile' => $mobile], ['status' => ModelStatusEnum::OK, 'username' => $mobile, 'name' => $mobile]);
- if (!$admin) abort(ResponseCodeEnum::SERVICE_OPERATION_ERROR, '找不该用户');
- $token = auth('admins')->login($admin);
- //单机登录限制
- $admin_id = $admin['id'];
- SingleLoginLimit::setToken('admins', $admin_id, $token);
- $expires_in = auth()->factory()->getTTL() * 60;
- $this->singleLoginSetToken(login_admin_id(), $token, 'admins');
- $token = 'Bearer ' . $token;
- return $this->response->success(compact('token', 'expires_in'));
- }
- }
|