AuthController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. <?php
  2. namespace App\Http\Controllers\Api\V1;
  3. use App\Helper\AttachmentHelper;
  4. use App\Helper\JpushHelper;
  5. use App\Helper\SmsHelper;
  6. use Illuminate\Foundation\Auth\AuthenticatesUsers;
  7. use App\Models\UserInfoModel;
  8. use Illuminate\Http\Request;
  9. use App\Services\Base\ErrorCode;
  10. use Validator, Auth, Cache;
  11. class AuthController extends Controller
  12. {
  13. use SmsHelper,AuthenticatesUsers,AttachmentHelper,JpushHelper;
  14. private $expireTime = 5;
  15. private $keySmsCode = 'auth:sms:';
  16. private $keySmsCodeExist = 'auth:sms:exist';
  17. private $expireTimeExist = 24*60;
  18. public function test(){
  19. //test
  20. if(env("APP_DEBUG")){
  21. return $this->error(0);
  22. }else{
  23. //product
  24. return $this->api(1);
  25. }
  26. }
  27. /**
  28. * @api {post} /api/auth/login 登陆(login)
  29. * @apiDescription 登陆(login)
  30. * @apiGroup Auth
  31. * @apiPermission none
  32. * @apiVersion 0.1.0
  33. * @apiParam {string} phone 手机号码
  34. * @apiParam {string} [jpush]
  35. * @apiParam {string} wechat 微信openid
  36. * @apiParam {String} verify_code 手机验证码
  37. * @apiSuccessExample {json} Success-Response:
  38. * HTTP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Pm8AEB9bqv5z4EU4B8-XTd3zKNqtNba_snHbc711i4EytCiZfYSjNB1hwenq45YYOAhPTwOpFI0kxyRazc",
  45. * "user": {
  46. * "id": 1,
  47. * "name": "15888888888",
  48. * "email": "abcdefg@gmail.com",
  49. * "type": 2,
  50. * "phone": "15888888888",
  51. * "avatar": null,
  52. * "last_ip": null,
  53. * "created_at": "2016-09-30 00:45:13",
  54. * "updated_at": "2016-09-29 16:43:36"
  55. * }
  56. * }
  57. * }
  58. * @apiErrorExample {json} Error-Response:
  59. * HTTP/1.1 400 Bad Request
  60. * {
  61. * "state": false,
  62. * "code": 1000,
  63. * "message": "传入参数不正确",
  64. * "data": null or []
  65. * }
  66. * 可能出现的错误代码:
  67. * 1000 CLIENT_WRONG_PARAMS 传入参数不正确
  68. * 1103 VERIFY_CODE_TOO_MUCH 验证码大于5次
  69. * 1610 SERVICE_CODE_FAILED 验证码错误
  70. *
  71. */
  72. public function login(Request $request) {
  73. $this->jPush('1212大减价','',1);dd();
  74. $validator = Validator::make($request->all(),
  75. [
  76. // 'wechat' => 'required',
  77. 'phone' => 'required|regex:/^1[34578]\d{9}$/',
  78. 'verify_code' => 'required',
  79. ],
  80. [
  81. // 'wechat.required' => '请先绑定微信',
  82. 'phone.required' => '请输入手机号码',
  83. 'phone.regex' => '手机号码格式不正确',
  84. 'verify_code.required' => '短信验证码必填',
  85. ]
  86. );
  87. if ($validator->fails())
  88. return $this->validatorError($validator->messages()->all(),ErrorCode::CLIENT_WRONG_PARAMS);
  89. $phone = $request->phone;
  90. $wechat = $request->wechat;
  91. // $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxc5181c0d406023e6&secret=82d15bf4c5c5baaad1e5a521cfdcf96c&code=".$wechat."&grant_type=authorization_code";
  92. // $res = file_get_contents($url); //file_get_contents获取指定路由返回的数据
  93. // \Log::info($res);
  94. // $arr = json_decode($res, true);
  95. // $openid='';
  96. // if(!$arr['errcode'])$openid = $arr['openid'];
  97. \Log::info('openid: ' . $wechat);
  98. $user = UserInfoModel::where('wechat',$wechat)->first();
  99. $jpush = $request->jpush;
  100. $key = $this->keySmsCode . $phone;
  101. $code = Cache::store('file')->get($key);
  102. $password = 123456;
  103. if ($request->verify_code != $code) return $this->error(ErrorCode::SERVICE_CODE_FAILED);
  104. if(empty($user)){
  105. $user = UserInfoModel::where('phone',$phone)->first();
  106. }else{
  107. $phone_user = UserInfoModel::where('phone',$phone)->first();
  108. if(!empty($phone_user)){
  109. // return $this->error(ErrorCode::USER_DOES_EXIST);
  110. $user = $phone_user;
  111. $token = $user->createToken($user->phone)->accessToken;
  112. return $this->api(compact( 'user', 'code','token'));
  113. }
  114. }
  115. // 如果走到这里 就检查user_info.phone是否唯一 允许为空
  116. if (empty($user)) {
  117. $user = UserInfoModel::create([
  118. 'phone'=>$phone,
  119. 'wechat'=>$wechat,
  120. 'jpush'=>$jpush,
  121. 'nickname'=>'瞄喵'.rand(1000,9999),
  122. 'status'=>1,
  123. 'password'=>bcrypt(123456)
  124. ]);
  125. }else{
  126. //用户已经存在,重新绑定
  127. $user->wechat=$wechat;
  128. $user->phone=$phone;
  129. $user->password=bcrypt(123456);
  130. $user->save();
  131. }
  132. $status =empty($user) ? 0 : $user->status;
  133. if ($status == 0) return $this->error(ErrorCode::LOCK_USER);
  134. if (Auth::attempt(['phone'=>$phone,'password'=>$password])) {
  135. $user = Auth::user();
  136. /* if (!empty($wechat)) {
  137. $user->wechat =$wechat;
  138. $user->save();
  139. }*/
  140. \Log::info($user);
  141. $token = $user->createToken($user->phone)->accessToken;
  142. return $this->api(compact( 'user', 'code','token'));
  143. }else{
  144. return $this->error(ErrorCode::INCORRECT_USER_OR_PASS);
  145. }
  146. }
  147. // 第三方登录 微信
  148. /**
  149. * @api {get} /api/auth/wechat_login 微信登陆(login)
  150. * @apiDescription 微信登陆(login)
  151. * @apiGroup Auth
  152. * @apiPermission none
  153. * @apiVersion 0.1.0
  154. * @apiParam {string} wechat 微信id
  155. * @apiSuccessExample {json} Success-Response:
  156. * HTTP/1.1 200 OK
  157. * {
  158. * "state": true,
  159. * "code": 0,
  160. * "message": "",
  161. * "data": {
  162. * "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjdjYWUyYzFmYTUwMTIyZDI0ZTRiYTZhZGZhNmQxYmZlOWNiMzIxMTBmYWJlZjNjYzIyNmViZjRmNGExNWM3NjllNmU2ZTNiYWE5OGNhOWUzIn0.eyJhdWQiOiIxIiwianRpIjoiN2NhZTJjMWZhNTAxMjJkMjRlNGJhNmFkZmE2ZDFiZmU5Y2IzMjExMGZhYmVmM2NjMjI2ZWJmNGY0YTE1Yzc2OWU2ZTZlM2JhYTk4Y2E5ZTMiLCJpYXQiOjE0NzU0MTE1NTgsIm5iZiI6MTQ3NTQxMTU1OCwiZXhwIjo0NjMxMDg1MTU4LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.E9YGEzuRUOk02aV1EiWLJ_pD0hKoCyW0k_sGy63hM3u5X8K_HI1kVhaU6JNLqLZeszIAroTEDB8XMgZKAqTLlwtL8PLCJcuDoxfk1BRHbfjhDheTsahBysKGalvNEpzRCrGlao0mS0Cg9qDpEsndtypPFS8sfaflToOzbJjiSK2DvQiHSH8xZI3zHJTezgZMz-pB_hPTxp8ajdv0ve1gWtWjs3vERr0Y91X4hngO8X7LuXtAYtfxGZRIye12YE7TuLBMYzj8CCfiRt7Smhyf4palNW5mzKlZpa2l87n6NQ14Iy4oMzQ2PON1j_swrosuE2yZohGOn6fDdSCBRdJ6dLD_emjBdQCQOoB63R7BbhFZgvFX25TjzFJ7r9AdVMiGmebuRKEVSZV_JCGu1C71OIbQk-UK35s00gSr2fmJGBbN2cZTXBRTJpfuMZ_ihFYEZrvVq_Ih2X0xkd36JUuxaUld1BXRgPZvH-9jBuhe0YW2OOlgwpdm6ZB8BMcuS4ftLoi6FipgzFqfIuy-0ZqPMDnJaG7Gycrdpxza00mgOFxYxJtqwZNsUWFRZEVU881l6VC_cy294YXSPQxUwEoyKg-G5Pm8AEB9bqv5z4EU4B8-XTd3zKNqtNba_snHbc711i4EytCiZfYSjNB1hwenq45YYOAhPTwOpFI0kxyRazc",
  163. * "user": {
  164. * "id": 1,
  165. * "name": "15888888888",
  166. * "email": "abcdefg@gmail.com",
  167. * "type": 2,
  168. * "phone": "15888888888",
  169. * "avatar": null,
  170. * "last_ip": null,
  171. * "created_at": "2016-09-30 00:45:13",
  172. * "updated_at": "2016-09-29 16:43:36"
  173. * }
  174. * }
  175. * }
  176. * @apiErrorExample {json} Error-Response:
  177. * HTTP/1.1 400 Bad Request
  178. */
  179. public function wechatLogin(Request $request) {
  180. $validator = Validator::make($request->all(),
  181. [
  182. 'wechat' => 'required',
  183. ],
  184. [
  185. 'wechat.required' => '微信id不存在',
  186. ]
  187. );
  188. if ($validator->fails())
  189. return $this->validatorError($validator->messages()->all(),ErrorCode::CLIENT_WRONG_PARAMS);
  190. $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxc5181c0d406023e6&secret=82d15bf4c5c5baaad1e5a521cfdcf96c&code=".$request->wechat."&grant_type=authorization_code";
  191. $res = file_get_contents($url); //file_get_contents获取指定路由返回的数据
  192. \Log::info($res);
  193. $arr = json_decode($res, true);
  194. $openid='';
  195. if(!isset($arr['errcode']))$openid = $arr['openid'];
  196. if(!empty($openid)){
  197. $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$arr['access_token']."&openid=".$openid."&lang=zh_CN";
  198. $userInfoJson = file_get_contents($url); //file_get_contents获取指定路由返回的数据
  199. $userInfo = json_decode($userInfoJson, true);
  200. \Log::info('userInfo: ' . $userInfoJson);
  201. }
  202. \Log::info('openid: ' . $openid);
  203. if($openid!='')$user = UserInfoModel::where('wechat',$openid)->first();
  204. \Log::info($user);
  205. if (empty($user)||$user->phone=='') {
  206. \Log::info('empty: ' . empty($user));
  207. if(empty($user)){
  208. UserInfoModel::create([
  209. 'wechat'=>$openid,
  210. 'nickname'=>$userInfo['nickname'],
  211. 'avatar'=>$userInfo['headimgurl'],
  212. 'status'=>1,
  213. 'password'=>bcrypt(123456)
  214. ]);
  215. }
  216. return $this->api(['openid' => $openid]);
  217. // return $this->api(['wechat' => $openid]);
  218. }else{
  219. $token = $user->createToken($user->phone)->accessToken;
  220. return $this->api(compact( 'user', 'openid','token'));
  221. }
  222. }
  223. /**
  224. * @api {get} /api/auth/logout 退出(logout)
  225. * @apiDescription 退出(logout)
  226. * @apiGroup Auth
  227. * @apiPermission Passport
  228. * @apiVersion 0.1.0
  229. * @apiSuccessExample {json} Success-Response:
  230. * HTTP/1.1 200 OK
  231. * {
  232. * "state": true,
  233. * "code": 0,
  234. * "message": "",
  235. * "data": {
  236. * "result": true/false
  237. * }
  238. * }
  239. * @apiErrorExample {json} Error-Response:
  240. * HTTP/1.1 400 Bad Request
  241. * {
  242. * "state": false,
  243. * "code": 1104,
  244. * "message": "退出失败",
  245. * "data": null
  246. * }
  247. * 可能出现的错误代码:
  248. * 1104 LOGOUT_FAILED 退出失败
  249. */
  250. public function logout() {
  251. $user = Auth::guard('api')->user();
  252. if ($user->token()->delete()) {
  253. return $this->api(['result' => true]);
  254. }
  255. return $this->error(ErrorCode::LOGOUT_FAILED);
  256. }
  257. /**
  258. * @api {post} /api/auth/code 获取验证码(get code)
  259. * @apiDescription 获取验证码(get code),验证码有效期暂定为15分钟
  260. * @apiGroup Auth
  261. * @apiPermission none
  262. * @apiVersion 0.1.0
  263. * @apiParam {string} phone 手机
  264. * @apiSuccessExample {json} Success-Response:
  265. * HTTP/1.1 200 OK
  266. * {
  267. * "state": true,
  268. * "code": 0,
  269. * "message": "",
  270. * "data": {
  271. * "verify_code": "1234"//该值调试时使用,sms调通后取消
  272. * }
  273. * }
  274. * @apiErrorExample {json} Error-Response:
  275. * HTTP/1.1 400 Bad Request
  276. * {
  277. * "state": false,
  278. * "code": 1000,
  279. * "message": "传入参数不正确",
  280. * "data": null or []
  281. * }
  282. * 可能出现的错误代码:
  283. * 1000 CLIENT_WRONG_PARAMS 传入参数不正确
  284. */
  285. public function getCode(Request $request)
  286. {
  287. $validator = Validator::make($request->all(),
  288. [
  289. 'phone' => 'required|regex:/^1[34578]\d{9}$/',
  290. ],
  291. [
  292. 'phone.required' => '手机号码必填',
  293. 'phone.regex' => '手机号码格式不正确',
  294. ]
  295. );
  296. if ($validator->fails())
  297. return $this->validatorError($validator->messages()->all(),ErrorCode::CLIENT_WRONG_PARAMS);
  298. $phone = $request->phone;
  299. $keyexist = $this->keySmsCodeExist . $phone;
  300. $times = Cache::store('file')->get($keyexist);
  301. if($times>60) {
  302. return $this->error(ErrorCode::VERIFY_CODE_TOO_MUCH);
  303. }else{
  304. $times++;
  305. Cache::store('file')->put($keyexist, $times, $this->expireTimeExist);
  306. }
  307. $verify_code = (string) mt_rand(1000, 9999);
  308. \Log::info('verify_code:'.$verify_code);
  309. $key = $this->keySmsCode . $phone;
  310. Cache::store('file')->put($key, $verify_code, $this->expireTime);
  311. $msg = '【喵喵】您的验证码是:(' . $verify_code.')。5分钟内有效请及时验证';
  312. if(env("APP_DEBUG")){
  313. return $this->api(['verify_code' => $verify_code]);
  314. }else{
  315. $result = $this->sendSms($msg, $phone);
  316. }
  317. // $result = $this->sendSms($msg, $phone);
  318. /*if (!$result)
  319. $this->logger->Error("Send sms failed.");*/
  320. if ($result!='success') {
  321. \Log::error("Send sms failed.");
  322. }
  323. // return $this->api(['verify_code' => $verify_code]);
  324. }
  325. public function refreshToken() {
  326. $token = '';//TODO
  327. return $this->api([
  328. 'token' => $token,
  329. ]);
  330. }
  331. public function isLogin()
  332. {
  333. $user = Auth::guard('api')->user();
  334. $res = true;
  335. if(!$user) $res = false;
  336. return $this->api([
  337. 'result' => $res,
  338. ]);
  339. }
  340. /**
  341. * @api {post} /api/auth/avatar 上传头像(avatar)
  342. * @apiDescription 上传头像(reset)
  343. * @apiGroup Auth
  344. * @apiPermission Passport
  345. * @apiVersion 0.1.0
  346. * @apiParam {File} avatar 头像图片
  347. * @apiSuccessExample {json} Success-Response:
  348. * HTTP/1.1 200 OK
  349. * {
  350. * "state": true,
  351. * "code": 0,
  352. * "message": "",
  353. * "data": {
  354. * "md5": "fdf8dd78eb383b8acf6d94d4752c1424",
  355. * }
  356. * }
  357. * @apiErrorExample {json} Error-Response:
  358. * HTTP/1.1 400 Bad Request
  359. * {
  360. * "state": false,
  361. * "code": 1000,
  362. * "message": "传入参数不正确",
  363. * "data": null or []
  364. * }
  365. * 可能出现的错误代码:
  366. * 200 SAVE_USER_FAILED 保存用户数据失败
  367. * 201 ATTACHMENT_MKDIR_FAILED 创建附件目录失败
  368. * 202 ATTACHMENT_UPLOAD_INVALID 上传附件文件无效
  369. * 203 ATTACHMENT_SAVE_FAILED 保存附件失败
  370. * 204 ATTACHMENT_MOVE_FAILED 移动附件失败
  371. * 205 ATTACHMENT_DELETE_FAILED 删除附件文件失败
  372. * 206 ATTACHMENT_RECORD_DELETE_FAILED 删除附件记录失败
  373. * 1000 CLIENT_WRONG_PARAMS 传入参数不正确
  374. * 1101 INCORRECT_VERIFY_CODE 输入验证码错误
  375. * 1105 USER_DOES_NOT_EXIST 用户不存在
  376. * 1200 ATTACHMENT_UPLOAD_FAILED 附件上传失败
  377. * 1201 ATTACHMENT_SIZE_EXCEEDED 附件大小超过限制
  378. * 1202 ATTACHMENT_MIME_NOT_ALLOWED 附件类型不允许
  379. * 1203 ATTACHMENT_NOT_EXIST 附件不存在
  380. */
  381. public function avatar(Request $request) {
  382. // $user = Auth::user();
  383. $user = $this->getUser();
  384. $old_avatar = $user->avatar;
  385. $result = $this->uploadAttachment($request, 'avatar', 'avatar', 4 * 1024 * 1024, [
  386. 'image/jpeg',
  387. 'image/png',
  388. 'image/gif',
  389. ]);
  390. if (is_array($result)) {
  391. $result = array_shift($result);
  392. }
  393. if (is_string($result)) {
  394. $user->avatar = config('app.url')."/attachment/".$result;
  395. if (!$user->save()) {
  396. return $this->error(ErrorCode::SAVE_USER_FAILED);
  397. }
  398. $this->deleteAttachment($old_avatar);
  399. return $this->api(['file' => $result]);
  400. }
  401. return $this->error($result);
  402. }
  403. }