AuthController.php 15 KB

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