UserController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Events\UserUpdateCreditsEvent;
  4. use App\Http\Controllers\Controller;
  5. use App\Models\User;
  6. use App\Notifications\DynamicNotification;
  7. use App\Settings\LocaleSettings;
  8. use Exception;
  9. use Illuminate\Contracts\Foundation\Application;
  10. use Illuminate\Contracts\View\Factory;
  11. use Illuminate\Contracts\View\View;
  12. use Illuminate\Http\RedirectResponse;
  13. use Illuminate\Http\Request;
  14. use Illuminate\Http\Response;
  15. use Illuminate\Notifications\Messages\MailMessage;
  16. use Illuminate\Support\Facades\Auth;
  17. use Illuminate\Support\Facades\DB;
  18. use Illuminate\Support\Facades\Hash;
  19. use Illuminate\Support\Facades\Notification;
  20. use Illuminate\Support\HtmlString;
  21. use Illuminate\Validation\Rule;
  22. use Illuminate\Validation\ValidationException;
  23. use Spatie\QueryBuilder\QueryBuilder;
  24. class UserController extends Controller
  25. {
  26. /**
  27. * Display a listing of the resource.
  28. *
  29. * @param Request $request
  30. * @return Application|Factory|View|Response
  31. */
  32. public function index(LocaleSettings $locale_settings)
  33. {
  34. return view('admin.users.index', [
  35. 'locale_datatables' => $locale_settings->datatables
  36. ]);
  37. }
  38. /**
  39. * Display the specified resource.
  40. *
  41. * @param User $user
  42. * @return Application|Factory|View|Response
  43. */
  44. public function show(User $user)
  45. {
  46. //QUERY ALL REFERRALS A USER HAS
  47. //i am not proud of this at all.
  48. $allReferals = [];
  49. $referrals = DB::table('user_referrals')->where('referral_id', '=', $user->id)->get();
  50. foreach ($referrals as $referral) {
  51. array_push($allReferals, $allReferals['id'] = User::query()->findOrFail($referral->registered_user_id));
  52. }
  53. array_pop($allReferals);
  54. return view('admin.users.show')->with([
  55. 'user' => $user,
  56. 'referrals' => $allReferals,
  57. ]);
  58. }
  59. /**
  60. * Get a JSON response of users.
  61. *
  62. * @return \Illuminate\Support\Collection|\App\models\User
  63. */
  64. public function json(Request $request)
  65. {
  66. $users = QueryBuilder::for(User::query())
  67. ->allowedFilters(['id', 'name', 'pterodactyl_id', 'email'])
  68. ->paginate(25);
  69. if ($request->query('user_id')) {
  70. $user = User::query()->findOrFail($request->input('user_id'));
  71. $user->avatarUrl = $user->getAvatar();
  72. return $user;
  73. }
  74. return $users->map(function ($item) {
  75. $item->avatarUrl = $item->getAvatar();
  76. return $item;
  77. });
  78. }
  79. /**
  80. * Show the form for editing the specified resource.
  81. *
  82. * @param User $user
  83. * @return Application|Factory|View|Response
  84. */
  85. public function edit(User $user)
  86. {
  87. return view('admin.users.edit')->with([
  88. 'user' => $user,
  89. ]);
  90. }
  91. /**
  92. * Update the specified resource in storage.
  93. *
  94. * @param Request $request
  95. * @param User $user
  96. * @return RedirectResponse
  97. *
  98. * @throws Exception
  99. */
  100. public function update(Request $request, User $user)
  101. {
  102. $request->validate([
  103. 'name' => 'required|string|min:4|max:30',
  104. 'pterodactyl_id' => "required|numeric|unique:users,pterodactyl_id,{$user->id}",
  105. 'email' => 'required|string|email',
  106. 'credits' => 'required|numeric|min:0|max:99999999',
  107. 'server_limit' => 'required|numeric|min:0|max:1000000',
  108. 'role' => Rule::in(['admin', 'moderator', 'client', 'member']),
  109. 'referral_code' => "required|string|min:2|max:32|unique:users,referral_code,{$user->id}",
  110. ]);
  111. if (isset($this->pterodactyl->getUser($request->input('pterodactyl_id'))['errors'])) {
  112. throw ValidationException::withMessages([
  113. 'pterodactyl_id' => [__("User does not exists on pterodactyl's panel")],
  114. ]);
  115. }
  116. if (!is_null($request->input('new_password'))) {
  117. $request->validate([
  118. 'new_password' => 'required|string|min:8',
  119. 'new_password_confirmation' => 'required|same:new_password',
  120. ]);
  121. $user->update([
  122. 'password' => Hash::make($request->input('new_password')),
  123. ]);
  124. }
  125. $user->update($request->all());
  126. event(new UserUpdateCreditsEvent($user));
  127. return redirect()->route('admin.users.index')->with('success', 'User updated!');
  128. }
  129. /**
  130. * Remove the specified resource from storage.
  131. *
  132. * @param User $user
  133. * @return RedirectResponse
  134. */
  135. public function destroy(User $user)
  136. {
  137. $user->delete();
  138. return redirect()->back()->with('success', __('user has been removed!'));
  139. }
  140. /**
  141. * Verifys the users email
  142. *
  143. * @param User $user
  144. * @return RedirectResponse
  145. */
  146. public function verifyEmail(User $user)
  147. {
  148. $user->verifyEmail();
  149. return redirect()->back()->with('success', __('Email has been verified!'));
  150. }
  151. /**
  152. * @param Request $request
  153. * @param User $user
  154. * @return RedirectResponse
  155. */
  156. public function loginAs(Request $request, User $user)
  157. {
  158. $request->session()->put('previousUser', Auth::user()->id);
  159. Auth::login($user);
  160. return redirect()->route('home');
  161. }
  162. /**
  163. * @param Request $request
  164. * @return RedirectResponse
  165. */
  166. public function logBackIn(Request $request)
  167. {
  168. Auth::loginUsingId($request->session()->get('previousUser'), true);
  169. $request->session()->remove('previousUser');
  170. return redirect()->route('admin.users.index');
  171. }
  172. /**
  173. * Show the form for seding notifications to the specified resource.
  174. *
  175. * @param User $user
  176. * @return Application|Factory|View|Response
  177. */
  178. public function notifications()
  179. {
  180. return view('admin.users.notifications');
  181. }
  182. /**
  183. * Notify the specified resource.
  184. *
  185. * @param Request $request
  186. * @param User $user
  187. * @return RedirectResponse
  188. *
  189. * @throws Exception
  190. */
  191. public function notify(Request $request)
  192. {
  193. $data = $request->validate([
  194. 'via' => 'required|min:1|array',
  195. 'via.*' => 'required|string|in:mail,database',
  196. 'all' => 'required_without:users|boolean',
  197. 'users' => 'required_without:all|min:1|array',
  198. 'users.*' => 'exists:users,id',
  199. 'title' => 'required|string|min:1',
  200. 'content' => 'required|string|min:1',
  201. ]);
  202. $mail = null;
  203. $database = null;
  204. if (in_array('database', $data['via'])) {
  205. $database = [
  206. 'title' => $data['title'],
  207. 'content' => $data['content'],
  208. ];
  209. }
  210. if (in_array('mail', $data['via'])) {
  211. $mail = (new MailMessage)
  212. ->subject($data['title'])
  213. ->line(new HtmlString($data['content']));
  214. }
  215. $all = $data['all'] ?? false;
  216. $users = $all ? User::all() : User::whereIn('id', $data['users'])->get();
  217. Notification::send($users, new DynamicNotification($data['via'], $database, $mail));
  218. return redirect()->route('admin.users.notifications')->with('success', __('Notification sent!'));
  219. }
  220. /**
  221. * @param User $user
  222. * @return RedirectResponse
  223. */
  224. public function toggleSuspended(User $user)
  225. {
  226. try {
  227. !$user->isSuspended() ? $user->suspend() : $user->unSuspend();
  228. } catch (Exception $exception) {
  229. return redirect()->back()->with('error', $exception->getMessage());
  230. }
  231. return redirect()->back()->with('success', __('User has been updated!'));
  232. }
  233. /**
  234. * @throws Exception
  235. */
  236. public function dataTable(Request $request)
  237. {
  238. $query = User::with('discordUser')->withCount('servers');
  239. // manually count referrals in user_referrals table
  240. $query->selectRaw('users.*, (SELECT COUNT(*) FROM user_referrals WHERE user_referrals.referral_id = users.id) as referrals_count');
  241. return datatables($query)
  242. ->addColumn('avatar', function (User $user) {
  243. return '<img width="28px" height="28px" class="rounded-circle ml-1" src="' . $user->getAvatar() . '">';
  244. })
  245. ->addColumn('credits', function (User $user) {
  246. return '<i class="fas fa-coins mr-2"></i> ' . $user->credits();
  247. })
  248. ->addColumn('verified', function (User $user) {
  249. return $user->getVerifiedStatus();
  250. })
  251. ->addColumn('discordId', function (User $user) {
  252. return $user->discordUser ? $user->discordUser->id : '';
  253. })
  254. ->addColumn('actions', function (User $user) {
  255. $suspendColor = $user->isSuspended() ? 'btn-success' : 'btn-warning';
  256. $suspendIcon = $user->isSuspended() ? 'fa-play-circle' : 'fa-pause-circle';
  257. $suspendText = $user->isSuspended() ? __('Unsuspend') : __('Suspend');
  258. return '
  259. <a data-content="' . __('Login as User') . '" data-toggle="popover" data-trigger="hover" data-placement="top" href="' . route('admin.users.loginas', $user->id) . '" class="btn btn-sm btn-primary mr-1"><i class="fas fa-sign-in-alt"></i></a>
  260. <a data-content="' . __('Verify') . '" data-toggle="popover" data-trigger="hover" data-placement="top" href="' . route('admin.users.verifyEmail', $user->id) . '" class="btn btn-sm btn-secondary mr-1"><i class="fas fa-envelope"></i></a>
  261. <a data-content="' . __('Show') . '" data-toggle="popover" data-trigger="hover" data-placement="top" href="' . route('admin.users.show', $user->id) . '" class="btn btn-sm text-white btn-warning mr-1"><i class="fas fa-eye"></i></a>
  262. <a data-content="' . __('Edit') . '" data-toggle="popover" data-trigger="hover" data-placement="top" href="' . route('admin.users.edit', $user->id) . '" class="btn btn-sm btn-info mr-1"><i class="fas fa-pen"></i></a>
  263. <form class="d-inline" method="post" action="' . route('admin.users.togglesuspend', $user->id) . '">
  264. ' . csrf_field() . '
  265. <button data-content="' . $suspendText . '" data-toggle="popover" data-trigger="hover" data-placement="top" class="btn btn-sm ' . $suspendColor . ' text-white mr-1"><i class="far ' . $suspendIcon . '"></i></button>
  266. </form>
  267. <form class="d-inline" onsubmit="return submitResult();" method="post" action="' . route('admin.users.destroy', $user->id) . '">
  268. ' . csrf_field() . '
  269. ' . method_field('DELETE') . '
  270. <button data-content="' . __('Delete') . '" data-toggle="popover" data-trigger="hover" data-placement="top" class="btn btn-sm btn-danger mr-1"><i class="fas fa-trash"></i></button>
  271. </form>
  272. ';
  273. })
  274. ->editColumn('role', function (User $user) {
  275. switch ($user->role) {
  276. case 'admin':
  277. $badgeColor = 'badge-danger';
  278. break;
  279. case 'moderator':
  280. $badgeColor = 'badge-info';
  281. break;
  282. case 'client':
  283. $badgeColor = 'badge-success';
  284. break;
  285. default:
  286. $badgeColor = 'badge-secondary';
  287. break;
  288. }
  289. return '<span class="badge ' . $badgeColor . '">' . $user->role . '</span>';
  290. })
  291. ->editColumn('last_seen', function (User $user) {
  292. return $user->last_seen ? $user->last_seen->diffForHumans() : __('Never');
  293. })
  294. ->editColumn('name', function (User $user) {
  295. return '<a class="text-info" target="_blank" href="' . config('SETTINGS::SYSTEM:PTERODACTYL:URL') . '/admin/users/view/' . $user->pterodactyl_id . '">' . strip_tags($user->name) . '</a>';
  296. })
  297. ->rawColumns(['avatar', 'name', 'credits', 'role', 'usage', 'actions'])
  298. ->make();
  299. }
  300. }