123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380 |
- <?php
- /*
- * This file is part of the Jiannei/lumen-api-starter.
- *
- * (c) Jiannei <longjian.huang@foxmail.com>
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
- namespace App\Http\Controllers\Api\Base;
- use App\Http\Controllers\Controller;
- use App\Repositories\Enums\ModelStatusEnum;
- use App\Repositories\Enums\Navigation\TypeEnum;
- use App\Repositories\Enums\ResponseCodeEnum;
- use App\Repositories\Models\Base\Admin;
- use App\Repositories\Models\CMS\Setting;
- use App\Repositories\Models\Navigation\Category;
- use App\Repositories\Models\User\User;
- use App\Repositories\Transformers\User\UserTransformer;
- use Carbon\Carbon;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\Hash;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Str;
- use Jiannei\Response\Laravel\Support\Facades\Response;
- use Spatie\Permission\Models\Role;
- class AuthController extends Controller
- {
- /**
- * Create a new controller instance.
- */
- public function __construct()
- {
- // $this->middleware('throttle:10,1', ['only' => ['login', 'me']]);
- }
- /**
- * 账号密码登录
- * Author: Mead
- */
- public function login(Request $request)
- {
- $this->validate($request, [
- 'username' => 'required',
- 'password' => 'required|min:6'
- ]);
- $credentials = request(['username', 'password']);
- $credentials['status'] = ModelStatusEnum::OK;
- if (!$token = auth()->guard('api')->attempt($credentials)) {
- return Response::fail(T('The account or password is incorrect.'), ResponseCodeEnum::SERVICE_LOGIN_ERROR);
- }
- $user = auth('api')->user();
- //判断个人是否有分类
- if (!Category::query()->where('user_id', $user->id)->status()->where('pid', 0)->exists()) {
- Category::query()->create([
- 'name' => '个人网站',
- 'pid' => 0,
- 'type' => TypeEnum::PERSON,
- 'slug' => Str::random(6),
- 'user_id' => $user->id,
- 'tier' => 0,
- 'logo' => 'fa-user-circle'
- ]);
- }
- $user = $user->only(['id', 'username', 'name', 'sex', 'role_id', 'class', 'mobile', 'organization_id']);
- return Response::success(compact('token', 'user'));
- }
- /**
- * 退出
- * @return mixed
- * Author: Mead
- */
- public function logout()
- {
- auth('api')->logout();
- return Response::noContent();
- }
- /**
- * 注册
- * Author: Mead
- */
- public function store(Request $request)
- {
- $this->validate($request, [
- 'name' => 'required',
- // 'turename' => 'required',
- 'mobile' => 'required',
- 'username' => 'required|min:8|unique:base_users,username',
- 'password' => 'required|min:6'
- ]);
- $data = $request->only(['turename', 'mobile', 'username', 'password']);
- $data['password'] = Hash::make($data['password']);
- User::query()->create($data);
- return Response::success(null);
- }
- /**
- * 用户
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
- * Author: Mead
- */
- public function me()
- {
- $me = (new UserTransformer())->transform(User::query()->find(login_user_id()));
- return Response::success($me);
- // return Response::success(1);
- }
- /**
- * 修改个人信息
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\Resource
- * @throws \Illuminate\Validation\ValidationException
- * Author: Mead
- */
- public function update(Request $request)
- {
- $this->validate($request, [
- 'name' => 'required',
- 'headimg' => 'sometimes',
- 'sex' => 'nullable',
- 'email' => 'nullable|email',
- 'class' => 'nullable',
- 'mobile' => 'nullable|mobile',
- 'intro' => 'nullable',
- 'personal_signature' => 'nullable',
- 'userrate' => 'nullable',
- ]);
- try {
- $data = $request->only(['turename', 'headimg', 'email', 'mobile', 'class', 'intro', 'personal_signature', 'userrate', 'name', 'sex']);
- $re = User::query()->where('id', login_user_id())->update($data);
- if ($re) {
- return Response::success(null);
- }
- return $this->errorFail();
- } catch (\Exception $e) {
- $this->errorStore($e);
- }
- }
- /**
- * 修改密码
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\Resource
- * @throws \Illuminate\Validation\ValidationException
- * Author: Mead
- */
- public function changePassword(Request $request)
- {
- $this->validate($request, [
- 'password' => 'required|min:6|confirmed',
- ]);
- $password = $request->get('password');
- $data['password'] = Hash::make($password);
- $re = User::query()->where('id', login_user_id())->update($data);
- if ($re) {
- return Response::success(null);
- }
- return $this->errorFail();
- }
- /**
- * 手机验证码
- * @param Request $request
- * Author: Mead
- */
- public function verificationCode(Request $request)
- {
- $this->validate($request, [
- 'mobile' => 'required|mobile',
- ]);
- $mobile = $request->get('mobile');
- $code = rand(1000, 9999);
- // try {
- // app('easy_sms')->send($mobile, [
- // 'template' => config('sms.template.verification_code'),
- // 'data' => [
- // 'code' => $code
- // ]
- // ]);
- //
- // } catch (\Exception $exception) {
- // Log::error($exception);
- // return Response::fail('发送失败');
- // }
- Cache::put("verification_code_{$mobile}", $code, Carbon::now()->addMinutes(5));
- return Response::success($code);
- }
- /**
- * 手机号登录
- * @param Request $request
- * Author: Mead
- */
- public function mobileLogin(Request $request)
- {
- $this->validate($request, [
- 'mobile' => 'required|mobile',
- 'code' => 'required|size:4',
- ]);
- $mobile = $request->get('mobile');
- $code = $request->get('code');
- // $cache_code = Cache::get("verification_code_{$mobile}", false);
- //
- // if ((int)$cache_code !== (int)$code) {
- // return Response::fail('验证码错误');
- // }
- $user = User::query()->where('mobile', $mobile)->with('organization')->select(['id', 'name', 'mobile', 'headimg', 'sex', 'organization_id', 'status'])->where('status', ModelStatusEnum::OK)->orderByDesc('id')->first();
- if (!$user) {
- return Response::fail('找不到该用户');
- // $user = User::query()->create([
- // 'name' => '圆圈导航-' . rand(99999, 10000),
- // 'mobile' => $mobile,
- // ]);
- }
- //判断个人是否有分类
- if (!Category::query()->where('user_id', $user->id)->status()->where('pid', 0)->exists()) {
- Category::query()->create([
- 'name' => '个人网站',
- 'pid' => 0,
- 'type' => TypeEnum::PERSON,
- 'slug' => Str::random(6),
- 'user_id' => $user->id,
- 'tier' => 0,
- 'logo' => 'fa-user-circle'
- ]);
- }
- $token = auth('api')->login($user);
- return Response::success(compact('token', 'user'));
- }
- /**
- * 小程序登录
- * Author: Mead
- */
- public function weappLogin(Request $request)
- {
- $this->validate($request, [
- 'appid' => 'required',
- 'code' => 'required',
- ]);
- $code = $request->code;
- $appid = $request->appid;
- if ($appid !== config('wechat.mini_program.default.app_id')) {
- return $this->error('app_id is error');
- }
- $response = [];
- try {
- // $miniProgram = Factory::miniProgram(config('wechat'));
- $miniProgram = app('wechat.mini_program');
- $data = $miniProgram->auth->session($code);
- } catch (\Exception $exception) {
- return $this->error('code 不正确,请刷新重试');
- }
- if (isset($data['errcode'])) {
- return $this->error('code 不正确,请刷新重试');
- }
- $user = User::query()->where('credential', $data['openid'])->first();
- //response参数
- $response['session_key'] = $data['session_key'];
- $is_new_user = false;
- if (!$user) {
- //注册用户
- $userInfo['name'] = config('site.userName', '用户') . '-' . rand(10000, 99999);
- $userInfo['credential'] = $data['openid'];
- $user = User::query()->create($userInfo);
- $is_new_user = true;
- }
- $token = auth('api')->login($user);
- $response['token'] = 'Bearer ' . $token;
- $response['exp'] = Carbon::now()->getTimestamp();
- $response['user'] = $user;
- $response['is_new_user'] = $is_new_user;
- return Response::success($response);
- }
- /**
- * 更新用户基本信息
- * User: Mead
- */
- public function weappUserInfoSync(Request $request)
- {
- $this->validate($request, [
- 'nickName' => 'required',
- 'gender' => 'required',
- ]);
- try {
- $user = auth('api')->user();
- User::query()->where('id', $user->id)->update([
- 'name' => $request->get('nickName', $user->nickname),
- 'sex' => $request->get('gender', 0),
- // 'country' => $request->get('country', 'China'),
- // 'province' => $request->get('province', 'Henan'),
- // 'city' => $request->get('city', 'Zhengzhou'),
- 'headimg' => $request->get('avatarUrl', config('filesystems.disks.qiniu.url') . '/logo.png') ?? config('filesystems.disks.qiniu.url') . "/logo.png",
- // 'language' => $request->get('language', 'zh_CN'),
- 'is_sync_info' => 1
- ]);
- $me = (new UserTransformer())->transform(User::query()->where('id', $user->id)->first());
- return Response::success($me);
- } catch (\Exception $exception) {
- return $this->error($exception);
- }
- }
- /**
- * 微信小程序绑定用户手机号
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Resources\Json\Resource|void
- * Author: Mead
- */
- public function weappBindMobile(Request $request)
- {
- $this->validate($request, [
- 'session_key' => 'required',
- 'iv' => 'required',
- 'encryptedData' => 'required',
- ]);
- try {
- //微信解析手机号
- $session = $request->get('session_key');
- $iv = $request->get('iv');
- $encryptedData = $request->get('encryptedData');
- if (!$iv) {
- return $this->error('授权失败');
- }
- $miniProgram = app('wechat.mini_program');
- $decryptedData = $miniProgram->encryptor->decryptData($session, $iv, $encryptedData);
- $mobile = $decryptedData['purePhoneNumber'];
- User::query()->where('id', login_user_id())->update([
- 'mobile' => $mobile,
- 'is_bind_mobile' => 1
- ]);
- return Response::success(null);
- } catch (\Exception $exception) {
- return $this->exception($exception);
- }
- }
- }
|