AccountController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\EmailVerification;
  4. use App\Follower;
  5. use App\FollowRequest;
  6. use App\Jobs\FollowPipeline\FollowPipeline;
  7. use App\Mail\ConfirmEmail;
  8. use App\Notification;
  9. use App\Profile;
  10. use App\User;
  11. use App\UserFilter;
  12. use Auth;
  13. use Cache;
  14. use Carbon\Carbon;
  15. use Illuminate\Http\Request;
  16. use Mail;
  17. use Redis;
  18. use PragmaRX\Google2FA\Google2FA;
  19. class AccountController extends Controller
  20. {
  21. protected $filters = [
  22. 'user.mute',
  23. 'user.block',
  24. ];
  25. public function __construct()
  26. {
  27. $this->middleware('auth');
  28. }
  29. public function notifications(Request $request)
  30. {
  31. $this->validate($request, [
  32. 'page' => 'nullable|min:1|max:3',
  33. 'a' => 'nullable|alpha_dash',
  34. ]);
  35. $profile = Auth::user()->profile;
  36. $action = $request->input('a');
  37. $timeago = Carbon::now()->subMonths(6);
  38. if ($action && in_array($action, ['comment', 'follow', 'mention'])) {
  39. $notifications = Notification::whereProfileId($profile->id)
  40. ->whereAction($action)
  41. ->whereDate('created_at', '>', $timeago)
  42. ->orderBy('id', 'desc')
  43. ->simplePaginate(30);
  44. } else {
  45. $notifications = Notification::whereProfileId($profile->id)
  46. ->whereDate('created_at', '>', $timeago)
  47. ->orderBy('id', 'desc')
  48. ->simplePaginate(30);
  49. }
  50. return view('account.activity', compact('profile', 'notifications'));
  51. }
  52. public function followingActivity(Request $request)
  53. {
  54. $this->validate($request, [
  55. 'page' => 'nullable|min:1|max:3',
  56. 'a' => 'nullable|alpha_dash',
  57. ]);
  58. $profile = Auth::user()->profile;
  59. $action = $request->input('a');
  60. $allowed = ['like', 'follow'];
  61. $timeago = Carbon::now()->subMonths(3);
  62. $following = $profile->following->pluck('id');
  63. $notifications = Notification::whereIn('actor_id', $following)
  64. ->whereIn('action', $allowed)
  65. ->where('actor_id', '<>', $profile->id)
  66. ->where('profile_id', '<>', $profile->id)
  67. ->whereDate('created_at', '>', $timeago)
  68. ->orderBy('notifications.created_at', 'desc')
  69. ->simplePaginate(30);
  70. return view('account.following', compact('profile', 'notifications'));
  71. }
  72. public function verifyEmail(Request $request)
  73. {
  74. return view('account.verify_email');
  75. }
  76. public function sendVerifyEmail(Request $request)
  77. {
  78. $timeLimit = Carbon::now()->subDays(1)->toDateTimeString();
  79. $recentAttempt = EmailVerification::whereUserId(Auth::id())
  80. ->where('created_at', '>', $timeLimit)->count();
  81. $exists = EmailVerification::whereUserId(Auth::id())->count();
  82. if ($recentAttempt == 1 && $exists == 1) {
  83. return redirect()->back()->with('error', 'A verification email has already been sent recently. Please check your email, or try again later.');
  84. } elseif ($recentAttempt == 0 && $exists !== 0) {
  85. // Delete old verification and send new one.
  86. EmailVerification::whereUserId(Auth::id())->delete();
  87. }
  88. $user = User::whereNull('email_verified_at')->find(Auth::id());
  89. $utoken = hash('sha512', $user->id);
  90. $rtoken = str_random(40);
  91. $verify = new EmailVerification();
  92. $verify->user_id = $user->id;
  93. $verify->email = $user->email;
  94. $verify->user_token = $utoken;
  95. $verify->random_token = $rtoken;
  96. $verify->save();
  97. Mail::to($user->email)->send(new ConfirmEmail($verify));
  98. return redirect()->back()->with('status', 'Verification email sent!');
  99. }
  100. public function confirmVerifyEmail(Request $request, $userToken, $randomToken)
  101. {
  102. $verify = EmailVerification::where('user_token', $userToken)
  103. ->where('random_token', $randomToken)
  104. ->firstOrFail();
  105. if (Auth::id() === $verify->user_id) {
  106. $user = User::find(Auth::id());
  107. $user->email_verified_at = Carbon::now();
  108. $user->save();
  109. return redirect('/');
  110. }
  111. }
  112. public function fetchNotifications($id)
  113. {
  114. $key = config('cache.prefix').":user.{$id}.notifications";
  115. $redis = Redis::connection();
  116. $notifications = $redis->lrange($key, 0, 30);
  117. if (empty($notifications)) {
  118. $notifications = Notification::whereProfileId($id)
  119. ->orderBy('id', 'desc')->take(30)->get();
  120. } else {
  121. $notifications = $this->hydrateNotifications($notifications);
  122. }
  123. return $notifications;
  124. }
  125. public function hydrateNotifications($keys)
  126. {
  127. $prefix = 'notification.';
  128. $notifications = collect([]);
  129. foreach ($keys as $key) {
  130. $notifications->push(Cache::get("{$prefix}{$key}"));
  131. }
  132. return $notifications;
  133. }
  134. public function messages()
  135. {
  136. return view('account.messages');
  137. }
  138. public function showMessage(Request $request, $id)
  139. {
  140. return view('account.message');
  141. }
  142. public function mute(Request $request)
  143. {
  144. $this->validate($request, [
  145. 'type' => 'required|string',
  146. 'item' => 'required|integer|min:1',
  147. ]);
  148. $user = Auth::user()->profile;
  149. $type = $request->input('type');
  150. $item = $request->input('item');
  151. $action = "{$type}.mute";
  152. if (!in_array($action, $this->filters)) {
  153. return abort(406);
  154. }
  155. $filterable = [];
  156. switch ($type) {
  157. case 'user':
  158. $profile = Profile::findOrFail($item);
  159. if ($profile->id == $user->id) {
  160. return abort(403);
  161. }
  162. $class = get_class($profile);
  163. $filterable['id'] = $profile->id;
  164. $filterable['type'] = $class;
  165. break;
  166. default:
  167. // code...
  168. break;
  169. }
  170. $filter = UserFilter::firstOrCreate([
  171. 'user_id' => $user->id,
  172. 'filterable_id' => $filterable['id'],
  173. 'filterable_type' => $filterable['type'],
  174. 'filter_type' => 'mute',
  175. ]);
  176. $pid = $user->id;
  177. Cache::remember("user:filter:list:$pid", 1440, function() use($pid) {
  178. return UserFilter::whereUserId($pid)
  179. ->whereFilterableType('App\Profile')
  180. ->whereIn('filter_type', ['mute', 'block'])
  181. ->pluck('filterable_id')->toArray();
  182. });
  183. return redirect()->back();
  184. }
  185. public function block(Request $request)
  186. {
  187. $this->validate($request, [
  188. 'type' => 'required|string',
  189. 'item' => 'required|integer|min:1',
  190. ]);
  191. $user = Auth::user()->profile;
  192. $type = $request->input('type');
  193. $item = $request->input('item');
  194. $action = "{$type}.block";
  195. if (!in_array($action, $this->filters)) {
  196. return abort(406);
  197. }
  198. $filterable = [];
  199. switch ($type) {
  200. case 'user':
  201. $profile = Profile::findOrFail($item);
  202. if ($profile->id == $user->id) {
  203. return abort(403);
  204. }
  205. $class = get_class($profile);
  206. $filterable['id'] = $profile->id;
  207. $filterable['type'] = $class;
  208. Follower::whereProfileId($profile->id)->whereFollowingId($user->id)->delete();
  209. Notification::whereProfileId($user->id)->whereActorId($profile->id)->delete();
  210. break;
  211. default:
  212. // code...
  213. break;
  214. }
  215. $filter = UserFilter::firstOrCreate([
  216. 'user_id' => $user->id,
  217. 'filterable_id' => $filterable['id'],
  218. 'filterable_type' => $filterable['type'],
  219. 'filter_type' => 'block',
  220. ]);
  221. $pid = $user->id;
  222. Cache::remember("user:filter:list:$pid", 1440, function() use($pid) {
  223. return UserFilter::whereUserId($pid)
  224. ->whereFilterableType('App\Profile')
  225. ->whereIn('filter_type', ['mute', 'block'])
  226. ->pluck('filterable_id')->toArray();
  227. });
  228. return redirect()->back();
  229. }
  230. public function followRequests(Request $request)
  231. {
  232. $pid = Auth::user()->profile->id;
  233. $followers = FollowRequest::whereFollowingId($pid)->orderBy('id','desc')->whereIsRejected(0)->simplePaginate(10);
  234. return view('account.follow-requests', compact('followers'));
  235. }
  236. public function followRequestHandle(Request $request)
  237. {
  238. $this->validate($request, [
  239. 'action' => 'required|string|max:10',
  240. 'id' => 'required|integer|min:1'
  241. ]);
  242. $pid = Auth::user()->profile->id;
  243. $action = $request->input('action') === 'accept' ? 'accept' : 'reject';
  244. $id = $request->input('id');
  245. $followRequest = FollowRequest::whereFollowingId($pid)->findOrFail($id);
  246. $follower = $followRequest->follower;
  247. switch ($action) {
  248. case 'accept':
  249. $follow = new Follower();
  250. $follow->profile_id = $follower->id;
  251. $follow->following_id = $pid;
  252. $follow->save();
  253. FollowPipeline::dispatch($follow);
  254. $followRequest->delete();
  255. break;
  256. case 'reject':
  257. $followRequest->is_rejected = true;
  258. $followRequest->save();
  259. break;
  260. }
  261. return response()->json(['msg' => 'success'], 200);
  262. }
  263. public function sudoMode(Request $request)
  264. {
  265. return view('auth.sudo');
  266. }
  267. public function sudoModeVerify(Request $request)
  268. {
  269. $this->validate($request, [
  270. 'password' => 'required|string|max:500'
  271. ]);
  272. $user = Auth::user();
  273. $password = $request->input('password');
  274. $next = $request->session()->get('redirectNext', '/');
  275. if(password_verify($password, $user->password) === true) {
  276. $request->session()->put('sudoMode', time());
  277. return redirect($next);
  278. } else {
  279. return redirect()
  280. ->back()
  281. ->withErrors(['password' => __('auth.failed')]);
  282. }
  283. }
  284. public function twoFactorCheckpoint(Request $request)
  285. {
  286. return view('auth.checkpoint');
  287. }
  288. public function twoFactorVerify(Request $request)
  289. {
  290. $this->validate($request, [
  291. 'code' => 'required|string|max:32'
  292. ]);
  293. $user = Auth::user();
  294. $code = $request->input('code');
  295. $google2fa = new Google2FA();
  296. $verify = $google2fa->verifyKey($user->{'2fa_secret'}, $code);
  297. if($verify) {
  298. $request->session()->push('2fa.session.active', true);
  299. return redirect('/');
  300. } else {
  301. if($request->session()->has('2fa.attempts')) {
  302. $count = (int) $request->session()->has('2fa.attempts');
  303. $request->session()->push('2fa.attempts', $count + 1);
  304. } else {
  305. $request->session()->push('2fa.attempts', 1);
  306. }
  307. return redirect()->back()->withErrors([
  308. 'code' => 'Invalid code'
  309. ]);
  310. }
  311. }
  312. }