UserController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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', 'roles', 'discordUser'];
  28. const ALLOWED_FILTERS = ['name', 'server_limit', 'email', 'pterodactyl_id', '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. ]);
  78. event(new UserUpdateCreditsEvent($user));
  79. //Update Users Password on Pterodactyl
  80. //Username,Mail,First and Lastname are required aswell
  81. $response = Pterodactyl::client()->patch('/application/users/'.$user->pterodactyl_id, [
  82. 'username' => $request->name,
  83. 'first_name' => $request->name,
  84. 'last_name' => $request->name,
  85. 'email' => $request->email,
  86. ]);
  87. if ($response->failed()) {
  88. throw ValidationException::withMessages([
  89. 'pterodactyl_error_message' => $response->toException()->getMessage(),
  90. 'pterodactyl_error_status' => $response->toException()->getCode(),
  91. ]);
  92. }
  93. if($request->has("role")){
  94. $user->syncRoles($request->role);
  95. }
  96. $user->update($request->except('role'));
  97. return $user;
  98. }
  99. /**
  100. * increments the users credits or/and server_limit
  101. *
  102. * @param Request $request
  103. * @param int $id
  104. * @return User
  105. *
  106. * @throws ValidationException
  107. */
  108. public function increment(Request $request, int $id)
  109. {
  110. $discordUser = DiscordUser::find($id);
  111. $user = $discordUser ? $discordUser->user : User::findOrFail($id);
  112. $request->validate([
  113. 'credits' => 'sometimes|numeric|min:0|max:1000000',
  114. 'server_limit' => 'sometimes|numeric|min:0|max:1000000',
  115. ]);
  116. if ($request->credits) {
  117. if ($user->credits + $request->credits >= 99999999) {
  118. throw ValidationException::withMessages([
  119. 'credits' => "You can't add this amount of credits because you would exceed the credit limit",
  120. ]);
  121. }
  122. event(new UserUpdateCreditsEvent($user));
  123. $user->increment('credits', $request->credits);
  124. }
  125. if ($request->server_limit) {
  126. if ($user->server_limit + $request->server_limit >= 2147483647) {
  127. throw ValidationException::withMessages([
  128. 'server_limit' => 'You cannot add this amount of servers because it would exceed the server limit.',
  129. ]);
  130. }
  131. $user->increment('server_limit', $request->server_limit);
  132. }
  133. return $user;
  134. }
  135. /**
  136. * decrements the users credits or/and server_limit
  137. *
  138. * @param Request $request
  139. * @param int $id
  140. * @return User
  141. *
  142. * @throws ValidationException
  143. */
  144. public function decrement(Request $request, int $id)
  145. {
  146. $discordUser = DiscordUser::find($id);
  147. $user = $discordUser ? $discordUser->user : User::findOrFail($id);
  148. $request->validate([
  149. 'credits' => 'sometimes|numeric|min:0|max:1000000',
  150. 'server_limit' => 'sometimes|numeric|min:0|max:1000000',
  151. ]);
  152. if ($request->credits) {
  153. if ($user->credits - $request->credits < 0) {
  154. throw ValidationException::withMessages([
  155. 'credits' => "You can't remove this amount of credits because you would exceed the minimum credit limit",
  156. ]);
  157. }
  158. $user->decrement('credits', $request->credits);
  159. }
  160. if ($request->server_limit) {
  161. if ($user->server_limit - $request->server_limit < 0) {
  162. throw ValidationException::withMessages([
  163. 'server_limit' => 'You cannot remove this amount of servers because it would exceed the minimum server.',
  164. ]);
  165. }
  166. $user->decrement('server_limit', $request->server_limit);
  167. }
  168. return $user;
  169. }
  170. /**
  171. * Suspends the user
  172. *
  173. * @param Request $request
  174. * @param int $id
  175. * @return bool
  176. *
  177. * @throws ValidationException
  178. */
  179. public function suspend(Request $request, int $id)
  180. {
  181. $discordUser = DiscordUser::find($id);
  182. $user = $discordUser ? $discordUser->user : User::findOrFail($id);
  183. if ($user->isSuspended()) {
  184. throw ValidationException::withMessages([
  185. 'error' => 'The user is already suspended',
  186. ]);
  187. }
  188. $user->suspend();
  189. return $user;
  190. }
  191. /**
  192. * Unsuspend the user
  193. *
  194. * @param Request $request
  195. * @param int $id
  196. * @return bool
  197. *
  198. * @throws ValidationException
  199. */
  200. public function unsuspend(Request $request, int $id)
  201. {
  202. $discordUser = DiscordUser::find($id);
  203. $user = $discordUser ? $discordUser->user : User::findOrFail($id);
  204. if (! $user->isSuspended()) {
  205. throw ValidationException::withMessages([
  206. 'error' => 'You cannot unsuspend an User who is not suspended.',
  207. ]);
  208. }
  209. $user->unSuspend();
  210. return $user;
  211. }
  212. /**
  213. * Create a unique Referral Code for User
  214. *
  215. * @return string
  216. */
  217. protected function createReferralCode()
  218. {
  219. $referralcode = STR::random(8);
  220. if (User::where('referral_code', '=', $referralcode)->exists()) {
  221. $this->createReferralCode();
  222. }
  223. return $referralcode;
  224. }
  225. /**
  226. * @throws ValidationException
  227. */
  228. public function store(Request $request)
  229. {
  230. $request->validate([
  231. 'name' => ['required', 'string', 'max:30', 'min:4', 'alpha_num', 'unique:users'],
  232. 'email' => ['required', 'string', 'email', 'max:64', 'unique:users'],
  233. 'password' => ['required', 'string', 'min:8', 'max:191'],
  234. ]);
  235. // Prevent the creation of new users via API if this is enabled.
  236. if (! config('SETTINGS::SYSTEM:CREATION_OF_NEW_USERS', 'true')) {
  237. throw ValidationException::withMessages([
  238. 'error' => 'The creation of new users has been blocked by the system administrator.',
  239. ]);
  240. }
  241. $user = User::create([
  242. 'name' => $request->input('name'),
  243. 'email' => $request->input('email'),
  244. 'credits' => config('SETTINGS::USER:INITIAL_CREDITS', 150),
  245. 'server_limit' => config('SETTINGS::USER:INITIAL_SERVER_LIMIT', 1),
  246. 'password' => Hash::make($request->input('password')),
  247. 'referral_code' => $this->createReferralCode(),
  248. ]);
  249. $response = Pterodactyl::client()->post('/application/users', [
  250. 'external_id' => App::environment('local') ? Str::random(16) : (string) $user->id,
  251. 'username' => $user->name,
  252. 'email' => $user->email,
  253. 'first_name' => $user->name,
  254. 'last_name' => $user->name,
  255. 'password' => $request->input('password'),
  256. 'root_admin' => false,
  257. 'language' => 'en',
  258. ]);
  259. if ($response->failed()) {
  260. $user->delete();
  261. throw ValidationException::withMessages([
  262. 'pterodactyl_error_message' => $response->toException()->getMessage(),
  263. 'pterodactyl_error_status' => $response->toException()->getCode(),
  264. ]);
  265. }
  266. $user->update([
  267. 'pterodactyl_id' => $response->json()['attributes']['id'],
  268. ]);
  269. //INCREMENT REFERRAL-USER CREDITS
  270. if (! empty($request->input('referral_code'))) {
  271. $ref_code = $request->input('referral_code');
  272. $new_user = $user->id;
  273. if ($ref_user = User::query()->where('referral_code', '=', $ref_code)->first()) {
  274. if (config('SETTINGS::REFERRAL:MODE') == 'register' || config('SETTINGS::REFERRAL:MODE') == 'both') {
  275. $ref_user->increment('credits', config('SETTINGS::REFERRAL::REWARD'));
  276. $ref_user->notify(new ReferralNotification($ref_user->id, $new_user));
  277. }
  278. //INSERT INTO USER_REFERRALS TABLE
  279. DB::table('user_referrals')->insert([
  280. 'referral_id' => $ref_user->id,
  281. 'registered_user_id' => $user->id,
  282. 'created_at' => Carbon::now(),
  283. 'updated_at' => Carbon::now(),
  284. ]);
  285. }
  286. }
  287. $user->sendEmailVerificationNotification();
  288. return $user;
  289. }
  290. /**
  291. * Remove the specified resource from storage.
  292. *
  293. * @param int $id
  294. * @return Application|Response|ResponseFactory
  295. */
  296. public function destroy(int $id)
  297. {
  298. $discordUser = DiscordUser::find($id);
  299. $user = $discordUser ? $discordUser->user : User::findOrFail($id);
  300. $user->delete();
  301. return response($user, 200);
  302. }
  303. }