AuthController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. <?php
  2. namespace App\Http\Controllers\Api\V1;
  3. use App\Helper\AttachmentHelper;
  4. use App\Helper\SmsHelper;
  5. use Illuminate\Foundation\Auth\AuthenticatesUsers;
  6. use App\Models\UserInfoModel;
  7. use Illuminate\Http\Request;
  8. use App\Services\Base\ErrorCode;
  9. use Validator, Auth, Cache;
  10. class AuthController extends Controller
  11. {
  12. use SmsHelper,AuthenticatesUsers,AttachmentHelper;
  13. private $expireTime = 1;
  14. private $keySmsCode = 'auth:sms:';
  15. private $keySmsCodeExist = 'auth:sms:exist';
  16. private $expireTimeExist = 24*60;
  17. public function test(){
  18. // return $this->error(ErrorCode::SAVE_USER_FAILED);
  19. return $this->api(['test' => 'test']);
  20. }
  21. /**
  22. * @api {post} /api/auth/login 登陆(login)
  23. * @apiDescription 登陆(login)
  24. * @apiGroup Auth
  25. * @apiPermission none
  26. * @apiVersion 0.1.0
  27. * @apiParam {string} phone 手机号码
  28. * @apiParam {String} verify_code 手机验证码
  29. * @apiSuccessExample {json} Success-Response:
  30. * HTTP/1.1 200 OK
  31. * {
  32. * "state": true,
  33. * "code": 0,
  34. * "message": "",
  35. * "data": {
  36. * "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjdjYWUyYzFmYTUwMTIyZDI0ZTRiYTZhZGZhNmQxYmZlOWNiMzIxMTBmYWJlZjNjYzIyNmViZjRmNGExNWM3NjllNmU2ZTNiYWE5OGNhOWUzIn0.eyJhdWQiOiIxIiwianRpIjoiN2NhZTJjMWZhNTAxMjJkMjRlNGJhNmFkZmE2ZDFiZmU5Y2IzMjExMGZhYmVmM2NjMjI2ZWJmNGY0YTE1Yzc2OWU2ZTZlM2JhYTk4Y2E5ZTMiLCJpYXQiOjE0NzU0MTE1NTgsIm5iZiI6MTQ3NTQxMTU1OCwiZXhwIjo0NjMxMDg1MTU4LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.E9YGEzuRUOk02aV1EiWLJ_pD0hKoCyW0k_sGy63hM3u5X8K_HI1kVhaU6JNLqLZeszIAroTEDB8XMgZKAqTLlwtL8PLCJcuDoxfk1BRHbfjhDheTsahBysKGalvNEpzRCrGlao0mS0Cg9qDpEsndtypPFS8sfaflToOzbJjiSK2DvQiHSH8xZI3zHJTezgZMz-pB_hPTxp8ajdv0ve1gWtWjs3vERr0Y91X4hngO8X7LuXtAYtfxGZRIye12YE7TuLBMYzj8CCfiRt7Smhyf4palNW5mzKlZpa2l87n6NQ14Iy4oMzQ2PON1j_swrosuE2yZohGOn6fDdSCBRdJ6dLD_emjBdQCQOoB63R7BbhFZgvFX25TjzFJ7r9AdVMiGmebuRKEVSZV_JCGu1C71OIbQk-UK35s00gSr2fmJGBbN2cZTXBRTJpfuMZ_ihFYEZrvVq_Ih2X0xkd36JUuxaUld1BXRgPZvH-9jBuhe0YW2OOlgwpdm6ZB8BMcuS4ftLoi6FipgzFqfIuy-0ZqPMDnJaG7Gycrdpxza00mgOFxYxJtqwZNsUWFRZEVU881l6VC_cy294YXSPQxUwEoyKg-G5Pm8AEB9bqv5z4EU4B8-XTd3zKNqtNba_snHbc711i4EytCiZfYSjNB1hwenq45YYOAhPTwOpFI0kxyRazc",
  37. * "user": {
  38. * "id": 1,
  39. * "name": "15888888888",
  40. * "email": "abcdefg@gmail.com",
  41. * "type": 2,
  42. * "phone": "15888888888",
  43. * "avatar": null,
  44. * "last_ip": null,
  45. * "created_at": "2016-09-30 00:45:13",
  46. * "updated_at": "2016-09-29 16:43:36"
  47. * }
  48. * }
  49. * }
  50. * @apiErrorExample {json} Error-Response:
  51. * HTTP/1.1 400 Bad Request
  52. * {
  53. * "state": false,
  54. * "code": 1000,
  55. * "message": "传入参数不正确",
  56. * "data": null or []
  57. * }
  58. * 可能出现的错误代码:
  59. * 1000 CLIENT_WRONG_PARAMS 传入参数不正确
  60. * 1103 VERIFY_CODE_TOO_MUCH 验证码大于5次
  61. * 1610 SERVICE_CODE_FAILED 验证码错误
  62. *
  63. */
  64. public function login(Request $request) {
  65. $validator = Validator::make($request->all(),
  66. [
  67. 'phone' => 'required|regex:/^1[34578]\d{9}$/',
  68. 'verify_code' => 'required',
  69. ],
  70. [
  71. 'phone.required' => '请输入手机号码',
  72. 'phone.regex' => '手机号码格式不正确',
  73. 'verify_code.required' => '短信验证码必填',
  74. ]
  75. );
  76. if ($validator->fails())
  77. return $this->validatorError($validator->messages()->all(),ErrorCode::CLIENT_WRONG_PARAMS);
  78. $phone = $request->phone;
  79. $key = $this->keySmsCode . $phone;
  80. $code = Cache::store('file')->get($key);
  81. $password = 123456;
  82. if ($request->verify_code != $code)
  83. return $this->error(ErrorCode::SERVICE_CODE_FAILED);
  84. $user = UserInfoModel::where('phone',$phone)->first();
  85. if (empty($user)) {
  86. $user = UserInfoModel::create(['phone'=>$phone,'password'=>bcrypt(123456)]);
  87. $user->status=1;
  88. }
  89. $status =empty($user) ? 0 : $user->status;
  90. if ($status == 0) return $this->error(ErrorCode::LOCK_USER);
  91. if (Auth::attempt(['phone'=>$phone,'password'=>$password])) {
  92. $user = Auth::user();
  93. \Log::info($user);
  94. $token = $user->createToken($user->phone)->accessToken;
  95. return $this->api(compact( 'user', 'code','token'));
  96. }else{
  97. return $this->error(ErrorCode::INCORRECT_USER_OR_PASS);
  98. }
  99. }
  100. /**
  101. * @api {get} /api/auth/logout 退出(logout)
  102. * @apiDescription 退出(logout)
  103. * @apiGroup Auth
  104. * @apiPermission Passport
  105. * @apiVersion 0.1.0
  106. * @apiSuccessExample {json} Success-Response:
  107. * HTTP/1.1 200 OK
  108. * {
  109. * "state": true,
  110. * "code": 0,
  111. * "message": "",
  112. * "data": {
  113. * "result": true/false
  114. * }
  115. * }
  116. * @apiErrorExample {json} Error-Response:
  117. * HTTP/1.1 400 Bad Request
  118. * {
  119. * "state": false,
  120. * "code": 1104,
  121. * "message": "退出失败",
  122. * "data": null
  123. * }
  124. * 可能出现的错误代码:
  125. * 1104 LOGOUT_FAILED 退出失败
  126. */
  127. public function logout() {
  128. $user = Auth::guard('api')->user();
  129. if ($user->token()->delete()) {
  130. return $this->api(['result' => true]);
  131. }
  132. return $this->error(ErrorCode::LOGOUT_FAILED);
  133. }
  134. /**
  135. * @api {post} /api/auth/code 获取验证码(get code)
  136. * @apiDescription 获取验证码(get code),验证码有效期暂定为15分钟
  137. * @apiGroup Auth
  138. * @apiPermission none
  139. * @apiVersion 0.1.0
  140. * @apiParam {string} phone 手机
  141. * @apiSuccessExample {json} Success-Response:
  142. * HTTP/1.1 200 OK
  143. * {
  144. * "state": true,
  145. * "code": 0,
  146. * "message": "",
  147. * "data": {
  148. * "verify_code": "1234"//该值调试时使用,sms调通后取消
  149. * }
  150. * }
  151. * @apiErrorExample {json} Error-Response:
  152. * HTTP/1.1 400 Bad Request
  153. * {
  154. * "state": false,
  155. * "code": 1000,
  156. * "message": "传入参数不正确",
  157. * "data": null or []
  158. * }
  159. * 可能出现的错误代码:
  160. * 1000 CLIENT_WRONG_PARAMS 传入参数不正确
  161. */
  162. public function getCode(Request $request)
  163. {
  164. $validator = Validator::make($request->all(),
  165. [
  166. 'phone' => 'required|regex:/^1[34578]\d{9}$/',
  167. ],
  168. [
  169. 'phone.required' => '手机号码必填',
  170. 'phone.regex' => '手机号码格式不正确',
  171. ]
  172. );
  173. if ($validator->fails())
  174. return $this->validatorError($validator->messages()->all(),ErrorCode::CLIENT_WRONG_PARAMS);
  175. $phone = $request->phone;
  176. $keyexist = $this->keySmsCodeExist . $phone;
  177. $times = Cache::store('file')->get($keyexist);
  178. if($times>5) {
  179. return $this->error(ErrorCode::VERIFY_CODE_TOO_MUCH);
  180. }else{
  181. $times++;
  182. Cache::store('file')->put($keyexist, $times, $this->expireTimeExist);
  183. }
  184. $verify_code = (string) mt_rand(1000, 9999);
  185. \Log::info('verify_code:'.$verify_code);
  186. $key = $this->keySmsCode . $phone;
  187. Cache::store('file')->put($key, $verify_code, $this->expireTime);
  188. $msg = '【喵喵】您的验证码是:' . $verify_code;
  189. /*
  190. $result = $this->sendSms($msg, $phone);
  191. if (!$result)
  192. $this->logger->Error("Send sms failed.");
  193. */
  194. return $this->api(['verify_code' => $verify_code]);
  195. }
  196. public function refreshToken() {
  197. $token = '';//TODO
  198. return $this->api([
  199. 'token' => $token,
  200. ]);
  201. }
  202. public function isLogin()
  203. {
  204. $user = Auth::user();
  205. $res = true;
  206. if(!$user) $res = false;
  207. return $this->api([
  208. 'result' => $res,
  209. ]);
  210. }
  211. /**
  212. * @api {post} /api/auth/avatar 上传头像(avatar)
  213. * @apiDescription 上传头像(reset)
  214. * @apiGroup Auth
  215. * @apiPermission Passport
  216. * @apiVersion 0.1.0
  217. * @apiParam {File} avatar 头像图片
  218. * @apiSuccessExample {json} Success-Response:
  219. * HTTP/1.1 200 OK
  220. * {
  221. * "state": true,
  222. * "code": 0,
  223. * "message": "",
  224. * "data": {
  225. * "md5": "fdf8dd78eb383b8acf6d94d4752c1424",
  226. * }
  227. * }
  228. * @apiErrorExample {json} Error-Response:
  229. * HTTP/1.1 400 Bad Request
  230. * {
  231. * "state": false,
  232. * "code": 1000,
  233. * "message": "传入参数不正确",
  234. * "data": null or []
  235. * }
  236. * 可能出现的错误代码:
  237. * 200 SAVE_USER_FAILED 保存用户数据失败
  238. * 201 ATTACHMENT_MKDIR_FAILED 创建附件目录失败
  239. * 202 ATTACHMENT_UPLOAD_INVALID 上传附件文件无效
  240. * 203 ATTACHMENT_SAVE_FAILED 保存附件失败
  241. * 204 ATTACHMENT_MOVE_FAILED 移动附件失败
  242. * 205 ATTACHMENT_DELETE_FAILED 删除附件文件失败
  243. * 206 ATTACHMENT_RECORD_DELETE_FAILED 删除附件记录失败
  244. * 1000 CLIENT_WRONG_PARAMS 传入参数不正确
  245. * 1101 INCORRECT_VERIFY_CODE 输入验证码错误
  246. * 1105 USER_DOES_NOT_EXIST 用户不存在
  247. * 1200 ATTACHMENT_UPLOAD_FAILED 附件上传失败
  248. * 1201 ATTACHMENT_SIZE_EXCEEDED 附件大小超过限制
  249. * 1202 ATTACHMENT_MIME_NOT_ALLOWED 附件类型不允许
  250. * 1203 ATTACHMENT_NOT_EXIST 附件不存在
  251. */
  252. public function avatar(Request $request) {
  253. // $user = Auth::user();
  254. $user = $this->getUser();
  255. $old_avatar = $user->avatar;
  256. $result = $this->uploadAttachment($request, 'avatar', 'avatar', 4 * 1024 * 1024, [
  257. 'image/jpeg',
  258. 'image/png',
  259. 'image/gif',
  260. ]);
  261. if (is_array($result)) {
  262. $result = array_shift($result);
  263. }
  264. if (is_string($result)) {
  265. $user->avatar = config('app.url')."/api/attachment/download/".$result;
  266. if (!$user->save()) {
  267. return $this->error(ErrorCode::SAVE_USER_FAILED);
  268. }
  269. $this->deleteAttachment($old_avatar);
  270. return $this->api(['file' => $result]);
  271. }
  272. return $this->error($result);
  273. }
  274. }