UserController.php 13 KB

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