AuthController.php 17 KB

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