GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

ServerController::install()   A
last analyzed

Complexity

Conditions 3
Paths 5

Size

Total Lines 21
Code Lines 15

Duplication

Lines 21
Ratio 100 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 21
loc 21
rs 9.3142
cc 3
eloc 15
nc 5
nop 2
1
<?php
2
/**
3
 * Pterodactyl - Panel
4
 * Copyright (c) 2015 - 2017 Dane Everitt <[email protected]>.
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in all
14
 * copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
 * SOFTWARE.
23
 */
24
25
namespace Pterodactyl\Http\Controllers\API\Admin;
26
27
use Log;
28
use Fractal;
29
use Illuminate\Http\Request;
30
use Pterodactyl\Models\Server;
31
use GuzzleHttp\Exception\TransferException;
32
use Pterodactyl\Exceptions\DisplayException;
33
use Pterodactyl\Http\Controllers\Controller;
34
use Pterodactyl\Repositories\ServerRepository;
35
use Pterodactyl\Transformers\Admin\ServerTransformer;
36
use Pterodactyl\Exceptions\DisplayValidationException;
37
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
38
39
class ServerController extends Controller
40
{
41
    /**
42
     * Controller to handle returning all servers on the system.
43
     *
44
     * @param  \Illuminate\Http\Request  $request
45
     * @return array
46
     */
47 View Code Duplication
    public function index(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
48
    {
49
        $this->authorize('server-list', $request->apiKey());
50
51
        $servers = Server::paginate(config('pterodactyl.paginate.api.servers'));
52
        $fractal = Fractal::create()->collection($servers)
53
            ->transformWith(new ServerTransformer($request))
54
            ->withResourceName('user')
55
            ->paginateWith(new IlluminatePaginatorAdapter($servers));
56
57
        if (config('pterodactyl.api.include_on_list') && $request->input('include')) {
58
            $fractal->parseIncludes(explode(',', $request->input('include')));
59
        }
60
61
        return $fractal->toArray();
62
    }
63
64
    /**
65
     * Controller to handle returning information on a single server.
66
     *
67
     * @param  \Illuminate\Http\Request  $request
68
     * @param  int                       $id
69
     * @return array
70
     */
71 View Code Duplication
    public function view(Request $request, $id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
72
    {
73
        $this->authorize('server-view', $request->apiKey());
74
75
        $server = Server::findOrFail($id);
76
        $fractal = Fractal::create()->item($server);
77
78
        if ($request->input('include')) {
79
            $fractal->parseIncludes(explode(',', $request->input('include')));
80
        }
81
82
        return $fractal->transformWith(new ServerTransformer($request))
83
            ->withResourceName('server')
84
            ->toArray();
85
    }
86
87
    /**
88
     * Create a new server on the system.
89
     *
90
     * @param  \Illuminate\Http\Request  $request
91
     * @return \Illuminate\Http\JsonResponse|array
92
     */
93
    public function store(Request $request)
94
    {
95
        $this->authorize('server-create', $request->apiKey());
96
97
        $repo = new ServerRepository;
98
        try {
99
            $server = $repo->create($request->all());
100
101
            $fractal = Fractal::create()->item($server)->transformWith(new ServerTransformer($request));
102
            if ($request->input('include')) {
103
                $fractal->parseIncludes(explode(',', $request->input('include')));
104
            }
105
106
            return $fractal->withResourceName('server')->toArray();
107
        } catch (DisplayValidationException $ex) {
108
            return response()->json([
109
                'error' => json_decode($ex->getMessage()),
110
            ], 400);
111
        } catch (DisplayException $ex) {
112
            return response()->json([
113
                'error' => $ex->getMessage(),
114
            ], 400);
115
        } catch (TransferException $ex) {
116
            Log::warning($ex);
117
118
            return response()->json([
119
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
120
            ], 504);
121
        } catch (\Exception $ex) {
122
            Log::error($ex);
123
124
            return response()->json([
125
                'error' => 'An unhandled exception occured while attemping to add this server. Please try again.',
126
            ], 500);
127
        }
128
    }
129
130
    /**
131
     * Delete a server from the system.
132
     *
133
     * @param  \Illuminate\Http\Request  $request
134
     * @param  int                       $id
135
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
136
     */
137
    public function delete(Request $request, $id)
138
    {
139
        $this->authorize('server-delete', $request->apiKey());
140
141
        $repo = new ServerRepository;
142
        try {
143
            $repo->delete($id, $request->has('force_delete'));
144
145
            return response('', 204);
146
        } catch (DisplayException $ex) {
147
            return response()->json([
148
                'error' => $ex->getMessage(),
149
            ], 400);
150
        } catch (TransferException $ex) {
151
            Log::warning($ex);
152
153
            return response()->json([
154
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
155
            ], 504);
156
        } catch (\Exception $ex) {
157
            Log::error($ex);
158
159
            return response()->json([
160
                'error' => 'An unhandled exception occured while attemping to add this server. Please try again.',
161
            ], 500);
162
        }
163
    }
164
165
    /**
166
     * Update the details for a server.
167
     *
168
     * @param  \Illuminate\Http\Request  $request
169
     * @param  int                       $id
170
     * @return \Illuminate\Http\JsonResponse|array
171
     */
172
    public function details(Request $request, $id)
173
    {
174
        $this->authorize('server-edit-details', $request->apiKey());
175
176
        $repo = new ServerRepository;
177
        try {
178
            $server = $repo->updateDetails($id, $request->intersect([
179
                'owner_id', 'name', 'description', 'reset_token',
180
            ]));
181
182
            $fractal = Fractal::create()->item($server)->transformWith(new ServerTransformer($request));
183
            if ($request->input('include')) {
184
                $fractal->parseIncludes(explode(',', $request->input('include')));
185
            }
186
187
            return $fractal->withResourceName('server')->toArray();
188
        } catch (DisplayValidationException $ex) {
189
            return response()->json([
190
                'error' => json_decode($ex->getMessage()),
191
            ], 400);
192
        } catch (DisplayException $ex) {
193
            return response()->json([
194
                'error' => $ex->getMessage(),
195
            ], 400);
196
        } catch (\Exception $ex) {
197
            Log::error($ex);
198
199
            return response()->json([
200
                'error' => 'An unhandled exception occured while attemping to modify this server. Please try again.',
201
            ], 500);
202
        }
203
    }
204
205
    /**
206
     * Set the new docker container for a server.
207
     *
208
     * @param  \Illuminate\Http\Request  $request
209
     * @param  int                       $id
210
     * @return \Illuminate\Http\RedirectResponse|array
211
     */
212
    public function container(Request $request, $id)
213
    {
214
        $this->authorize('server-edit-container', $request->apiKey());
215
216
        $repo = new ServerRepository;
217
        try {
218
            $server = $repo->updateContainer($id, $request->intersect('docker_image'));
219
220
            $fractal = Fractal::create()->item($server)->transformWith(new ServerTransformer($request));
221
            if ($request->input('include')) {
222
                $fractal->parseIncludes(explode(',', $request->input('include')));
223
            }
224
225
            return $fractal->withResourceName('server')->toArray();
226
        } catch (DisplayValidationException $ex) {
227
            return response()->json([
0 ignored issues
show
Bug Best Practice introduced by
The return type of return response()->json(...->getMessage())), 400); (Illuminate\Http\JsonResponse) is incompatible with the return type documented by Pterodactyl\Http\Control...erController::container of type Illuminate\Http\RedirectResponse|array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
228
                'error' => json_decode($ex->getMessage()),
229
            ], 400);
230
        } catch (TransferException $ex) {
231
            Log::warning($ex);
232
233
            return response()->json([
0 ignored issues
show
Bug Best Practice introduced by
The return type of return response()->json(...s been logged.'), 504); (Illuminate\Http\JsonResponse) is incompatible with the return type documented by Pterodactyl\Http\Control...erController::container of type Illuminate\Http\RedirectResponse|array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
234
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
235
            ], 504);
236
        } catch (\Exception $ex) {
237
            Log::error($ex);
238
239
            return response()->json([
0 ignored issues
show
Bug Best Practice introduced by
The return type of return response()->json(...ase try again.'), 500); (Illuminate\Http\JsonResponse) is incompatible with the return type documented by Pterodactyl\Http\Control...erController::container of type Illuminate\Http\RedirectResponse|array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
240
                'error' => 'An unhandled exception occured while attemping to modify this server container. Please try again.',
241
            ], 500);
242
        }
243
    }
244
245
    /**
246
     * Toggles the install status for a server.
247
     *
248
     * @param  \Illuminate\Http\Request  $request
249
     * @param  int                       $id
250
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
251
     */
252 View Code Duplication
    public function install(Request $request, $id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
253
    {
254
        $this->authorize('server-install', $request->apiKey());
255
256
        $repo = new ServerRepository;
257
        try {
258
            $repo->toggleInstall($id);
259
260
            return response('', 204);
261
        } catch (DisplayException $ex) {
262
            return response()->json([
263
                'error' => $ex->getMessage(),
264
            ], 400);
265
        } catch (\Exception $ex) {
266
            Log::error($ex);
267
268
            return response()->json([
269
                'error' => 'An unhandled exception occured while attemping to toggle the install status for this server. Please try again.',
270
            ], 500);
271
        }
272
    }
273
274
    /**
275
     * Setup a server to have a container rebuild.
276
     *
277
     * @param  \Illuminate\Http\Request  $request
278
     * @param  int                       $id
279
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
280
     */
281
    public function rebuild(Request $request, $id)
282
    {
283
        $this->authorize('server-rebuild', $request->apiKey());
284
        $server = Server::with('node')->findOrFail($id);
0 ignored issues
show
Bug introduced by
The method findOrFail does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Eloquent\Model.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
285
286
        try {
287
            $server->node->guzzleClient([
288
                'X-Access-Server' => $server->uuid,
289
                'X-Access-Token' => $server->node->daemonSecret,
290
            ])->request('POST', '/server/rebuild');
291
292
            return response('', 204);
293
        } catch (TransferException $ex) {
294
            Log::warning($ex);
295
296
            return response()->json([
297
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
298
            ], 504);
299
        }
300
    }
301
302
    /**
303
     * Manage the suspension status for a server.
304
     *
305
     * @param  \Illuminate\Http\Request  $request
306
     * @param  int                       $id
307
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
308
     */
309
    public function suspend(Request $request, $id)
310
    {
311
        $this->authorize('server-suspend', $request->apiKey());
312
313
        $repo = new ServerRepository;
314
        $action = $request->input('action');
315
        if (! in_array($action, ['suspend', 'unsuspend'])) {
316
            return response()->json([
317
                'error' => 'The action provided was invalid. Action should be one of: suspend, unsuspend.',
318
            ], 400);
319
        }
320
321
        try {
322
            $repo->toggleAccess($id, ($action === 'unsuspend'));
323
324
            return response('', 204);
325
        } catch (DisplayException $ex) {
326
            return response()->json([
327
                'error' => $ex->getMessage(),
328
            ], 400);
329
        } catch (TransferException $ex) {
330
            Log::warning($ex);
331
332
            return response()->json([
333
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
334
            ], 504);
335
        } catch (\Exception $ex) {
336
            Log::error($ex);
337
338
            return response()->json([
339
                'error' => 'An unhandled exception occured while attemping to ' . $action . ' this server. Please try again.',
340
            ], 500);
341
        }
342
    }
343
344
    /**
345
     * Update the build configuration for a server.
346
     *
347
     * @param  \Illuminate\Http\Request  $request
348
     * @param  int                       $id
349
     * @return \Illuminate\Http\JsonResponse|array
350
     */
351
    public function build(Request $request, $id)
352
    {
353
        $this->authorize('server-edit-build', $request->apiKey());
354
355
        $repo = new ServerRepository;
356
        try {
357
            $server = $repo->changeBuild($id, $request->intersect([
358
                'allocation_id', 'add_allocations', 'remove_allocations',
359
                'memory', 'swap', 'io', 'cpu',
360
            ]));
361
362
            $fractal = Fractal::create()->item($server)->transformWith(new ServerTransformer($request));
363
            if ($request->input('include')) {
364
                $fractal->parseIncludes(explode(',', $request->input('include')));
365
            }
366
367
            return $fractal->withResourceName('server')->toArray();
368
        } catch (DisplayValidationException $ex) {
369
            return response()->json([
370
                'error' => json_decode($ex->getMessage()),
371
            ], 400);
372
        } catch (DisplayException $ex) {
373
            return response()->json([
374
                'error' => $ex->getMessage(),
375
            ], 400);
376
        } catch (TransferException $ex) {
377
            Log::warning($ex);
378
379
            return response()->json([
380
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
381
            ], 504);
382
        } catch (\Exception $ex) {
383
            Log::error($ex);
384
385
            return response()->json([
386
                'error' => 'An unhandled exception occured while attemping to modify the build settings for this server. Please try again.',
387
            ], 500);
388
        }
389
    }
390
391
    /**
392
     * Update the startup command as well as variables.
393
     *
394
     * @param  \Illuminate\Http\Request  $request
395
     * @param  int                       $id
396
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
397
     */
398
    public function startup(Request $request, $id)
399
    {
400
        $this->authorize('server-edit-startup', $request->apiKey());
401
402
        $repo = new ServerRepository;
403
        try {
404
            $repo->updateStartup($id, $request->all(), true);
405
406
            return response('', 204);
407
        } catch (DisplayValidationException $ex) {
408
            return response()->json([
409
                'error' => json_decode($ex->getMessage()),
410
            ], 400);
411
        } catch (DisplayException $ex) {
412
            return response()->json([
413
                'error' => $ex->getMessage(),
414
            ], 400);
415
        } catch (TransferException $ex) {
416
            Log::warning($ex);
417
418
            return response()->json([
419
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
420
            ], 504);
421
        } catch (\Exception $ex) {
422
            Log::error($ex);
423
424
            return response()->json([
425
                'error' => 'An unhandled exception occured while attemping to modify the startup settings for this server. Please try again.',
426
            ], 500);
427
        }
428
    }
429
}
430