UserController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Classes\Pterodactyl;
  4. use App\Events\UserUpdateCreditsEvent;
  5. use App\Http\Controllers\Controller;
  6. use App\Models\DiscordUser;
  7. use App\Models\User;
  8. use App\Notifications\ReferralNotification;
  9. use Carbon\Carbon;
  10. use Illuminate\Contracts\Foundation\Application;
  11. use Illuminate\Contracts\Pagination\LengthAwarePaginator;
  12. use Illuminate\Contracts\Routing\ResponseFactory;
  13. use Illuminate\Database\Eloquent\Builder;
  14. use Illuminate\Database\Eloquent\Collection;
  15. use Illuminate\Database\Eloquent\Model;
  16. use Illuminate\Http\Request;
  17. use Illuminate\Http\Response;
  18. use Illuminate\Support\Facades\App;
  19. use Illuminate\Support\Facades\DB;
  20. use Illuminate\Support\Facades\Hash;
  21. use Illuminate\Support\Str;
  22. use Illuminate\Validation\Rule;
  23. use Illuminate\Validation\ValidationException;
  24. use Spatie\QueryBuilder\QueryBuilder;
  25. class UserController extends Controller
  26. {
  27. const ALLOWED_INCLUDES = ['servers', 'notifications', 'payments', 'vouchers', 'discordUser'];
  28. const ALLOWED_FILTERS = ['name', 'server_limit', 'email', 'pterodactyl_id', 'role', 'suspended'];
  29. /**
  30. * Display a listing of the resource.
  31. *
  32. * @param Request $request
  33. * @return LengthAwarePaginator
  34. */
  35. public function index(Request $request)
  36. {
  37. $query = QueryBuilder::for(User::class)
  38. ->allowedIncludes(self::ALLOWED_INCLUDES)
  39. ->allowedFilters(self::ALLOWED_FILTERS);
  40. return $query->paginate($request->input('per_page') ?? 50);
  41. }
  42. /**
  43. * Display the specified resource.
  44. *
  45. * @param int $id
  46. * @return User|Builder|Collection|Model
  47. */
  48. public function show(int $id)
  49. {
  50. $discordUser = DiscordUser::find($id);
  51. $user = $discordUser ? $discordUser->user : User::findOrFail($id);
  52. $query = QueryBuilder::for($user)
  53. ->with('discordUser')
  54. ->allowedIncludes(self::ALLOWED_INCLUDES)
  55. ->where('users.id', '=', $id)
  56. ->orWhereHas('discordUser', function (Builder $builder) use ($id) {
  57. $builder->where('id', '=', $id);
  58. });
  59. return $query->firstOrFail();
  60. }
  61. /**
  62. * Update the specified resource in storage.
  63. *
  64. * @param Request $request
  65. * @param int $id
  66. * @return User
  67. */
  68. public function update(Request $request, int $id)
  69. {
  70. $discordUser = DiscordUser::find($id);
  71. $user = $discordUser ? $discordUser->user : User::findOrFail($id);
  72. $request->validate([
  73. 'name' => 'sometimes|string|min:4|max:30',
  74. 'email' => 'sometimes|string|email',
  75. 'credits' => 'sometimes|numeric|min:0|max:1000000',
  76. 'server_limit' => 'sometimes|numeric|min:0|max:1000000',
  77. 'role' => ['sometimes', Rule::in(['admin', 'moderator', 'client', 'member'])],
  78. ]);
  79. event(new UserUpdateCreditsEvent($user));
  80. //Update Users Password on Pterodactyl
  81. //Username,Mail,First and Lastname are required aswell
  82. $response = Pterodactyl::client()->patch('/application/users/'.$user->pterodactyl_id, [
  83. 'username' => $request->name,
  84. 'first_name' => $request->name,
  85. 'last_name' => $request->name,
  86. 'email' => $request->email,
  87. ]);
  88. if ($response->failed()) {
  89. throw ValidationException::withMessages([
  90. 'pterodactyl_error_message' => $response->toException()->getMessage(),
  91. 'pterodactyl_error_status' => $response->toException()->getCode(),
  92. ]);
  93. }
  94. $user->update($request->all());
  95. return $user;
  96. }
  97. /**
  98. * increments the users credits or/and server_limit
  99. *
  100. * @param Request $request
  101. * @param int $id
  102. * @return User
  103. *
  104. * @throws ValidationException
  105. */
  106. public function increment(Request $request, int $id)
  107. {
  108. $discordUser = DiscordUser::find($id);
  109. $user = $discordUser ? $discordUser->user : User::findOrFail($id);
  110. $request->validate([
  111. 'credits' => 'sometimes|numeric|min:0|max:1000000',
  112. 'server_limit' => 'sometimes|numeric|min:0|max:1000000',
  113. ]);
  114. if ($request->credits) {
  115. if ($user->credits + $request->credits >= 99999999) {
  116. throw ValidationException::withMessages([
  117. 'credits' => "You can't add this amount of credits because you would exceed the credit limit",
  118. ]);
  119. }
  120. event(new UserUpdateCreditsEvent($user));
  121. $user->increment('credits', $request->credits);
  122. }
  123. if ($request->server_limit) {
  124. if ($user->server_limit + $request->server_limit >= 2147483647) {
  125. throw ValidationException::withMessages([
  126. 'server_limit' => 'You cannot add this amount of servers because it would exceed the server limit.',
  127. ]);
  128. }
  129. $user->increment('server_limit', $request->server_limit);
  130. }
  131. return $user;
  132. }
  133. /**
  134. * decrements the users credits or/and server_limit
  135. *
  136. * @param Request $request
  137. * @param int $id
  138. * @return User
  139. *
  140. * @throws ValidationException
  141. */
  142. public function decrement(Request $request, int $id)
  143. {
  144. $discordUser = DiscordUser::find($id);
  145. $user = $discordUser ? $discordUser->user : User::findOrFail($id);
  146. $request->validate([
  147. 'credits' => 'sometimes|numeric|min:0|max:1000000',
  148. 'server_limit' => 'sometimes|numeric|min:0|max:1000000',
  149. ]);
  150. if ($request->credits) {
  151. if ($user->credits - $request->credits < 0) {
  152. throw ValidationException::withMessages([
  153. 'credits' => "You can't remove this amount of credits because you would exceed the minimum credit limit",
  154. ]);
  155. }
  156. $user->decrement('credits', $request->credits);
  157. }
  158. if ($request->server_limit) {
  159. if ($user->server_limit - $request->server_limit < 0) {
  160. throw ValidationException::withMessages([
  161. 'server_limit' => 'You cannot remove this amount of servers because it would exceed the minimum server.',
  162. ]);
  163. }
  164. $user->decrement('server_limit', $request->server_limit);
  165. }
  166. return $user;
  167. }
  168. /**
  169. * Suspends the user
  170. *
  171. * @param Request $request
  172. * @param int $id
  173. * @return bool
  174. *
  175. * @throws ValidationException
  176. */
  177. public function suspend(Request $request, int $id)
  178. {
  179. $discordUser = DiscordUser::find($id);
  180. $user = $discordUser ? $discordUser->user : User::findOrFail($id);
  181. if ($user->isSuspended()) {
  182. throw ValidationException::withMessages([
  183. 'error' => 'The user is already suspended',
  184. ]);
  185. }
  186. $user->suspend();
  187. return $user;
  188. }
  189. /**
  190. * Unsuspend the user
  191. *
  192. * @param Request $request
  193. * @param int $id
  194. * @return bool
  195. *
  196. * @throws ValidationException
  197. */
  198. public function unsuspend(Request $request, int $id)
  199. {
  200. $discordUser = DiscordUser::find($id);
  201. $user = $discordUser ? $discordUser->user : User::findOrFail($id);
  202. if (! $user->isSuspended()) {
  203. throw ValidationException::withMessages([
  204. 'error' => 'You cannot unsuspend an User who is not suspended.',
  205. ]);
  206. }
  207. $user->unSuspend();
  208. return $user;
  209. }
  210. /**
  211. * Create a unique Referral Code for User
  212. *
  213. * @return string
  214. */
  215. protected function createReferralCode()
  216. {
  217. $referralcode = STR::random(8);
  218. if (User::where('referral_code', '=', $referralcode)->exists()) {
  219. $this->createReferralCode();
  220. }
  221. return $referralcode;
  222. }
  223. /**
  224. * @throws ValidationException
  225. */
  226. public function store(Request $request)
  227. {
  228. $request->validate([
  229. 'name' => ['required', 'string', 'max:30', 'min:4', 'alpha_num', 'unique:users'],
  230. 'email' => ['required', 'string', 'email', 'max:64', 'unique:users'],
  231. 'password' => ['required', 'string', 'min:8', 'max:191'],
  232. ]);
  233. // Prevent the creation of new users via API if this is enabled.
  234. if (! config('SETTINGS::SYSTEM:CREATION_OF_NEW_USERS', 'true')) {
  235. throw ValidationException::withMessages([
  236. 'error' => 'The creation of new users has been blocked by the system administrator.',
  237. ]);
  238. }
  239. $user = User::create([
  240. 'name' => $request->input('name'),
  241. 'email' => $request->input('email'),
  242. 'credits' => config('SETTINGS::USER:INITIAL_CREDITS', 150),
  243. 'server_limit' => config('SETTINGS::USER:INITIAL_SERVER_LIMIT', 1),
  244. 'password' => Hash::make($request->input('password')),
  245. 'referral_code' => $this->createReferralCode(),
  246. ]);
  247. $response = Pterodactyl::client()->post('/application/users', [
  248. 'external_id' => App::environment('local') ? Str::random(16) : (string) $user->id,
  249. 'username' => $user->name,
  250. 'email' => $user->email,
  251. 'first_name' => $user->name,
  252. 'last_name' => $user->name,
  253. 'password' => $request->input('password'),
  254. 'root_admin' => false,
  255. 'language' => 'en',
  256. ]);
  257. if ($response->failed()) {
  258. $user->delete();
  259. throw ValidationException::withMessages([
  260. 'pterodactyl_error_message' => $response->toException()->getMessage(),
  261. 'pterodactyl_error_status' => $response->toException()->getCode(),
  262. ]);
  263. }
  264. $user->update([
  265. 'pterodactyl_id' => $response->json()['attributes']['id'],
  266. ]);
  267. //INCREMENT REFERRAL-USER CREDITS
  268. if (! empty($request->input('referral_code'))) {
  269. $ref_code = $request->input('referral_code');
  270. $new_user = $user->id;
  271. if ($ref_user = User::query()->where('referral_code', '=', $ref_code)->first()) {
  272. if (config('SETTINGS::REFERRAL:MODE') == 'register' || config('SETTINGS::REFERRAL:MODE') == 'both') {
  273. $ref_user->increment('credits', config('SETTINGS::REFERRAL::REWARD'));
  274. $ref_user->notify(new ReferralNotification($ref_user->id, $new_user));
  275. }
  276. //INSERT INTO USER_REFERRALS TABLE
  277. DB::table('user_referrals')->insert([
  278. 'referral_id' => $ref_user->id,
  279. 'registered_user_id' => $user->id,
  280. 'created_at' => Carbon::now(),
  281. 'updated_at' => Carbon::now(),
  282. ]);
  283. }
  284. }
  285. $user->sendEmailVerificationNotification();
  286. return $user;
  287. }
  288. /**
  289. * Remove the specified resource from storage.
  290. *
  291. * @param int $id
  292. * @return Application|Response|ResponseFactory
  293. */
  294. public function destroy(int $id)
  295. {
  296. $discordUser = DiscordUser::find($id);
  297. $user = $discordUser ? $discordUser->user : User::findOrFail($id);
  298. $user->delete();
  299. return response($user, 200);
  300. }
  301. }