UserController.php 13 KB

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