UserController.php 12 KB

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