UserController.php 13 KB

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