ApiV1Dot1Controller.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use Cache;
  4. use DB;
  5. use App\Http\Controllers\Controller;
  6. use Illuminate\Http\Request;
  7. use League\Fractal;
  8. use League\Fractal\Serializer\ArraySerializer;
  9. use League\Fractal\Pagination\IlluminatePaginatorAdapter;
  10. use App\AccountLog;
  11. use App\EmailVerification;
  12. use App\Place;
  13. use App\Status;
  14. use App\Report;
  15. use App\Profile;
  16. use App\StatusArchived;
  17. use App\User;
  18. use App\Services\AccountService;
  19. use App\Services\StatusService;
  20. use App\Services\ProfileStatusService;
  21. use App\Util\Lexer\RestrictedNames;
  22. use App\Services\EmailService;
  23. use Illuminate\Support\Str;
  24. use Illuminate\Support\Facades\Hash;
  25. use Jenssegers\Agent\Agent;
  26. use Mail;
  27. use App\Mail\PasswordChange;
  28. use App\Mail\ConfirmAppEmail;
  29. use App\Http\Resources\StatusStateless;
  30. class ApiV1Dot1Controller extends Controller
  31. {
  32. protected $fractal;
  33. public function __construct()
  34. {
  35. $this->fractal = new Fractal\Manager();
  36. $this->fractal->setSerializer(new ArraySerializer());
  37. }
  38. public function json($res, $code = 200, $headers = [])
  39. {
  40. return response()->json($res, $code, $headers, JSON_UNESCAPED_SLASHES);
  41. }
  42. public function error($msg, $code = 400, $extra = [], $headers = [])
  43. {
  44. $res = [
  45. "msg" => $msg,
  46. "code" => $code
  47. ];
  48. return response()->json(array_merge($res, $extra), $code, $headers, JSON_UNESCAPED_SLASHES);
  49. }
  50. public function report(Request $request)
  51. {
  52. $user = $request->user();
  53. abort_if(!$user, 403);
  54. abort_if($user->status != null, 403);
  55. $report_type = $request->input('report_type');
  56. $object_id = $request->input('object_id');
  57. $object_type = $request->input('object_type');
  58. $types = [
  59. 'spam',
  60. 'sensitive',
  61. 'abusive',
  62. 'underage',
  63. 'violence',
  64. 'copyright',
  65. 'impersonation',
  66. 'scam',
  67. 'terrorism'
  68. ];
  69. if (!$report_type || !$object_id || !$object_type) {
  70. return $this->error("Invalid or missing parameters", 400, ["error_code" => "ERROR_INVALID_PARAMS"]);
  71. }
  72. if (!in_array($report_type, $types)) {
  73. return $this->error("Invalid report type", 400, ["error_code" => "ERROR_TYPE_INVALID"]);
  74. }
  75. if ($object_type === "user" && $object_id == $user->profile_id) {
  76. return $this->error("Cannot self report", 400, ["error_code" => "ERROR_NO_SELF_REPORTS"]);
  77. }
  78. $rpid = null;
  79. switch ($object_type) {
  80. case 'post':
  81. $object = Status::find($object_id);
  82. if (!$object) {
  83. return $this->error("Invalid object id", 400, ["error_code" => "ERROR_INVALID_OBJECT_ID"]);
  84. }
  85. $object_type = 'App\Status';
  86. $exists = Report::whereUserId($user->id)
  87. ->whereObjectId($object->id)
  88. ->whereObjectType('App\Status')
  89. ->count();
  90. $rpid = $object->profile_id;
  91. break;
  92. case 'user':
  93. $object = Profile::find($object_id);
  94. if (!$object) {
  95. return $this->error("Invalid object id", 400, ["error_code" => "ERROR_INVALID_OBJECT_ID"]);
  96. }
  97. $object_type = 'App\Profile';
  98. $exists = Report::whereUserId($user->id)
  99. ->whereObjectId($object->id)
  100. ->whereObjectType('App\Profile')
  101. ->count();
  102. $rpid = $object->id;
  103. break;
  104. default:
  105. return $this->error("Invalid report type", 400, ["error_code" => "ERROR_REPORT_OBJECT_TYPE_INVALID"]);
  106. break;
  107. }
  108. if ($exists !== 0) {
  109. return $this->error("Duplicate report", 400, ["error_code" => "ERROR_REPORT_DUPLICATE"]);
  110. }
  111. if ($object->profile_id == $user->profile_id) {
  112. return $this->error("Cannot self report", 400, ["error_code" => "ERROR_NO_SELF_REPORTS"]);
  113. }
  114. $report = new Report;
  115. $report->profile_id = $user->profile_id;
  116. $report->user_id = $user->id;
  117. $report->object_id = $object->id;
  118. $report->object_type = $object_type;
  119. $report->reported_profile_id = $rpid;
  120. $report->type = $report_type;
  121. $report->save();
  122. $res = [
  123. "msg" => "Successfully sent report",
  124. "code" => 200
  125. ];
  126. return $this->json($res);
  127. }
  128. /**
  129. * DELETE /api/v1.1/accounts/avatar
  130. *
  131. * @return \App\Transformer\Api\AccountTransformer
  132. */
  133. public function deleteAvatar(Request $request)
  134. {
  135. $user = $request->user();
  136. abort_if(!$user, 403);
  137. abort_if($user->status != null, 403);
  138. $avatar = $user->profile->avatar;
  139. if( $avatar->media_path == 'public/avatars/default.png' ||
  140. $avatar->media_path == 'public/avatars/default.jpg'
  141. ) {
  142. return AccountService::get($user->profile_id);
  143. }
  144. if(is_file(storage_path('app/' . $avatar->media_path))) {
  145. @unlink(storage_path('app/' . $avatar->media_path));
  146. }
  147. $avatar->media_path = 'public/avatars/default.jpg';
  148. $avatar->change_count = $avatar->change_count + 1;
  149. $avatar->save();
  150. Cache::forget('avatar:' . $user->profile_id);
  151. Cache::forget("avatar:{$user->profile_id}");
  152. Cache::forget('user:account:id:'.$user->id);
  153. AccountService::del($user->profile_id);
  154. return AccountService::get($user->profile_id);
  155. }
  156. /**
  157. * GET /api/v1.1/accounts/{id}/posts
  158. *
  159. * @return \App\Transformer\Api\StatusTransformer
  160. */
  161. public function accountPosts(Request $request, $id)
  162. {
  163. $user = $request->user();
  164. abort_if(!$user, 403);
  165. abort_if($user->status != null, 403);
  166. $account = AccountService::get($id);
  167. if(!$account || $account['username'] !== $request->input('username')) {
  168. return $this->json([]);
  169. }
  170. $posts = ProfileStatusService::get($id);
  171. if(!$posts) {
  172. return $this->json([]);
  173. }
  174. $res = collect($posts)
  175. ->map(function($id) {
  176. return StatusService::get($id);
  177. })
  178. ->filter(function($post) {
  179. return $post && isset($post['account']);
  180. })
  181. ->toArray();
  182. return $this->json($res);
  183. }
  184. /**
  185. * POST /api/v1.1/accounts/change-password
  186. *
  187. * @return \App\Transformer\Api\AccountTransformer
  188. */
  189. public function accountChangePassword(Request $request)
  190. {
  191. $user = $request->user();
  192. abort_if(!$user, 403);
  193. abort_if($user->status != null, 403);
  194. $this->validate($request, [
  195. 'current_password' => 'bail|required|current_password',
  196. 'new_password' => 'required|min:' . config('pixelfed.min_password_length', 8),
  197. 'confirm_password' => 'required|same:new_password'
  198. ],[
  199. 'current_password' => 'The password you entered is incorrect'
  200. ]);
  201. $user->password = bcrypt($request->input('new_password'));
  202. $user->save();
  203. $log = new AccountLog;
  204. $log->user_id = $user->id;
  205. $log->item_id = $user->id;
  206. $log->item_type = 'App\User';
  207. $log->action = 'account.edit.password';
  208. $log->message = 'Password changed';
  209. $log->link = null;
  210. $log->ip_address = $request->ip();
  211. $log->user_agent = $request->userAgent();
  212. $log->save();
  213. Mail::to($request->user())->send(new PasswordChange($user));
  214. return $this->json(AccountService::get($user->profile_id));
  215. }
  216. /**
  217. * GET /api/v1.1/accounts/login-activity
  218. *
  219. * @return array
  220. */
  221. public function accountLoginActivity(Request $request)
  222. {
  223. $user = $request->user();
  224. abort_if(!$user, 403);
  225. abort_if($user->status != null, 403);
  226. $agent = new Agent();
  227. $currentIp = $request->ip();
  228. $activity = AccountLog::whereUserId($user->id)
  229. ->whereAction('auth.login')
  230. ->orderBy('created_at', 'desc')
  231. ->groupBy('ip_address')
  232. ->limit(10)
  233. ->get()
  234. ->map(function($item) use($agent, $currentIp) {
  235. $agent->setUserAgent($item->user_agent);
  236. return [
  237. 'id' => $item->id,
  238. 'action' => $item->action,
  239. 'ip' => $item->ip_address,
  240. 'ip_current' => $item->ip_address === $currentIp,
  241. 'is_mobile' => $agent->isMobile(),
  242. 'device' => $agent->device(),
  243. 'browser' => $agent->browser(),
  244. 'platform' => $agent->platform(),
  245. 'created_at' => $item->created_at->format('c')
  246. ];
  247. });
  248. return $this->json($activity);
  249. }
  250. /**
  251. * GET /api/v1.1/accounts/two-factor
  252. *
  253. * @return array
  254. */
  255. public function accountTwoFactor(Request $request)
  256. {
  257. $user = $request->user();
  258. abort_if(!$user, 403);
  259. abort_if($user->status != null, 403);
  260. $res = [
  261. 'active' => (bool) $user->{'2fa_enabled'},
  262. 'setup_at' => $user->{'2fa_setup_at'}
  263. ];
  264. return $this->json($res);
  265. }
  266. /**
  267. * GET /api/v1.1/accounts/emails-from-pixelfed
  268. *
  269. * @return array
  270. */
  271. public function accountEmailsFromPixelfed(Request $request)
  272. {
  273. $user = $request->user();
  274. abort_if(!$user, 403);
  275. abort_if($user->status != null, 403);
  276. $from = config('mail.from.address');
  277. $emailVerifications = EmailVerification::whereUserId($user->id)
  278. ->orderByDesc('id')
  279. ->where('created_at', '>', now()->subDays(14))
  280. ->limit(10)
  281. ->get()
  282. ->map(function($mail) use($user, $from) {
  283. return [
  284. 'type' => 'Email Verification',
  285. 'subject' => 'Confirm Email',
  286. 'to_address' => $user->email,
  287. 'from_address' => $from,
  288. 'created_at' => str_replace('@', 'at', $mail->created_at->format('M j, Y @ g:i:s A'))
  289. ];
  290. })
  291. ->toArray();
  292. $passwordResets = DB::table('password_resets')
  293. ->whereEmail($user->email)
  294. ->where('created_at', '>', now()->subDays(14))
  295. ->orderByDesc('created_at')
  296. ->limit(10)
  297. ->get()
  298. ->map(function($mail) use($user, $from) {
  299. return [
  300. 'type' => 'Password Reset',
  301. 'subject' => 'Reset Password Notification',
  302. 'to_address' => $user->email,
  303. 'from_address' => $from,
  304. 'created_at' => str_replace('@', 'at', now()->parse($mail->created_at)->format('M j, Y @ g:i:s A'))
  305. ];
  306. })
  307. ->toArray();
  308. $passwordChanges = AccountLog::whereUserId($user->id)
  309. ->whereAction('account.edit.password')
  310. ->where('created_at', '>', now()->subDays(14))
  311. ->orderByDesc('created_at')
  312. ->limit(10)
  313. ->get()
  314. ->map(function($mail) use($user, $from) {
  315. return [
  316. 'type' => 'Password Change',
  317. 'subject' => 'Password Change',
  318. 'to_address' => $user->email,
  319. 'from_address' => $from,
  320. 'created_at' => str_replace('@', 'at', now()->parse($mail->created_at)->format('M j, Y @ g:i:s A'))
  321. ];
  322. })
  323. ->toArray();
  324. $res = collect([])
  325. ->merge($emailVerifications)
  326. ->merge($passwordResets)
  327. ->merge($passwordChanges)
  328. ->sortByDesc('created_at')
  329. ->values();
  330. return $this->json($res);
  331. }
  332. /**
  333. * GET /api/v1.1/accounts/apps-and-applications
  334. *
  335. * @return array
  336. */
  337. public function accountApps(Request $request)
  338. {
  339. $user = $request->user();
  340. abort_if(!$user, 403);
  341. abort_if($user->status != null, 403);
  342. $res = $user->tokens->sortByDesc('created_at')->take(10)->map(function($token, $key) {
  343. return [
  344. 'id' => $key + 1,
  345. 'did' => encrypt($token->id),
  346. 'name' => $token->client->name,
  347. 'scopes' => $token->scopes,
  348. 'revoked' => $token->revoked,
  349. 'created_at' => str_replace('@', 'at', now()->parse($token->created_at)->format('M j, Y @ g:i:s A')),
  350. 'expires_at' => str_replace('@', 'at', now()->parse($token->expires_at)->format('M j, Y @ g:i:s A'))
  351. ];
  352. });
  353. return $this->json($res);
  354. }
  355. public function inAppRegistrationPreFlightCheck(Request $request)
  356. {
  357. return [
  358. 'open' => config('pixelfed.open_registration'),
  359. 'iara' => config('pixelfed.allow_app_registration')
  360. ];
  361. }
  362. public function inAppRegistration(Request $request)
  363. {
  364. abort_if($request->user(), 404);
  365. abort_unless(config('pixelfed.open_registration'), 404);
  366. abort_unless(config('pixelfed.allow_app_registration'), 404);
  367. abort_unless($request->hasHeader('X-PIXELFED-APP'), 403);
  368. $this->validate($request, [
  369. 'email' => [
  370. 'required',
  371. 'string',
  372. 'email',
  373. 'max:255',
  374. 'unique:users',
  375. function ($attribute, $value, $fail) {
  376. $banned = EmailService::isBanned($value);
  377. if($banned) {
  378. return $fail('Email is invalid.');
  379. }
  380. },
  381. ],
  382. 'username' => [
  383. 'required',
  384. 'min:2',
  385. 'max:15',
  386. 'unique:users',
  387. function ($attribute, $value, $fail) {
  388. $dash = substr_count($value, '-');
  389. $underscore = substr_count($value, '_');
  390. $period = substr_count($value, '.');
  391. if(ends_with($value, ['.php', '.js', '.css'])) {
  392. return $fail('Username is invalid.');
  393. }
  394. if(($dash + $underscore + $period) > 1) {
  395. return $fail('Username is invalid. Can only contain one dash (-), period (.) or underscore (_).');
  396. }
  397. if (!ctype_alnum($value[0])) {
  398. return $fail('Username is invalid. Must start with a letter or number.');
  399. }
  400. if (!ctype_alnum($value[strlen($value) - 1])) {
  401. return $fail('Username is invalid. Must end with a letter or number.');
  402. }
  403. $val = str_replace(['_', '.', '-'], '', $value);
  404. if(!ctype_alnum($val)) {
  405. return $fail('Username is invalid. Username must be alpha-numeric and may contain dashes (-), periods (.) and underscores (_).');
  406. }
  407. $restricted = RestrictedNames::get();
  408. if (in_array(strtolower($value), array_map('strtolower', $restricted))) {
  409. return $fail('Username cannot be used.');
  410. }
  411. },
  412. ],
  413. 'password' => 'required|string|min:8',
  414. ]);
  415. $email = $request->input('email');
  416. $username = $request->input('username');
  417. $password = $request->input('password');
  418. if(config('database.default') == 'pgsql') {
  419. $username = strtolower($username);
  420. $email = strtolower($email);
  421. }
  422. $user = new User;
  423. $user->name = $username;
  424. $user->username = $username;
  425. $user->email = $email;
  426. $user->password = Hash::make($password);
  427. $user->register_source = 'app';
  428. $user->app_register_ip = $request->ip();
  429. $user->app_register_token = Str::random(32);
  430. $user->save();
  431. $rtoken = Str::random(mt_rand(64, 70));
  432. $verify = new EmailVerification();
  433. $verify->user_id = $user->id;
  434. $verify->email = $user->email;
  435. $verify->user_token = $user->app_register_token;
  436. $verify->random_token = $rtoken;
  437. $verify->save();
  438. $appUrl = url('/api/v1.1/auth/iarer?ut=' . $user->app_register_token . '&rt=' . $rtoken);
  439. Mail::to($user->email)->send(new ConfirmAppEmail($verify, $appUrl));
  440. return response()->json([
  441. 'success' => true,
  442. ]);
  443. }
  444. public function inAppRegistrationEmailRedirect(Request $request)
  445. {
  446. $this->validate($request, [
  447. 'ut' => 'required',
  448. 'rt' => 'required'
  449. ]);
  450. $ut = $request->input('ut');
  451. $rt = $request->input('rt');
  452. $url = 'pixelfed://confirm-account/'. $ut . '?rt=' . $rt;
  453. return redirect()->away($url);
  454. }
  455. public function inAppRegistrationConfirm(Request $request)
  456. {
  457. abort_if($request->user(), 404);
  458. abort_unless(config('pixelfed.open_registration'), 404);
  459. abort_unless(config('pixelfed.allow_app_registration'), 404);
  460. abort_unless($request->hasHeader('X-PIXELFED-APP'), 403);
  461. $this->validate($request, [
  462. 'user_token' => 'required',
  463. 'random_token' => 'required',
  464. 'email' => 'required'
  465. ]);
  466. $verify = EmailVerification::whereEmail($request->input('email'))
  467. ->whereUserToken($request->input('user_token'))
  468. ->whereRandomToken($request->input('random_token'))
  469. ->first();
  470. if(!$verify) {
  471. return response()->json(['error' => 'Invalid tokens'], 403);
  472. }
  473. if($verify->created_at->lt(now()->subHours(24))) {
  474. $verify->delete();
  475. return response()->json(['error' => 'Invalid tokens'], 403);
  476. }
  477. $user = User::findOrFail($verify->user_id);
  478. $user->email_verified_at = now();
  479. $user->last_active_at = now();
  480. $user->save();
  481. $token = $user->createToken('Pixelfed');
  482. return response()->json([
  483. 'access_token' => $token->accessToken
  484. ]);
  485. }
  486. public function archive(Request $request, $id)
  487. {
  488. abort_if(!$request->user(), 403);
  489. $status = Status::whereNull('in_reply_to_id')
  490. ->whereNull('reblog_of_id')
  491. ->whereProfileId($request->user()->profile_id)
  492. ->findOrFail($id);
  493. if($status->scope === 'archived') {
  494. return [200];
  495. }
  496. $archive = new StatusArchived;
  497. $archive->status_id = $status->id;
  498. $archive->profile_id = $status->profile_id;
  499. $archive->original_scope = $status->scope;
  500. $archive->save();
  501. $status->scope = 'archived';
  502. $status->visibility = 'draft';
  503. $status->save();
  504. StatusService::del($status->id, true);
  505. AccountService::syncPostCount($status->profile_id);
  506. return [200];
  507. }
  508. public function unarchive(Request $request, $id)
  509. {
  510. abort_if(!$request->user(), 403);
  511. $status = Status::whereNull('in_reply_to_id')
  512. ->whereNull('reblog_of_id')
  513. ->whereProfileId($request->user()->profile_id)
  514. ->findOrFail($id);
  515. if($status->scope !== 'archived') {
  516. return [200];
  517. }
  518. $archive = StatusArchived::whereStatusId($status->id)
  519. ->whereProfileId($status->profile_id)
  520. ->firstOrFail();
  521. $status->scope = $archive->original_scope;
  522. $status->visibility = $archive->original_scope;
  523. $status->save();
  524. $archive->delete();
  525. StatusService::del($status->id, true);
  526. AccountService::syncPostCount($status->profile_id);
  527. return [200];
  528. }
  529. public function archivedPosts(Request $request)
  530. {
  531. abort_if(!$request->user(), 403);
  532. $statuses = Status::whereProfileId($request->user()->profile_id)
  533. ->whereScope('archived')
  534. ->orderByDesc('id')
  535. ->cursorPaginate(10);
  536. return StatusStateless::collection($statuses);
  537. }
  538. public function placesById(Request $request, $id, $slug)
  539. {
  540. abort_if(!$request->user(), 403);
  541. $place = Place::whereSlug($slug)->findOrFail($id);
  542. $posts = Cache::remember('pf-api:v1.1:places-by-id:' . $place->id, 3600, function() use($place) {
  543. return Status::wherePlaceId($place->id)
  544. ->whereNull('uri')
  545. ->whereScope('public')
  546. ->orderByDesc('created_at')
  547. ->limit(60)
  548. ->pluck('id');
  549. });
  550. $posts = $posts->map(function($id) {
  551. return StatusService::get($id);
  552. })
  553. ->filter()
  554. ->values();
  555. return ['place' => [
  556. 'id' => $place->id,
  557. 'name' => $place->name,
  558. 'slug' => $place->slug,
  559. 'country' => $place->country,
  560. 'lat' => $place->lat,
  561. 'long' => $place->long
  562. ], 'posts' => $posts];
  563. }
  564. }