ApiV1Dot1Controller.php 20 KB

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