AuthController.php 15 KB

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