UserController.php 11 KB

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