AuthController.php 15 KB

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