ApiV1Dot1Controller.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\AccountLog;
  4. use App\EmailVerification;
  5. use App\Http\Controllers\Controller;
  6. use App\Http\Resources\StatusStateless;
  7. use App\Jobs\ReportPipeline\ReportNotifyAdminViaEmail;
  8. use App\Jobs\StatusPipeline\RemoteStatusDelete;
  9. use App\Jobs\StatusPipeline\StatusDelete;
  10. use App\Mail\ConfirmAppEmail;
  11. use App\Mail\PasswordChange;
  12. use App\Place;
  13. use App\Profile;
  14. use App\Report;
  15. use App\Services\AccountService;
  16. use App\Services\BouncerService;
  17. use App\Services\EmailService;
  18. use App\Services\FollowerService;
  19. use App\Services\NetworkTimelineService;
  20. use App\Services\ProfileStatusService;
  21. use App\Services\PublicTimelineService;
  22. use App\Services\StatusService;
  23. use App\Status;
  24. use App\StatusArchived;
  25. use App\User;
  26. use App\UserSetting;
  27. use App\Util\Lexer\RestrictedNames;
  28. use Cache;
  29. use DB;
  30. use Illuminate\Http\Request;
  31. use Illuminate\Support\Facades\Hash;
  32. use Illuminate\Support\Facades\RateLimiter;
  33. use Illuminate\Support\Str;
  34. use Jenssegers\Agent\Agent;
  35. use League\Fractal;
  36. use League\Fractal\Serializer\ArraySerializer;
  37. use Mail;
  38. class ApiV1Dot1Controller extends Controller
  39. {
  40. protected $fractal;
  41. public function __construct()
  42. {
  43. $this->fractal = new Fractal\Manager();
  44. $this->fractal->setSerializer(new ArraySerializer());
  45. }
  46. public function json($res, $code = 200, $headers = [])
  47. {
  48. return response()->json($res, $code, $headers, JSON_UNESCAPED_SLASHES);
  49. }
  50. public function error($msg, $code = 400, $extra = [], $headers = [])
  51. {
  52. $res = [
  53. 'msg' => $msg,
  54. 'code' => $code,
  55. ];
  56. return response()->json(array_merge($res, $extra), $code, $headers, JSON_UNESCAPED_SLASHES);
  57. }
  58. public function report(Request $request)
  59. {
  60. abort_if(! $request->user() || ! $request->user()->token(), 403);
  61. abort_unless($request->user()->tokenCan('write'), 403);
  62. $user = $request->user();
  63. abort_if($user->status != null, 403);
  64. if (config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  65. abort_if(BouncerService::checkIp($request->ip()), 404);
  66. }
  67. $report_type = $request->input('report_type');
  68. $object_id = $request->input('object_id');
  69. $object_type = $request->input('object_type');
  70. $types = [
  71. 'spam',
  72. 'sensitive',
  73. 'abusive',
  74. 'underage',
  75. 'violence',
  76. 'copyright',
  77. 'impersonation',
  78. 'scam',
  79. 'terrorism',
  80. ];
  81. if (! $report_type || ! $object_id || ! $object_type) {
  82. return $this->error('Invalid or missing parameters', 400, ['error_code' => 'ERROR_INVALID_PARAMS']);
  83. }
  84. if (! in_array($report_type, $types)) {
  85. return $this->error('Invalid report type', 400, ['error_code' => 'ERROR_TYPE_INVALID']);
  86. }
  87. if ($object_type === 'user' && $object_id == $user->profile_id) {
  88. return $this->error('Cannot self report', 400, ['error_code' => 'ERROR_NO_SELF_REPORTS']);
  89. }
  90. $rpid = null;
  91. switch ($object_type) {
  92. case 'post':
  93. $object = Status::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\Status';
  98. $exists = Report::whereUserId($user->id)
  99. ->whereObjectId($object->id)
  100. ->whereObjectType('App\Status')
  101. ->count();
  102. $rpid = $object->profile_id;
  103. break;
  104. case 'user':
  105. $object = Profile::find($object_id);
  106. if (! $object) {
  107. return $this->error('Invalid object id', 400, ['error_code' => 'ERROR_INVALID_OBJECT_ID']);
  108. }
  109. $object_type = 'App\Profile';
  110. $exists = Report::whereUserId($user->id)
  111. ->whereObjectId($object->id)
  112. ->whereObjectType('App\Profile')
  113. ->count();
  114. $rpid = $object->id;
  115. break;
  116. default:
  117. return $this->error('Invalid report type', 400, ['error_code' => 'ERROR_REPORT_OBJECT_TYPE_INVALID']);
  118. break;
  119. }
  120. if ($exists !== 0) {
  121. return $this->error('Duplicate report', 400, ['error_code' => 'ERROR_REPORT_DUPLICATE']);
  122. }
  123. if ($object->profile_id == $user->profile_id) {
  124. return $this->error('Cannot self report', 400, ['error_code' => 'ERROR_NO_SELF_REPORTS']);
  125. }
  126. $report = new Report;
  127. $report->profile_id = $user->profile_id;
  128. $report->user_id = $user->id;
  129. $report->object_id = $object->id;
  130. $report->object_type = $object_type;
  131. $report->reported_profile_id = $rpid;
  132. $report->type = $report_type;
  133. $report->save();
  134. if (config('instance.reports.email.enabled')) {
  135. ReportNotifyAdminViaEmail::dispatch($report)->onQueue('default');
  136. }
  137. $res = [
  138. 'msg' => 'Successfully sent report',
  139. 'code' => 200,
  140. ];
  141. return $this->json($res);
  142. }
  143. /**
  144. * DELETE /api/v1.1/accounts/avatar
  145. *
  146. * @return \App\Transformer\Api\AccountTransformer
  147. */
  148. public function deleteAvatar(Request $request)
  149. {
  150. abort_if(! $request->user() || ! $request->user()->token(), 403);
  151. abort_unless($request->user()->tokenCan('write'), 403);
  152. $user = $request->user();
  153. abort_if($user->status != null, 403);
  154. if (config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  155. abort_if(BouncerService::checkIp($request->ip()), 404);
  156. }
  157. $avatar = $user->profile->avatar;
  158. if ($avatar->media_path == 'public/avatars/default.png' ||
  159. $avatar->media_path == 'public/avatars/default.jpg'
  160. ) {
  161. return AccountService::get($user->profile_id);
  162. }
  163. if (is_file(storage_path('app/'.$avatar->media_path))) {
  164. @unlink(storage_path('app/'.$avatar->media_path));
  165. }
  166. $avatar->media_path = 'public/avatars/default.jpg';
  167. $avatar->change_count = $avatar->change_count + 1;
  168. $avatar->save();
  169. Cache::forget('avatar:'.$user->profile_id);
  170. Cache::forget("avatar:{$user->profile_id}");
  171. Cache::forget('user:account:id:'.$user->id);
  172. AccountService::del($user->profile_id);
  173. return AccountService::get($user->profile_id);
  174. }
  175. /**
  176. * GET /api/v1.1/accounts/{id}/posts
  177. *
  178. * @return \App\Transformer\Api\StatusTransformer
  179. */
  180. public function accountPosts(Request $request, $id)
  181. {
  182. abort_if(! $request->user() || ! $request->user()->token(), 403);
  183. abort_unless($request->user()->tokenCan('read'), 403);
  184. $user = $request->user();
  185. abort_if($user->status != null, 403);
  186. if (config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  187. abort_if(BouncerService::checkIp($request->ip()), 404);
  188. }
  189. $account = AccountService::get($id);
  190. if (! $account || $account['username'] !== $request->input('username')) {
  191. return $this->json([]);
  192. }
  193. $posts = ProfileStatusService::get($id);
  194. if (! $posts) {
  195. return $this->json([]);
  196. }
  197. $res = collect($posts)
  198. ->map(function ($id) {
  199. return StatusService::get($id);
  200. })
  201. ->filter(function ($post) {
  202. return $post && isset($post['account']);
  203. })
  204. ->toArray();
  205. return $this->json($res);
  206. }
  207. /**
  208. * POST /api/v1.1/accounts/change-password
  209. *
  210. * @return \App\Transformer\Api\AccountTransformer
  211. */
  212. public function accountChangePassword(Request $request)
  213. {
  214. abort_if(! $request->user() || ! $request->user()->token(), 403);
  215. abort_unless($request->user()->tokenCan('write'), 403);
  216. $user = $request->user();
  217. abort_if($user->status != null, 403);
  218. if (config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  219. abort_if(BouncerService::checkIp($request->ip()), 404);
  220. }
  221. $this->validate($request, [
  222. 'current_password' => 'bail|required|current_password',
  223. 'new_password' => 'required|min:'.config('pixelfed.min_password_length', 8),
  224. 'confirm_password' => 'required|same:new_password',
  225. ], [
  226. 'current_password' => 'The password you entered is incorrect',
  227. ]);
  228. $user->password = bcrypt($request->input('new_password'));
  229. $user->save();
  230. $log = new AccountLog;
  231. $log->user_id = $user->id;
  232. $log->item_id = $user->id;
  233. $log->item_type = 'App\User';
  234. $log->action = 'account.edit.password';
  235. $log->message = 'Password changed';
  236. $log->link = null;
  237. $log->ip_address = $request->ip();
  238. $log->user_agent = $request->userAgent();
  239. $log->save();
  240. Mail::to($request->user())->send(new PasswordChange($user));
  241. return $this->json(AccountService::get($user->profile_id));
  242. }
  243. /**
  244. * GET /api/v1.1/accounts/login-activity
  245. *
  246. * @return array
  247. */
  248. public function accountLoginActivity(Request $request)
  249. {
  250. abort_if(! $request->user() || ! $request->user()->token(), 403);
  251. abort_unless($request->user()->tokenCan('read'), 403);
  252. $user = $request->user();
  253. abort_if($user->status != null, 403);
  254. if (config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  255. abort_if(BouncerService::checkIp($request->ip()), 404);
  256. }
  257. $agent = new Agent();
  258. $currentIp = $request->ip();
  259. $activity = AccountLog::whereUserId($user->id)
  260. ->whereAction('auth.login')
  261. ->orderBy('created_at', 'desc')
  262. ->groupBy('ip_address')
  263. ->limit(10)
  264. ->get()
  265. ->map(function ($item) use ($agent, $currentIp) {
  266. $agent->setUserAgent($item->user_agent);
  267. return [
  268. 'id' => $item->id,
  269. 'action' => $item->action,
  270. 'ip' => $item->ip_address,
  271. 'ip_current' => $item->ip_address === $currentIp,
  272. 'is_mobile' => $agent->isMobile(),
  273. 'device' => $agent->device(),
  274. 'browser' => $agent->browser(),
  275. 'platform' => $agent->platform(),
  276. 'created_at' => $item->created_at->format('c'),
  277. ];
  278. });
  279. return $this->json($activity);
  280. }
  281. /**
  282. * GET /api/v1.1/accounts/two-factor
  283. *
  284. * @return array
  285. */
  286. public function accountTwoFactor(Request $request)
  287. {
  288. abort_if(! $request->user() || ! $request->user()->token(), 403);
  289. abort_unless($request->user()->tokenCan('read'), 403);
  290. $user = $request->user();
  291. abort_if($user->status != null, 403);
  292. if (config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  293. abort_if(BouncerService::checkIp($request->ip()), 404);
  294. }
  295. $res = [
  296. 'active' => (bool) $user->{'2fa_enabled'},
  297. 'setup_at' => $user->{'2fa_setup_at'},
  298. ];
  299. return $this->json($res);
  300. }
  301. /**
  302. * GET /api/v1.1/accounts/emails-from-pixelfed
  303. *
  304. * @return array
  305. */
  306. public function accountEmailsFromPixelfed(Request $request)
  307. {
  308. abort_if(! $request->user() || ! $request->user()->token(), 403);
  309. abort_unless($request->user()->tokenCan('read'), 403);
  310. $user = $request->user();
  311. abort_if($user->status != null, 403);
  312. if (config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  313. abort_if(BouncerService::checkIp($request->ip()), 404);
  314. }
  315. $from = config('mail.from.address');
  316. $emailVerifications = EmailVerification::whereUserId($user->id)
  317. ->orderByDesc('id')
  318. ->where('created_at', '>', now()->subDays(14))
  319. ->limit(10)
  320. ->get()
  321. ->map(function ($mail) use ($user, $from) {
  322. return [
  323. 'type' => 'Email Verification',
  324. 'subject' => 'Confirm Email',
  325. 'to_address' => $user->email,
  326. 'from_address' => $from,
  327. 'created_at' => str_replace('@', 'at', $mail->created_at->format('M j, Y @ g:i:s A')),
  328. ];
  329. })
  330. ->toArray();
  331. $passwordResets = DB::table('password_resets')
  332. ->whereEmail($user->email)
  333. ->where('created_at', '>', now()->subDays(14))
  334. ->orderByDesc('created_at')
  335. ->limit(10)
  336. ->get()
  337. ->map(function ($mail) use ($user, $from) {
  338. return [
  339. 'type' => 'Password Reset',
  340. 'subject' => 'Reset Password Notification',
  341. 'to_address' => $user->email,
  342. 'from_address' => $from,
  343. 'created_at' => str_replace('@', 'at', now()->parse($mail->created_at)->format('M j, Y @ g:i:s A')),
  344. ];
  345. })
  346. ->toArray();
  347. $passwordChanges = AccountLog::whereUserId($user->id)
  348. ->whereAction('account.edit.password')
  349. ->where('created_at', '>', now()->subDays(14))
  350. ->orderByDesc('created_at')
  351. ->limit(10)
  352. ->get()
  353. ->map(function ($mail) use ($user, $from) {
  354. return [
  355. 'type' => 'Password Change',
  356. 'subject' => 'Password Change',
  357. 'to_address' => $user->email,
  358. 'from_address' => $from,
  359. 'created_at' => str_replace('@', 'at', now()->parse($mail->created_at)->format('M j, Y @ g:i:s A')),
  360. ];
  361. })
  362. ->toArray();
  363. $res = collect([])
  364. ->merge($emailVerifications)
  365. ->merge($passwordResets)
  366. ->merge($passwordChanges)
  367. ->sortByDesc('created_at')
  368. ->values();
  369. return $this->json($res);
  370. }
  371. /**
  372. * GET /api/v1.1/accounts/apps-and-applications
  373. *
  374. * @return array
  375. */
  376. public function accountApps(Request $request)
  377. {
  378. abort_if(! $request->user() || ! $request->user()->token(), 403);
  379. abort_unless($request->user()->tokenCan('read'), 403);
  380. $user = $request->user();
  381. abort_if($user->status != null, 403);
  382. if (config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  383. abort_if(BouncerService::checkIp($request->ip()), 404);
  384. }
  385. $res = $user->tokens->sortByDesc('created_at')->take(10)->map(function ($token, $key) use ($request) {
  386. return [
  387. 'id' => $token->id,
  388. 'current_session' => $request->user()->token()->id == $token->id,
  389. 'name' => $token->client->name,
  390. 'scopes' => $token->scopes,
  391. 'revoked' => $token->revoked,
  392. 'created_at' => str_replace('@', 'at', now()->parse($token->created_at)->format('M j, Y @ g:i:s A')),
  393. 'expires_at' => str_replace('@', 'at', now()->parse($token->expires_at)->format('M j, Y @ g:i:s A')),
  394. ];
  395. });
  396. return $this->json($res);
  397. }
  398. public function inAppRegistrationPreFlightCheck(Request $request)
  399. {
  400. return [
  401. 'open' => (bool) config_cache('pixelfed.open_registration'),
  402. 'iara' => (bool) config_cache('pixelfed.allow_app_registration'),
  403. ];
  404. }
  405. public function inAppRegistration(Request $request)
  406. {
  407. abort_if($request->user(), 404);
  408. abort_unless((bool) config_cache('pixelfed.open_registration'), 404);
  409. abort_unless((bool) config_cache('pixelfed.allow_app_registration'), 404);
  410. abort_unless($request->hasHeader('X-PIXELFED-APP'), 403);
  411. if (config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  412. abort_if(BouncerService::checkIp($request->ip()), 404);
  413. }
  414. $rl = RateLimiter::attempt('pf:apiv1.1:iar:'.$request->ip(), config('pixelfed.app_registration_rate_limit_attempts', 3), function () {}, config('pixelfed.app_registration_rate_limit_decay', 1800));
  415. abort_if(! $rl, 400, 'Too many requests');
  416. $this->validate($request, [
  417. 'email' => [
  418. 'required',
  419. 'string',
  420. 'email',
  421. 'max:255',
  422. 'unique:users',
  423. function ($attribute, $value, $fail) {
  424. $banned = EmailService::isBanned($value);
  425. if ($banned) {
  426. return $fail('Email is invalid.');
  427. }
  428. },
  429. ],
  430. 'username' => [
  431. 'required',
  432. 'min:2',
  433. 'max:15',
  434. 'unique:users',
  435. function ($attribute, $value, $fail) {
  436. $dash = substr_count($value, '-');
  437. $underscore = substr_count($value, '_');
  438. $period = substr_count($value, '.');
  439. if (ends_with($value, ['.php', '.js', '.css'])) {
  440. return $fail('Username is invalid.');
  441. }
  442. if (($dash + $underscore + $period) > 1) {
  443. return $fail('Username is invalid. Can only contain one dash (-), period (.) or underscore (_).');
  444. }
  445. if (! ctype_alnum($value[0])) {
  446. return $fail('Username is invalid. Must start with a letter or number.');
  447. }
  448. if (! ctype_alnum($value[strlen($value) - 1])) {
  449. return $fail('Username is invalid. Must end with a letter or number.');
  450. }
  451. $val = str_replace(['_', '.', '-'], '', $value);
  452. if (! ctype_alnum($val)) {
  453. return $fail('Username is invalid. Username must be alpha-numeric and may contain dashes (-), periods (.) and underscores (_).');
  454. }
  455. $restricted = RestrictedNames::get();
  456. if (in_array(strtolower($value), array_map('strtolower', $restricted))) {
  457. return $fail('Username cannot be used.');
  458. }
  459. },
  460. ],
  461. 'password' => 'required|string|min:8',
  462. ]);
  463. $email = $request->input('email');
  464. $username = $request->input('username');
  465. $password = $request->input('password');
  466. if (config('database.default') == 'pgsql') {
  467. $username = strtolower($username);
  468. $email = strtolower($email);
  469. }
  470. $user = new User;
  471. $user->name = $username;
  472. $user->username = $username;
  473. $user->email = $email;
  474. $user->password = Hash::make($password);
  475. $user->register_source = 'app';
  476. $user->app_register_ip = $request->ip();
  477. $user->app_register_token = Str::random(40);
  478. $user->save();
  479. $rtoken = Str::random(64);
  480. $verify = new EmailVerification();
  481. $verify->user_id = $user->id;
  482. $verify->email = $user->email;
  483. $verify->user_token = $user->app_register_token;
  484. $verify->random_token = $rtoken;
  485. $verify->save();
  486. $params = http_build_query([
  487. 'ut' => $user->app_register_token,
  488. 'rt' => $rtoken,
  489. 'ea' => base64_encode($user->email),
  490. ]);
  491. $appUrl = url('/api/v1.1/auth/iarer?'.$params);
  492. Mail::to($user->email)->send(new ConfirmAppEmail($verify, $appUrl));
  493. return response()->json([
  494. 'success' => true,
  495. ]);
  496. }
  497. public function inAppRegistrationEmailRedirect(Request $request)
  498. {
  499. $this->validate($request, [
  500. 'ut' => 'required',
  501. 'rt' => 'required',
  502. 'ea' => 'required',
  503. ]);
  504. $ut = $request->input('ut');
  505. $rt = $request->input('rt');
  506. $ea = $request->input('ea');
  507. $params = http_build_query([
  508. 'ut' => $ut,
  509. 'rt' => $rt,
  510. 'domain' => config('pixelfed.domain.app'),
  511. 'ea' => $ea,
  512. ]);
  513. $url = 'pixelfed://confirm-account/'.$ut.'?'.$params;
  514. return redirect()->away($url);
  515. }
  516. public function inAppRegistrationConfirm(Request $request)
  517. {
  518. abort_if($request->user(), 404);
  519. abort_unless((bool) config_cache('pixelfed.open_registration'), 404);
  520. abort_unless((bool) config_cache('pixelfed.allow_app_registration'), 404);
  521. abort_unless($request->hasHeader('X-PIXELFED-APP'), 403);
  522. if (config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  523. abort_if(BouncerService::checkIp($request->ip()), 404);
  524. }
  525. $rl = RateLimiter::attempt('pf:apiv1.1:iarc:'.$request->ip(), config('pixelfed.app_registration_confirm_rate_limit_attempts', 20), function () {}, config('pixelfed.app_registration_confirm_rate_limit_decay', 1800));
  526. abort_if(! $rl, 429, 'Too many requests');
  527. $request->validate([
  528. 'user_token' => 'required',
  529. 'random_token' => 'required',
  530. 'email' => 'required',
  531. ]);
  532. $verify = EmailVerification::whereEmail($request->input('email'))
  533. ->whereUserToken($request->input('user_token'))
  534. ->whereRandomToken($request->input('random_token'))
  535. ->first();
  536. if (! $verify) {
  537. return response()->json(['error' => 'Invalid tokens'], 403);
  538. }
  539. if ($verify->created_at->lt(now()->subHours(24))) {
  540. $verify->delete();
  541. return response()->json(['error' => 'Invalid tokens'], 403);
  542. }
  543. $user = User::findOrFail($verify->user_id);
  544. $user->email_verified_at = now();
  545. $user->last_active_at = now();
  546. $user->save();
  547. $token = $user->createToken('Pixelfed', ['read', 'write', 'follow', 'admin:read', 'admin:write', 'push']);
  548. return response()->json([
  549. 'access_token' => $token->accessToken,
  550. ]);
  551. }
  552. public function archive(Request $request, $id)
  553. {
  554. abort_if(! $request->user() || ! $request->user()->token(), 403);
  555. abort_unless($request->user()->tokenCan('write'), 403);
  556. if (config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  557. abort_if(BouncerService::checkIp($request->ip()), 404);
  558. }
  559. $status = Status::whereNull('in_reply_to_id')
  560. ->whereNull('reblog_of_id')
  561. ->whereProfileId($request->user()->profile_id)
  562. ->findOrFail($id);
  563. if ($status->scope === 'archived') {
  564. return [200];
  565. }
  566. $archive = new StatusArchived;
  567. $archive->status_id = $status->id;
  568. $archive->profile_id = $status->profile_id;
  569. $archive->original_scope = $status->scope;
  570. $archive->save();
  571. $status->scope = 'archived';
  572. $status->visibility = 'draft';
  573. $status->save();
  574. StatusService::del($status->id, true);
  575. AccountService::syncPostCount($status->profile_id);
  576. return [200];
  577. }
  578. public function unarchive(Request $request, $id)
  579. {
  580. abort_if(! $request->user() || ! $request->user()->token(), 403);
  581. abort_unless($request->user()->tokenCan('write'), 403);
  582. if (config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  583. abort_if(BouncerService::checkIp($request->ip()), 404);
  584. }
  585. $status = Status::whereNull('in_reply_to_id')
  586. ->whereNull('reblog_of_id')
  587. ->whereProfileId($request->user()->profile_id)
  588. ->findOrFail($id);
  589. if ($status->scope !== 'archived') {
  590. return [200];
  591. }
  592. $archive = StatusArchived::whereStatusId($status->id)
  593. ->whereProfileId($status->profile_id)
  594. ->firstOrFail();
  595. $status->scope = $archive->original_scope;
  596. $status->visibility = $archive->original_scope;
  597. $status->save();
  598. $archive->delete();
  599. StatusService::del($status->id, true);
  600. AccountService::syncPostCount($status->profile_id);
  601. return [200];
  602. }
  603. public function archivedPosts(Request $request)
  604. {
  605. abort_if(! $request->user() || ! $request->user()->token(), 403);
  606. abort_unless($request->user()->tokenCan('read'), 403);
  607. if (config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  608. abort_if(BouncerService::checkIp($request->ip()), 404);
  609. }
  610. $statuses = Status::whereProfileId($request->user()->profile_id)
  611. ->whereScope('archived')
  612. ->orderByDesc('id')
  613. ->cursorPaginate(10);
  614. return StatusStateless::collection($statuses);
  615. }
  616. public function placesById(Request $request, $id, $slug)
  617. {
  618. abort_if(! $request->user() || ! $request->user()->token(), 403);
  619. abort_unless($request->user()->tokenCan('read'), 403);
  620. if (config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  621. abort_if(BouncerService::checkIp($request->ip()), 404);
  622. }
  623. $place = Place::whereSlug($slug)->findOrFail($id);
  624. $posts = Cache::remember('pf-api:v1.1:places-by-id:'.$place->id, 3600, function () use ($place) {
  625. return Status::wherePlaceId($place->id)
  626. ->whereNull('uri')
  627. ->whereScope('public')
  628. ->orderByDesc('created_at')
  629. ->limit(60)
  630. ->pluck('id');
  631. });
  632. $posts = $posts->map(function ($id) {
  633. return StatusService::get($id);
  634. })
  635. ->filter()
  636. ->values();
  637. return [
  638. 'place' => [
  639. 'id' => $place->id,
  640. 'name' => $place->name,
  641. 'slug' => $place->slug,
  642. 'country' => $place->country,
  643. 'lat' => $place->lat,
  644. 'long' => $place->long,
  645. ],
  646. 'posts' => $posts];
  647. }
  648. public function moderatePost(Request $request, $id)
  649. {
  650. abort_if(! $request->user() || ! $request->user()->token(), 403);
  651. abort_if($request->user()->is_admin != true, 403);
  652. abort_unless($request->user()->tokenCan('admin:write'), 403);
  653. if (config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  654. abort_if(BouncerService::checkIp($request->ip()), 404);
  655. }
  656. $this->validate($request, [
  657. 'action' => 'required|in:cw,mark-public,mark-unlisted,mark-private,mark-spammer,delete',
  658. ]);
  659. $action = $request->input('action');
  660. $status = Status::find($id);
  661. if (! $status) {
  662. return response()->json(['error' => 'Cannot find status'], 400);
  663. }
  664. if ($status->uri == null) {
  665. if ($status->profile->user && $status->profile->user->is_admin) {
  666. return response()->json(['error' => 'Cannot moderate admin accounts'], 400);
  667. }
  668. }
  669. if ($action == 'mark-spammer') {
  670. $status->profile->update([
  671. 'unlisted' => true,
  672. 'cw' => true,
  673. 'no_autolink' => true,
  674. ]);
  675. Status::whereProfileId($status->profile_id)
  676. ->get()
  677. ->each(function ($s) {
  678. if (in_array($s->scope, ['public', 'unlisted'])) {
  679. $s->scope = 'private';
  680. $s->visibility = 'private';
  681. }
  682. $s->is_nsfw = true;
  683. $s->save();
  684. StatusService::del($s->id, true);
  685. });
  686. Cache::forget('pf:bouncer_v0:exemption_by_pid:'.$status->profile_id);
  687. Cache::forget('pf:bouncer_v0:recent_by_pid:'.$status->profile_id);
  688. Cache::forget('admin-dash:reports:spam-count');
  689. } elseif ($action == 'cw') {
  690. $state = $status->is_nsfw;
  691. $status->is_nsfw = ! $state;
  692. $status->save();
  693. StatusService::del($status->id);
  694. } elseif ($action == 'mark-public') {
  695. $state = $status->scope;
  696. $status->scope = 'public';
  697. $status->visibility = 'public';
  698. $status->save();
  699. StatusService::del($status->id, true);
  700. if ($state !== 'public') {
  701. if ($status->uri) {
  702. if ($status->in_reply_to_id == null && $status->reblog_of_id == null) {
  703. NetworkTimelineService::add($status->id);
  704. }
  705. } else {
  706. if ($status->in_reply_to_id == null && $status->reblog_of_id == null) {
  707. PublicTimelineService::add($status->id);
  708. }
  709. }
  710. }
  711. } elseif ($action == 'mark-unlisted') {
  712. $state = $status->scope;
  713. $status->scope = 'unlisted';
  714. $status->visibility = 'unlisted';
  715. $status->save();
  716. StatusService::del($status->id);
  717. if ($state == 'public') {
  718. PublicTimelineService::del($status->id);
  719. NetworkTimelineService::del($status->id);
  720. }
  721. } elseif ($action == 'mark-private') {
  722. $state = $status->scope;
  723. $status->scope = 'private';
  724. $status->visibility = 'private';
  725. $status->save();
  726. StatusService::del($status->id);
  727. if ($state == 'public') {
  728. PublicTimelineService::del($status->id);
  729. NetworkTimelineService::del($status->id);
  730. }
  731. } elseif ($action == 'delete') {
  732. PublicTimelineService::del($status->id);
  733. NetworkTimelineService::del($status->id);
  734. Cache::forget('_api:statuses:recent_9:'.$status->profile_id);
  735. Cache::forget('profile:status_count:'.$status->profile_id);
  736. Cache::forget('profile:embed:'.$status->profile_id);
  737. StatusService::del($status->id, true);
  738. Cache::forget('profile:status_count:'.$status->profile_id);
  739. $status->uri ? RemoteStatusDelete::dispatch($status) : StatusDelete::dispatch($status);
  740. return [];
  741. }
  742. Cache::forget('_api:statuses:recent_9:'.$status->profile_id);
  743. return StatusService::get($status->id, false);
  744. }
  745. public function getWebSettings(Request $request)
  746. {
  747. abort_if(! $request->user() || ! $request->user()->token(), 403);
  748. abort_unless($request->user()->tokenCan('read'), 403);
  749. $uid = $request->user()->id;
  750. $settings = UserSetting::firstOrCreate([
  751. 'user_id' => $uid,
  752. ]);
  753. if (! $settings->other) {
  754. return [];
  755. }
  756. return $settings->other;
  757. }
  758. public function setWebSettings(Request $request)
  759. {
  760. abort_if(! $request->user() || ! $request->user()->token(), 403);
  761. abort_unless($request->user()->tokenCan('write'), 403);
  762. $this->validate($request, [
  763. 'field' => 'required|in:enable_reblogs,hide_reblog_banner',
  764. 'value' => 'required',
  765. ]);
  766. $field = $request->input('field');
  767. $value = $request->input('value');
  768. $settings = UserSetting::firstOrCreate([
  769. 'user_id' => $request->user()->id,
  770. ]);
  771. if (! $settings->other) {
  772. $other = [];
  773. } else {
  774. $other = $settings->other;
  775. }
  776. $other[$field] = $value;
  777. $settings->other = $other;
  778. $settings->save();
  779. return [200];
  780. }
  781. public function getMutualAccounts(Request $request, $id)
  782. {
  783. abort_if(! $request->user() || ! $request->user()->token(), 403);
  784. abort_unless($request->user()->tokenCan('follow'), 403);
  785. $account = AccountService::get($id, true);
  786. if (! $account || ! isset($account['id'])) {
  787. return [];
  788. }
  789. $res = collect(FollowerService::mutualAccounts($request->user()->profile_id, $id))
  790. ->map(function ($accountId) {
  791. return AccountService::get($accountId, true);
  792. })
  793. ->filter()
  794. ->take(24)
  795. ->values();
  796. return $this->json($res);
  797. }
  798. public function accountUsernameToId(Request $request, $username)
  799. {
  800. abort_if(! $request->user() || ! $request->user()->token() || ! $username, 403);
  801. abort_unless($request->user()->tokenCan('read'), 403);
  802. $username = trim($username);
  803. $rateLimiting = (bool) config_cache('api.rate-limits.v1Dot1.accounts.usernameToId.enabled');
  804. $ipRateLimiting = (bool) config_cache('api.rate-limits.v1Dot1.accounts.usernameToId.ip_enabled');
  805. if ($ipRateLimiting) {
  806. $userLimit = (int) config_cache('api.rate-limits.v1Dot1.accounts.usernameToId.ip_limit');
  807. $userDecay = (int) config_cache('api.rate-limits.v1Dot1.accounts.usernameToId.ip_decay');
  808. $userKey = 'pf:apiv1.1:acctU2ID:byIp:'.$request->ip();
  809. if (RateLimiter::tooManyAttempts($userKey, $userLimit)) {
  810. $limits = [
  811. 'X-Rate-Limit-Limit' => $userLimit,
  812. 'X-Rate-Limit-Remaining' => RateLimiter::remaining($userKey, $userLimit),
  813. 'X-Rate-Limit-Reset' => RateLimiter::availableIn($userKey),
  814. ];
  815. return $this->json(['error' => 'Too many attempts!'], 429, $limits);
  816. }
  817. RateLimiter::increment($userKey, $userDecay);
  818. $limits = [
  819. 'X-Rate-Limit-Limit' => $userLimit,
  820. 'X-Rate-Limit-Remaining' => RateLimiter::remaining($userKey, $userLimit),
  821. 'X-Rate-Limit-Reset' => RateLimiter::availableIn($userKey),
  822. ];
  823. }
  824. if ($rateLimiting) {
  825. $userLimit = (int) config_cache('api.rate-limits.v1Dot1.accounts.usernameToId.limit');
  826. $userDecay = (int) config_cache('api.rate-limits.v1Dot1.accounts.usernameToId.decay');
  827. $userKey = 'pf:apiv1.1:acctU2ID:byUid:'.$request->user()->id;
  828. if (RateLimiter::tooManyAttempts($userKey, $userLimit)) {
  829. $limits = [
  830. 'X-Rate-Limit-Limit' => $userLimit,
  831. 'X-Rate-Limit-Remaining' => RateLimiter::remaining($userKey, $userLimit),
  832. 'X-Rate-Limit-Reset' => RateLimiter::availableIn($userKey),
  833. ];
  834. return $this->json(['error' => 'Too many attempts!'], 429, $limits);
  835. }
  836. RateLimiter::increment($userKey, $userDecay);
  837. $limits = [
  838. 'X-Rate-Limit-Limit' => $userLimit,
  839. 'X-Rate-Limit-Remaining' => RateLimiter::remaining($userKey, $userLimit),
  840. 'X-Rate-Limit-Reset' => RateLimiter::availableIn($userKey),
  841. ];
  842. }
  843. if (str_ends_with($username, config_cache('pixelfed.domain.app'))) {
  844. $pre = str_starts_with($username, '@') ? substr($username, 1) : $username;
  845. $parts = explode('@', $pre);
  846. $username = $parts[0];
  847. }
  848. $accountId = AccountService::usernameToId($username, true);
  849. if (! $accountId) {
  850. return [];
  851. }
  852. $account = AccountService::get($accountId);
  853. return $this->json($account, 200, $rateLimiting ? $limits : []);
  854. }
  855. }