AccountController.php 17 KB

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