123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389 |
- <?php
- namespace App\Http\Controllers\Api\V1;
- use App\Helper\AttachmentHelper;
- use App\Helper\JpushHelper;
- use App\Helper\SmsHelper;
- use Illuminate\Foundation\Auth\AuthenticatesUsers;
- use App\Models\UserInfoModel;
- use Illuminate\Http\Request;
- use App\Services\Base\ErrorCode;
- use Validator, Auth, Cache;
- class AuthController extends Controller
- {
- use SmsHelper,AuthenticatesUsers,AttachmentHelper,JpushHelper;
- private $expireTime = 1;
- private $keySmsCode = 'auth:sms:';
- private $keySmsCodeExist = 'auth:sms:exist';
- private $expireTimeExist = 24*60;
- public function test(){
- // return $this->error(ErrorCode::SAVE_USER_FAILED);
- return $this->api(['test' => 'test']);
- }
- /**
- * @api {post} /api/auth/login 登陆(login)
- * @apiDescription 登陆(login)
- * @apiGroup Auth
- * @apiPermission none
- * @apiVersion 0.1.0
- * @apiParam {string} phone 手机号码
- * @apiParam {string} [jpush]
- * @apiParam {string} wechat 微信openid
- * @apiParam {String} verify_code 手机验证码
- * @apiSuccessExample {json} Success-Response:
- * HTTP/1.1 200 OK
- * {
- * "state": true,
- * "code": 0,
- * "message": "",
- * "data": {
- * "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjdjYWUyYzFmYTUwMTIyZDI0ZTRiYTZhZGZhNmQxY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avatar": null,
- * "last_ip": null,
- * "created_at": "2016-09-30 00:45:13",
- * "updated_at": "2016-09-29 16:43:36"
- * }
- * }
- * }
- * @apiErrorExample {json} Error-Response:
- * HTTP/1.1 400 Bad Request
- * {
- * "state": false,
- * "code": 1000,
- * "message": "传入参数不正确",
- * "data": null or []
- * }
- * 可能出现的错误代码:
- * 1000 CLIENT_WRONG_PARAMS 传入参数不正确
- * 1103 VERIFY_CODE_TOO_MUCH 验证码大于5次
- * 1610 SERVICE_CODE_FAILED 验证码错误
- *
- */
- public function login(Request $request) {
- $validator = Validator::make($request->all(),
- [
- // 'wechat' => 'required',
- 'phone' => 'required|regex:/^1[34578]\d{9}$/',
- 'verify_code' => 'required',
- ],
- [
- // 'wechat.required' => '请先绑定微信',
- 'phone.required' => '请输入手机号码',
- 'phone.regex' => '手机号码格式不正确',
- 'verify_code.required' => '短信验证码必填',
- ]
- );
- if ($validator->fails())
- return $this->validatorError($validator->messages()->all(),ErrorCode::CLIENT_WRONG_PARAMS);
- $phone = $request->phone;
- $wechat = $request->wechat;
- // $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxc5181c0d406023e6&secret=82d15bf4c5c5baaad1e5a521cfdcf96c&code=".$wechat."&grant_type=authorization_code";
- // $res = file_get_contents($url); //file_get_contents获取指定路由返回的数据
- // \Log::info($res);
- // $arr = json_decode($res, true);
- // $openid='';
- // if(!$arr['errcode'])$openid = $arr['openid'];
- \Log::info('openid: ' . $wechat);
- $jpush = $request->jpush;
- $key = $this->keySmsCode . $phone;
- $code = Cache::store('file')->get($key);
- $password = 123456;
- if ($request->verify_code != $code) return $this->error(ErrorCode::SERVICE_CODE_FAILED);
- $user = UserInfoModel::where('phone',$phone)->first();
- if (empty($user)) {
- $user = UserInfoModel::create([
- 'phone'=>$phone,
- 'wechat'=>$wechat,
- 'jpush'=>$jpush,
- 'nickname'=>'瞄喵',
- 'status'=>1,
- 'password'=>bcrypt(123456)
- ]);
- }else{
- //用户已经存在,重新绑定
- $user->wechat=$wechat;
- $user->password=bcrypt(123456);
- $user->save();
- }
- $status =empty($user) ? 0 : $user->status;
- if ($status == 0) return $this->error(ErrorCode::LOCK_USER);
- if (Auth::attempt(['phone'=>$phone,'password'=>$password])) {
- $user = Auth::user();
- /* if (!empty($wechat)) {
- $user->wechat =$wechat;
- $user->save();
- }*/
- \Log::info($user);
- $token = $user->createToken($user->phone)->accessToken;
- return $this->api(compact( 'user', 'code','token'));
- }else{
- return $this->error(ErrorCode::INCORRECT_USER_OR_PASS);
- }
- }
- // 第三方登录 微信
- /**
- * @api {get} /api/auth/wechat_login 微信登陆(login)
- * @apiDescription 微信登陆(login)
- * @apiGroup Auth
- * @apiPermission none
- * @apiVersion 0.1.0
- * @apiParam {string} wechat 微信id
- * @apiSuccessExample {json} Success-Response:
- * HTTP/1.1 200 OK
- * {
- * "state": true,
- * "code": 0,
- * "message": "",
- * "data": {
- * "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjdjYWUyYzFmYTUwMTIyZDI0ZTRiYTZhZGZhNmQxYmZlOWNiMzIxMTBmYWJlZjNjYzIyNmViZjRmNGExNWM3NjllNmU2ZTNiYWE5OGNhOWUzIn0.eyJhdWQiOiIxIiwianRpIjoiN2NhZTJjMWZhNTAxMjJkMjRlNGJhNmFkZmE2ZDFiZmU5Y2IzMjExMGZhYmVmM2NjMjI2ZWJmNGY0YTE1Yzc2OWU2ZTZlM2JhYTk4Y2E5ZTMiLCJpYXQiOjE0NzU0MTE1NTgsIm5iZiI6MTQ3NTQxMTU1OCwiZXhwIjo0NjMxMDg1MTU4LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.E9YGEzuRUOk02aV1EiWLJ_pD0hKoCyW0k_sGy63hM3u5X8K_HI1kVhaU6JNLqLZeszIAroTEDB8XMgZKAqTLlwtL8PLCJcuDoxfk1BRHbfjhDheTsahBysKGalvNEpzRCrGlao0mS0Cg9qDpEsndtypPFS8sfaflToOzbJjiSK2DvQiHSH8xZI3zHJTezgZMz-pB_hPTxp8ajdv0ve1gWtWjs3vERr0Y91X4hngO8X7LuXtAYtfxGZRIye12YE7TuLBMYzj8CCfiRt7Smhyf4palNW5mzKlZpa2l87n6NQ14Iy4oMzQ2PON1j_swrosuE2yZohGOn6fDdSCBRdJ6dLD_emjBdQCQOoB63R7BbhFZgvFX25TjzFJ7r9AdVMiGmebuRKEVSZV_JCGu1C71OIbQk-UK35s00gSr2fmJGBbN2cZTXBRTJpfuMZ_ihFYEZrvVq_Ih2X0xkd36JUuxaUld1BXRgPZvH-9jBuhe0YW2OOlgwpdm6ZB8BMcuS4ftLoi6FipgzFqfIuy-0ZqPMDnJaG7Gycrdpxza00mgOFxYxJtqwZNsUWFRZEVU881l6VC_cy294YXSPQxUwEoyKg-G5Pm8AEB9bqv5z4EU4B8-XTd3zKNqtNba_snHbc711i4EytCiZfYSjNB1hwenq45YYOAhPTwOpFI0kxyRazc",
- * "user": {
- * "id": 1,
- * "name": "15888888888",
- * "email": "abcdefg@gmail.com",
- * "type": 2,
- * "phone": "15888888888",
- * "avatar": null,
- * "last_ip": null,
- * "created_at": "2016-09-30 00:45:13",
- * "updated_at": "2016-09-29 16:43:36"
- * }
- * }
- * }
- * @apiErrorExample {json} Error-Response:
- * HTTP/1.1 400 Bad Request
- */
- public function wechatLogin(Request $request) {
- $validator = Validator::make($request->all(),
- [
- 'wechat' => 'required',
- ],
- [
- 'wechat.required' => '微信id不存在',
- ]
- );
- if ($validator->fails())
- return $this->validatorError($validator->messages()->all(),ErrorCode::CLIENT_WRONG_PARAMS);
- $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxc5181c0d406023e6&secret=82d15bf4c5c5baaad1e5a521cfdcf96c&code=".$request->wechat."&grant_type=authorization_code";
- $res = file_get_contents($url); //file_get_contents获取指定路由返回的数据
- \Log::info($res);
- $arr = json_decode($res, true);
- $openid='';
- if(!isset($arr['errcode']))$openid = $arr['openid'];
- \Log::info('openid: ' . $openid);
- if($openid!='')$user = UserInfoModel::where('wechat',$openid)->first();
- if (empty($user)) {
- // return $this->error(ErrorCode::LOGIN_FAILED);
- return $this->api(compact('openid'));
- }else{
- $token = $user->createToken($user->phone)->accessToken;
- return $this->api(compact( 'user', 'openid','token'));
- }
- }
- /**
- * @api {get} /api/auth/logout 退出(logout)
- * @apiDescription 退出(logout)
- * @apiGroup Auth
- * @apiPermission Passport
- * @apiVersion 0.1.0
- * @apiSuccessExample {json} Success-Response:
- * HTTP/1.1 200 OK
- * {
- * "state": true,
- * "code": 0,
- * "message": "",
- * "data": {
- * "result": true/false
- * }
- * }
- * @apiErrorExample {json} Error-Response:
- * HTTP/1.1 400 Bad Request
- * {
- * "state": false,
- * "code": 1104,
- * "message": "退出失败",
- * "data": null
- * }
- * 可能出现的错误代码:
- * 1104 LOGOUT_FAILED 退出失败
- */
- public function logout() {
- $user = Auth::guard('api')->user();
- if ($user->token()->delete()) {
- return $this->api(['result' => true]);
- }
- return $this->error(ErrorCode::LOGOUT_FAILED);
- }
- /**
- * @api {post} /api/auth/code 获取验证码(get code)
- * @apiDescription 获取验证码(get code),验证码有效期暂定为15分钟
- * @apiGroup Auth
- * @apiPermission none
- * @apiVersion 0.1.0
- * @apiParam {string} phone 手机
- * @apiSuccessExample {json} Success-Response:
- * HTTP/1.1 200 OK
- * {
- * "state": true,
- * "code": 0,
- * "message": "",
- * "data": {
- * "verify_code": "1234"//该值调试时使用,sms调通后取消
- * }
- * }
- * @apiErrorExample {json} Error-Response:
- * HTTP/1.1 400 Bad Request
- * {
- * "state": false,
- * "code": 1000,
- * "message": "传入参数不正确",
- * "data": null or []
- * }
- * 可能出现的错误代码:
- * 1000 CLIENT_WRONG_PARAMS 传入参数不正确
- */
- public function getCode(Request $request)
- {
- $validator = Validator::make($request->all(),
- [
- 'phone' => 'required|regex:/^1[34578]\d{9}$/',
- ],
- [
- 'phone.required' => '手机号码必填',
- 'phone.regex' => '手机号码格式不正确',
- ]
- );
- if ($validator->fails())
- return $this->validatorError($validator->messages()->all(),ErrorCode::CLIENT_WRONG_PARAMS);
- $phone = $request->phone;
- $keyexist = $this->keySmsCodeExist . $phone;
- $times = Cache::store('file')->get($keyexist);
- if($times>20) {
- return $this->error(ErrorCode::VERIFY_CODE_TOO_MUCH);
- }else{
- $times++;
- Cache::store('file')->put($keyexist, $times, $this->expireTimeExist);
- }
- $verify_code = (string) mt_rand(1000, 9999);
- \Log::info('verify_code:'.$verify_code);
- $key = $this->keySmsCode . $phone;
- Cache::store('file')->put($key, $verify_code, $this->expireTime);
- $msg = '【喵喵】您的验证码是:' . $verify_code;
- /*
- $result = $this->sendSms($msg, $phone);
- if (!$result)
- $this->logger->Error("Send sms failed.");
- */
- return $this->api(['verify_code' => $verify_code]);
- }
- public function refreshToken() {
- $token = '';//TODO
- return $this->api([
- 'token' => $token,
- ]);
- }
- public function isLogin()
- {
- $user = Auth::user();
- $res = true;
- if(!$user) $res = false;
- return $this->api([
- 'result' => $res,
- ]);
- }
- /**
- * @api {post} /api/auth/avatar 上传头像(avatar)
- * @apiDescription 上传头像(reset)
- * @apiGroup Auth
- * @apiPermission Passport
- * @apiVersion 0.1.0
- * @apiParam {File} avatar 头像图片
- * @apiSuccessExample {json} Success-Response:
- * HTTP/1.1 200 OK
- * {
- * "state": true,
- * "code": 0,
- * "message": "",
- * "data": {
- * "md5": "fdf8dd78eb383b8acf6d94d4752c1424",
- * }
- * }
- * @apiErrorExample {json} Error-Response:
- * HTTP/1.1 400 Bad Request
- * {
- * "state": false,
- * "code": 1000,
- * "message": "传入参数不正确",
- * "data": null or []
- * }
- * 可能出现的错误代码:
- * 200 SAVE_USER_FAILED 保存用户数据失败
- * 201 ATTACHMENT_MKDIR_FAILED 创建附件目录失败
- * 202 ATTACHMENT_UPLOAD_INVALID 上传附件文件无效
- * 203 ATTACHMENT_SAVE_FAILED 保存附件失败
- * 204 ATTACHMENT_MOVE_FAILED 移动附件失败
- * 205 ATTACHMENT_DELETE_FAILED 删除附件文件失败
- * 206 ATTACHMENT_RECORD_DELETE_FAILED 删除附件记录失败
- * 1000 CLIENT_WRONG_PARAMS 传入参数不正确
- * 1101 INCORRECT_VERIFY_CODE 输入验证码错误
- * 1105 USER_DOES_NOT_EXIST 用户不存在
- * 1200 ATTACHMENT_UPLOAD_FAILED 附件上传失败
- * 1201 ATTACHMENT_SIZE_EXCEEDED 附件大小超过限制
- * 1202 ATTACHMENT_MIME_NOT_ALLOWED 附件类型不允许
- * 1203 ATTACHMENT_NOT_EXIST 附件不存在
- */
- public function avatar(Request $request) {
- // $user = Auth::user();
- $user = $this->getUser();
- $old_avatar = $user->avatar;
- $result = $this->uploadAttachment($request, 'avatar', 'avatar', 4 * 1024 * 1024, [
- 'image/jpeg',
- 'image/png',
- 'image/gif',
- ]);
- if (is_array($result)) {
- $result = array_shift($result);
- }
- if (is_string($result)) {
- $user->avatar = config('app.url')."/attachment/".$result;
- if (!$user->save()) {
- return $this->error(ErrorCode::SAVE_USER_FAILED);
- }
- $this->deleteAttachment($old_avatar);
- return $this->api(['file' => $result]);
- }
- return $this->error($result);
- }
- }
|