AccountController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\EmailVerification;
  4. use App\Follower;
  5. use App\FollowRequest;
  6. use App\Jobs\FollowPipeline\FollowAcceptPipeline;
  7. use App\Jobs\FollowPipeline\FollowPipeline;
  8. use App\Jobs\FollowPipeline\FollowRejectPipeline;
  9. use App\Mail\ConfirmEmail;
  10. use App\Notification;
  11. use App\Profile;
  12. use App\Services\AccountService;
  13. use App\Services\FollowerService;
  14. use App\Services\NotificationService;
  15. use App\Services\RelationshipService;
  16. use App\Services\UserFilterService;
  17. use App\Transformer\Api\Mastodon\v1\AccountTransformer;
  18. use App\User;
  19. use App\UserFilter;
  20. use Auth;
  21. use Cache;
  22. use Carbon\Carbon;
  23. use Illuminate\Http\Request;
  24. use Illuminate\Support\Str;
  25. use League\Fractal;
  26. use League\Fractal\Serializer\ArraySerializer;
  27. use Mail;
  28. use PragmaRX\Google2FA\Google2FA;
  29. class AccountController extends Controller
  30. {
  31. protected $filters = [
  32. 'user.mute',
  33. 'user.block',
  34. ];
  35. const FILTER_LIMIT_MUTE_TEXT = 'You cannot mute more than ';
  36. const FILTER_LIMIT_BLOCK_TEXT = 'You cannot block more than ';
  37. public function __construct()
  38. {
  39. $this->middleware('auth');
  40. }
  41. public function notifications(Request $request)
  42. {
  43. return view('account.activity');
  44. }
  45. public function followingActivity(Request $request)
  46. {
  47. $this->validate($request, [
  48. 'page' => 'nullable|min:1|max:3',
  49. 'a' => 'nullable|alpha_dash',
  50. ]);
  51. $action = $request->input('a');
  52. $allowed = ['like', 'follow'];
  53. $timeago = Carbon::now()->subMonths(3);
  54. $profile = Auth::user()->profile;
  55. $following = $profile->following->pluck('id');
  56. $notifications = Notification::whereIn('actor_id', $following)
  57. ->whereIn('action', $allowed)
  58. ->where('actor_id', '<>', $profile->id)
  59. ->where('profile_id', '<>', $profile->id)
  60. ->whereDate('created_at', '>', $timeago)
  61. ->orderBy('notifications.created_at', 'desc')
  62. ->simplePaginate(30);
  63. return view('account.following', compact('profile', 'notifications'));
  64. }
  65. public function verifyEmail(Request $request)
  66. {
  67. $recentSent = EmailVerification::whereUserId(Auth::id())
  68. ->whereDate('created_at', '>', now()->subHours(12))->count();
  69. return view('account.verify_email', compact('recentSent'));
  70. }
  71. public function sendVerifyEmail(Request $request)
  72. {
  73. $recentAttempt = EmailVerification::whereUserId(Auth::id())
  74. ->whereDate('created_at', '>', now()->subHours(12))->count();
  75. if ($recentAttempt > 0) {
  76. return redirect()->back()->with('error', 'A verification email has already been sent recently. Please check your email, or try again later.');
  77. }
  78. EmailVerification::whereUserId(Auth::id())->delete();
  79. $user = User::whereNull('email_verified_at')->find(Auth::id());
  80. $utoken = Str::uuid().Str::random(mt_rand(5, 9));
  81. $rtoken = Str::random(mt_rand(64, 70));
  82. $verify = new EmailVerification;
  83. $verify->user_id = $user->id;
  84. $verify->email = $user->email;
  85. $verify->user_token = $utoken;
  86. $verify->random_token = $rtoken;
  87. $verify->save();
  88. Mail::to($user->email)->send(new ConfirmEmail($verify));
  89. return redirect()->back()->with('status', 'Verification email sent!');
  90. }
  91. public function confirmVerifyEmail(Request $request, $userToken, $randomToken)
  92. {
  93. $verify = EmailVerification::where('user_token', $userToken)
  94. ->where('created_at', '>', now()->subHours(24))
  95. ->where('random_token', $randomToken)
  96. ->firstOrFail();
  97. if (Auth::id() === $verify->user_id && $verify->user_token === $userToken && $verify->random_token === $randomToken) {
  98. $user = User::find(Auth::id());
  99. $user->email_verified_at = Carbon::now();
  100. $user->save();
  101. return redirect('/');
  102. } else {
  103. abort(403);
  104. }
  105. }
  106. public function direct()
  107. {
  108. return view('account.direct');
  109. }
  110. public function directMessage(Request $request, $id)
  111. {
  112. $profile = Profile::where('id', '!=', $request->user()->profile_id)
  113. ->findOrFail($id);
  114. return view('account.directmessage', compact('id'));
  115. }
  116. public function mute(Request $request)
  117. {
  118. $this->validate($request, [
  119. 'type' => 'required|string|in:user',
  120. 'item' => 'required|integer|min:1',
  121. ]);
  122. $pid = $request->user()->profile_id;
  123. $count = UserFilterService::muteCount($pid);
  124. $maxLimit = (int) config_cache('instance.user_filters.max_user_mutes');
  125. abort_if($count >= $maxLimit, 422, self::FILTER_LIMIT_MUTE_TEXT.$maxLimit.' accounts');
  126. if ($count == 0) {
  127. $filterCount = UserFilter::whereUserId($pid)->count();
  128. abort_if($filterCount >= $maxLimit, 422, self::FILTER_LIMIT_MUTE_TEXT.$maxLimit.' accounts');
  129. }
  130. $type = $request->input('type');
  131. $item = $request->input('item');
  132. $action = $type.'.mute';
  133. if (! in_array($action, $this->filters)) {
  134. return abort(406);
  135. }
  136. $filterable = [];
  137. switch ($type) {
  138. case 'user':
  139. $profile = Profile::findOrFail($item);
  140. if ($profile->id == $pid) {
  141. return abort(403);
  142. }
  143. $class = get_class($profile);
  144. $filterable['id'] = $profile->id;
  145. $filterable['type'] = $class;
  146. break;
  147. }
  148. $filter = UserFilter::firstOrCreate([
  149. 'user_id' => $pid,
  150. 'filterable_id' => $filterable['id'],
  151. 'filterable_type' => $filterable['type'],
  152. 'filter_type' => 'mute',
  153. ]);
  154. UserFilterService::mute($pid, $filterable['id']);
  155. $res = RelationshipService::refresh($pid, $profile->id);
  156. if ($request->wantsJson()) {
  157. return response()->json($res);
  158. } else {
  159. return redirect()->back();
  160. }
  161. }
  162. public function unmute(Request $request)
  163. {
  164. $this->validate($request, [
  165. 'type' => 'required|string|in:user',
  166. 'item' => 'required|integer|min:1',
  167. ]);
  168. $pid = $request->user()->profile_id;
  169. $type = $request->input('type');
  170. $item = $request->input('item');
  171. $action = $type.'.mute';
  172. if (! in_array($action, $this->filters)) {
  173. return abort(406);
  174. }
  175. $filterable = [];
  176. switch ($type) {
  177. case 'user':
  178. $profile = Profile::findOrFail($item);
  179. if ($profile->id == $pid) {
  180. return abort(403);
  181. }
  182. $class = get_class($profile);
  183. $filterable['id'] = $profile->id;
  184. $filterable['type'] = $class;
  185. break;
  186. default:
  187. abort(400);
  188. break;
  189. }
  190. $filter = UserFilter::whereUserId($pid)
  191. ->whereFilterableId($filterable['id'])
  192. ->whereFilterableType($filterable['type'])
  193. ->whereFilterType('mute')
  194. ->first();
  195. if ($filter) {
  196. UserFilterService::unmute($pid, $filterable['id']);
  197. $filter->delete();
  198. }
  199. $res = RelationshipService::refresh($pid, $profile->id);
  200. if ($request->wantsJson()) {
  201. return response()->json($res);
  202. } else {
  203. return redirect()->back();
  204. }
  205. }
  206. public function block(Request $request)
  207. {
  208. $this->validate($request, [
  209. 'type' => 'required|string|in:user',
  210. 'item' => 'required|integer|min:1',
  211. ]);
  212. $pid = $request->user()->profile_id;
  213. $count = UserFilterService::blockCount($pid);
  214. $maxLimit = (int) config_cache('instance.user_filters.max_user_blocks');
  215. abort_if($count >= $maxLimit, 422, self::FILTER_LIMIT_BLOCK_TEXT.$maxLimit.' accounts');
  216. if ($count == 0) {
  217. $filterCount = UserFilter::whereUserId($pid)->whereFilterType('block')->count();
  218. abort_if($filterCount >= $maxLimit, 422, self::FILTER_LIMIT_BLOCK_TEXT.$maxLimit.' accounts');
  219. }
  220. $type = $request->input('type');
  221. $item = $request->input('item');
  222. $action = $type.'.block';
  223. if (! in_array($action, $this->filters)) {
  224. return abort(406);
  225. }
  226. $filterable = [];
  227. switch ($type) {
  228. case 'user':
  229. $profile = Profile::findOrFail($item);
  230. if ($profile->id == $pid || ($profile->user && $profile->user->is_admin == true)) {
  231. return abort(403);
  232. }
  233. $class = get_class($profile);
  234. $filterable['id'] = $profile->id;
  235. $filterable['type'] = $class;
  236. $followed = Follower::whereProfileId($profile->id)->whereFollowingId($pid)->first();
  237. if ($followed) {
  238. $followed->delete();
  239. $profile->following_count = Follower::whereProfileId($profile->id)->count();
  240. $profile->save();
  241. $selfProfile = $request->user()->profile;
  242. $selfProfile->followers_count = Follower::whereFollowingId($pid)->count();
  243. $selfProfile->save();
  244. FollowerService::remove($profile->id, $pid);
  245. AccountService::del($pid);
  246. AccountService::del($profile->id);
  247. }
  248. $following = Follower::whereProfileId($pid)->whereFollowingId($profile->id)->first();
  249. if ($following) {
  250. $following->delete();
  251. $profile->followers_count = Follower::whereFollowingId($profile->id)->count();
  252. $profile->save();
  253. $selfProfile = $request->user()->profile;
  254. $selfProfile->following_count = Follower::whereProfileId($pid)->count();
  255. $selfProfile->save();
  256. FollowerService::remove($pid, $profile->pid);
  257. AccountService::del($pid);
  258. AccountService::del($profile->id);
  259. }
  260. Notification::whereProfileId($pid)
  261. ->whereActorId($profile->id)
  262. ->get()
  263. ->map(function ($n) use ($pid) {
  264. NotificationService::del($pid, $n['id']);
  265. $n->forceDelete();
  266. });
  267. break;
  268. }
  269. $filter = UserFilter::firstOrCreate([
  270. 'user_id' => $pid,
  271. 'filterable_id' => $filterable['id'],
  272. 'filterable_type' => $filterable['type'],
  273. 'filter_type' => 'block',
  274. ]);
  275. UserFilterService::block($pid, $filterable['id']);
  276. $res = RelationshipService::refresh($pid, $profile->id);
  277. if ($request->wantsJson()) {
  278. return response()->json($res);
  279. } else {
  280. return redirect()->back();
  281. }
  282. }
  283. public function unblock(Request $request)
  284. {
  285. $this->validate($request, [
  286. 'type' => 'required|string|in:user',
  287. 'item' => 'required|integer|min:1',
  288. ]);
  289. $pid = $request->user()->profile_id;
  290. $type = $request->input('type');
  291. $item = $request->input('item');
  292. $action = $type.'.block';
  293. if (! in_array($action, $this->filters)) {
  294. return abort(406);
  295. }
  296. $filterable = [];
  297. switch ($type) {
  298. case 'user':
  299. $profile = Profile::findOrFail($item);
  300. if ($profile->id == $pid) {
  301. return abort(403);
  302. }
  303. $class = get_class($profile);
  304. $filterable['id'] = $profile->id;
  305. $filterable['type'] = $class;
  306. break;
  307. default:
  308. abort(400);
  309. break;
  310. }
  311. $filter = UserFilter::whereUserId($pid)
  312. ->whereFilterableId($filterable['id'])
  313. ->whereFilterableType($filterable['type'])
  314. ->whereFilterType('block')
  315. ->first();
  316. if ($filter) {
  317. $filter->delete();
  318. UserFilterService::unblock($pid, $filterable['id']);
  319. }
  320. $res = RelationshipService::refresh($pid, $profile->id);
  321. if ($request->wantsJson()) {
  322. return response()->json($res);
  323. } else {
  324. return redirect()->back();
  325. }
  326. }
  327. public function followRequests(Request $request)
  328. {
  329. $pid = Auth::user()->profile->id;
  330. $followers = FollowRequest::whereFollowingId($pid)->orderBy('id', 'desc')->whereIsRejected(0)->simplePaginate(10);
  331. return view('account.follow-requests', compact('followers'));
  332. }
  333. public function followRequestsJson(Request $request)
  334. {
  335. $pid = Auth::user()->profile_id;
  336. $followers = FollowRequest::whereFollowingId($pid)->orderBy('id', 'desc')->whereIsRejected(0)->get();
  337. $res = [
  338. 'count' => $followers->count(),
  339. 'accounts' => $followers->take(10)->map(function ($a) {
  340. $actor = $a->actor;
  341. return [
  342. 'rid' => (string) $a->id,
  343. 'id' => (string) $actor->id,
  344. 'username' => $actor->username,
  345. 'avatar' => $actor->avatarUrl(),
  346. 'url' => $actor->url(),
  347. 'local' => $actor->domain == null,
  348. 'account' => AccountService::get($actor->id),
  349. ];
  350. }),
  351. ];
  352. return response()->json($res, 200, [], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
  353. }
  354. public function followRequestHandle(Request $request)
  355. {
  356. $this->validate($request, [
  357. 'action' => 'required|string|max:10',
  358. 'id' => 'required|integer|min:1',
  359. ]);
  360. $pid = Auth::user()->profile->id;
  361. $action = $request->input('action') === 'accept' ? 'accept' : 'reject';
  362. $id = $request->input('id');
  363. $followRequest = FollowRequest::whereFollowingId($pid)->findOrFail($id);
  364. $follower = $followRequest->follower;
  365. switch ($action) {
  366. case 'accept':
  367. $follow = new Follower;
  368. $follow->profile_id = $follower->id;
  369. $follow->following_id = $pid;
  370. $follow->save();
  371. $profile = Profile::findOrFail($pid);
  372. $profile->followers_count++;
  373. $profile->save();
  374. AccountService::del($profile->id);
  375. $profile = Profile::findOrFail($follower->id);
  376. $profile->following_count++;
  377. $profile->save();
  378. AccountService::del($profile->id);
  379. if ($follower->domain != null && $follower->private_key === null) {
  380. FollowAcceptPipeline::dispatch($followRequest)->onQueue('follow');
  381. } else {
  382. FollowPipeline::dispatch($follow);
  383. $followRequest->delete();
  384. }
  385. break;
  386. case 'reject':
  387. if ($follower->domain != null && $follower->private_key === null) {
  388. FollowRejectPipeline::dispatch($followRequest)->onQueue('follow');
  389. } else {
  390. $followRequest->delete();
  391. }
  392. break;
  393. }
  394. Cache::forget('profile:follower_count:'.$pid);
  395. Cache::forget('profile:following_count:'.$pid);
  396. RelationshipService::refresh($pid, $follower->id);
  397. return response()->json(['msg' => 'success'], 200);
  398. }
  399. public function sudoMode(Request $request)
  400. {
  401. if ($request->session()->has('sudoModeAttempts') && $request->session()->get('sudoModeAttempts') >= 3) {
  402. $request->session()->pull('2fa.session.active');
  403. $request->session()->pull('redirectNext');
  404. $request->session()->pull('sudoModeAttempts');
  405. Auth::logout();
  406. return redirect(route('login'));
  407. }
  408. return view('auth.sudo');
  409. }
  410. public function sudoModeVerify(Request $request)
  411. {
  412. $this->validate($request, [
  413. 'password' => 'required|string|max:500',
  414. 'trustDevice' => 'nullable',
  415. ]);
  416. $user = Auth::user();
  417. $password = $request->input('password');
  418. $trustDevice = $request->input('trustDevice') == 'on';
  419. $next = $request->session()->get('redirectNext', '/');
  420. if ($request->session()->has('sudoModeAttempts')) {
  421. $count = (int) $request->session()->get('sudoModeAttempts');
  422. $request->session()->put('sudoModeAttempts', $count + 1);
  423. } else {
  424. $request->session()->put('sudoModeAttempts', 1);
  425. }
  426. if (password_verify($password, $user->password) === true) {
  427. $request->session()->put('sudoMode', time());
  428. if ($trustDevice == true) {
  429. $request->session()->put('sudoTrustDevice', 1);
  430. }
  431. // Fix wrong scheme when using reverse proxy
  432. if (! str_contains($next, 'https') && config('instance.force_https_urls', true)) {
  433. $next = Str::of($next)->replace('http', 'https')->toString();
  434. }
  435. return redirect($next);
  436. } else {
  437. return redirect()
  438. ->back()
  439. ->withErrors(['password' => __('auth.failed')]);
  440. }
  441. }
  442. public function twoFactorCheckpoint(Request $request)
  443. {
  444. return view('auth.checkpoint');
  445. }
  446. public function twoFactorVerify(Request $request)
  447. {
  448. $this->validate($request, [
  449. 'code' => 'required|string|max:32',
  450. ]);
  451. $user = Auth::user();
  452. $code = $request->input('code');
  453. $google2fa = new Google2FA;
  454. $verify = $google2fa->verifyKey($user->{'2fa_secret'}, $code);
  455. if ($verify) {
  456. $request->session()->push('2fa.session.active', true);
  457. return redirect('/');
  458. } else {
  459. if ($this->twoFactorBackupCheck($request, $code, $user)) {
  460. return redirect('/');
  461. }
  462. if ($request->session()->has('2fa.attempts')) {
  463. $count = (int) $request->session()->get('2fa.attempts');
  464. if ($count == 3) {
  465. Auth::logout();
  466. return redirect('/');
  467. }
  468. $request->session()->put('2fa.attempts', $count + 1);
  469. } else {
  470. $request->session()->put('2fa.attempts', 1);
  471. }
  472. return redirect('/i/auth/checkpoint')->withErrors([
  473. 'code' => 'Invalid code',
  474. ]);
  475. }
  476. }
  477. protected function twoFactorBackupCheck($request, $code, User $user)
  478. {
  479. $backupCodes = $user->{'2fa_backup_codes'};
  480. if ($backupCodes) {
  481. $codes = json_decode($backupCodes, true);
  482. foreach ($codes as $c) {
  483. if (hash_equals($c, $code)) {
  484. $codes = array_flatten(array_diff($codes, [$code]));
  485. $user->{'2fa_backup_codes'} = json_encode($codes);
  486. $user->save();
  487. $request->session()->push('2fa.session.active', true);
  488. return true;
  489. }
  490. }
  491. return false;
  492. } else {
  493. return false;
  494. }
  495. }
  496. public function accountRestored(Request $request) {}
  497. public function accountMutes(Request $request)
  498. {
  499. abort_if(! $request->user(), 403);
  500. $this->validate($request, [
  501. 'limit' => 'nullable|integer|min:1|max:40',
  502. ]);
  503. $user = $request->user();
  504. $limit = $request->input('limit') ?? 40;
  505. $mutes = UserFilter::whereUserId($user->profile_id)
  506. ->whereFilterableType('App\Profile')
  507. ->whereFilterType('mute')
  508. ->simplePaginate($limit)
  509. ->pluck('filterable_id');
  510. $accounts = Profile::find($mutes);
  511. $fractal = new Fractal\Manager;
  512. $fractal->setSerializer(new ArraySerializer);
  513. $resource = new Fractal\Resource\Collection($accounts, new AccountTransformer);
  514. $res = $fractal->createData($resource)->toArray();
  515. $url = $request->url();
  516. $page = $request->input('page', 1);
  517. $next = $page < 40 ? $page + 1 : 40;
  518. $prev = $page > 1 ? $page - 1 : 1;
  519. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  520. return response()->json($res, 200, ['Link' => $links]);
  521. }
  522. public function accountBlocks(Request $request)
  523. {
  524. abort_if(! $request->user(), 403);
  525. $this->validate($request, [
  526. 'limit' => 'nullable|integer|min:1|max:40',
  527. 'page' => 'nullable|integer|min:1|max:10',
  528. ]);
  529. $user = $request->user();
  530. $limit = $request->input('limit') ?? 40;
  531. $blocked = UserFilter::select('filterable_id', 'filterable_type', 'filter_type', 'user_id')
  532. ->whereUserId($user->profile_id)
  533. ->whereFilterableType('App\Profile')
  534. ->whereFilterType('block')
  535. ->simplePaginate($limit)
  536. ->pluck('filterable_id');
  537. $profiles = Profile::findOrFail($blocked);
  538. $fractal = new Fractal\Manager;
  539. $fractal->setSerializer(new ArraySerializer);
  540. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer);
  541. $res = $fractal->createData($resource)->toArray();
  542. $url = $request->url();
  543. $page = $request->input('page', 1);
  544. $next = $page < 40 ? $page + 1 : 40;
  545. $prev = $page > 1 ? $page - 1 : 1;
  546. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  547. return response()->json($res, 200, ['Link' => $links]);
  548. }
  549. public function accountBlocksV2(Request $request)
  550. {
  551. return response()->json(UserFilterService::blocks($request->user()->profile_id), 200, [], JSON_UNESCAPED_SLASHES);
  552. }
  553. public function accountMutesV2(Request $request)
  554. {
  555. return response()->json(UserFilterService::mutes($request->user()->profile_id), 200, [], JSON_UNESCAPED_SLASHES);
  556. }
  557. public function accountFiltersV2(Request $request)
  558. {
  559. return response()->json(UserFilterService::filters($request->user()->profile_id), 200, [], JSON_UNESCAPED_SLASHES);
  560. }
  561. }