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.
Completed
Pull Request — develop (#371)
by Dane
02:54
created

ServerController::details()   B

Complexity

Conditions 5
Paths 20

Size

Total Lines 31
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.439
c 0
b 0
f 0
cc 5
eloc 23
nc 20
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 Fractal;
28
use Illuminate\Http\Request;
29
use Pterodactyl\Models\Server;
30
use GuzzleHttp\Exception\TransferException;
31
use Pterodactyl\Exceptions\DisplayException;
32
use Pterodactyl\Http\Controllers\Controller;
33
use Pterodactyl\Repositories\ServerRepository;
34
use Pterodactyl\Transformers\Admin\ServerTransformer;
35
use Pterodactyl\Exceptions\DisplayValidationException;
36
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
37
38
class ServerController extends Controller
39
{
40
    /**
41
     * Controller to handle returning all servers on the system.
42
     *
43
     * @param  \Illuminate\Http\Request  $request
44
     * @return array
45
     */
46 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...
47
    {
48
        $this->authorize('server-list', $request->apiKey());
49
50
        $servers = Server::paginate(config('pterodactyl.paginate.api.servers'));
51
        $fractal = Fractal::create()->collection($servers)
52
            ->transformWith(new ServerTransformer($request))
53
            ->withResourceName('user')
54
            ->paginateWith(new IlluminatePaginatorAdapter($servers));
55
56
        if (config('pterodactyl.api.include_on_list') && $request->input('include')) {
57
            $fractal->parseIncludes(explode(',', $request->input('include')));
58
        }
59
60
        return $fractal->toArray();
61
    }
62
63
    /**
64
     * Controller to handle returning information on a single server.
65
     *
66
     * @param  \Illuminate\Http\Request  $request
67
     * @param  int                       $id
68
     * @return array
69
     */
70 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...
71
    {
72
        $this->authorize('server-view', $request->apiKey());
73
74
        $server = Server::findOrFail($id);
75
        $fractal = Fractal::create()->item($server);
76
77
        if ($request->input('include')) {
78
            $fractal->parseIncludes(explode(',', $request->input('include')));
79
        }
80
81
        return $fractal->transformWith(new ServerTransformer($request))
82
            ->withResourceName('server')
83
            ->toArray();
84
    }
85
86
    /**
87
     * Create a new server on the system.
88
     *
89
     * @param  \Illuminate\Http\Request  $request
90
     * @return \Illuminate\Http\JsonResponse|array
91
     */
92
    public function store(Request $request)
93
    {
94
        $this->authorize('server-create', $request->apiKey());
95
96
        $repo = new ServerRepository;
97
        try {
98
            $server = $repo->create($request->all());
99
100
            $fractal = Fractal::create()->item($server)->transformWith(new ServerTransformer($request));
101
            if ($request->input('include')) {
102
                $fractal->parseIncludes(explode(',', $request->input('include')));
103
            }
104
105
            return $fractal->withResourceName('server')->toArray();
106
        } catch (DisplayValidationException $ex) {
107
            return response()->json([
108
                'error' => json_decode($ex->getMessage()),
109
            ], 400);
110
        } catch (DisplayException $ex) {
111
            return response()->json([
112
                'error' => $ex->getMessage(),
113
            ], 400);
114
        } catch (TransferException $ex) {
115
            Log::warning($ex);
116
            return response()->json([
117
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
118
            ], 504);
119
        } catch (\Exception $ex) {
120
            Log::error($ex);
121
            return response()->json([
122
                'error' => 'An unhandled exception occured while attemping to add this server. Please try again.',
123
            ], 500);
124
        }
125
    }
126
127
    /**
128
     * Delete a server from the system.
129
     *
130
     * @param  \Illuminate\Http\Request  $request
131
     * @param  int                       $id
132
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
133
     */
134
    public function delete(Request $request, $id)
135
    {
136
        $this->authorize('server-delete', $request->apiKey());
137
138
        $repo = new ServerRepository;
139
        try {
140
            $repo->delete($id, $request->has('force_delete'));
141
142
            return response('', 204);
143
        } catch (DisplayException $ex) {
144
            return response()->json([
145
                'error' => $ex->getMessage(),
146
            ], 400);
147
        } catch (TransferException $ex) {
148
            Log::warning($ex);
149
            return response()->json([
150
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
151
            ], 504);
152
        } catch (\Exception $ex) {
153
            Log::error($ex);
154
            return response()->json([
155
                'error' => 'An unhandled exception occured while attemping to add this server. Please try again.',
156
            ], 500);
157
        }
158
    }
159
160
        /**
161
     * Update the details for a server.
162
     *
163
     * @param  \Illuminate\Http\Request  $request
164
     * @param  int                       $id
165
     * @return \Illuminate\Http\JsonResponse|array
166
     */
167
    public function details(Request $request, $id)
168
    {
169
        $this->authorize('server-edit-details', $request->apiKey());
170
171
        $repo = new ServerRepository;
172
        try {
173
            $server = $repo->updateDetails($id, $request->intersect([
174
                'owner_id', 'name', 'description', 'reset_token',
175
            ]));
176
177
            $fractal = Fractal::create()->item($server)->transformWith(new ServerTransformer($request));
178
            if ($request->input('include')) {
179
                $fractal->parseIncludes(explode(',', $request->input('include')));
180
            }
181
182
            return $fractal->withResourceName('server')->toArray();
183
        } catch (DisplayValidationException $ex) {
184
            return response()->json([
185
                'error' => json_decode($ex->getMessage()),
186
            ], 400);
187
        } catch (DisplayException $ex) {
188
            return response()->json([
189
                'error' => $ex->getMessage(),
190
            ], 400);
191
        } catch (\Exception $ex) {
192
            Log::error($ex);
193
            return response()->json([
194
                'error' => 'An unhandled exception occured while attemping to modify this server. Please try again.',
195
            ], 500);
196
        }
197
    }
198
199
    /**
200
     * Set the new docker container for a server.
201
     *
202
     * @param  \Illuminate\Http\Request  $request
203
     * @param  int                       $id
204
     * @return \Illuminate\Http\RedirectResponse|array
205
     */
206
    public function container(Request $request, $id)
207
    {
208
        $this->authorize('server-edit-container', $request->apiKey());
209
210
        $repo = new ServerRepository;
211
        try {
212
            $server = $repo->updateContainer($id, $request->intersect('docker_image'));
213
214
            $fractal = Fractal::create()->item($server)->transformWith(new ServerTransformer($request));
215
            if ($request->input('include')) {
216
                $fractal->parseIncludes(explode(',', $request->input('include')));
217
            }
218
219
            return $fractal->withResourceName('server')->toArray();
220
        } catch (DisplayValidationException $ex) {
221
            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...
222
                'error' => json_decode($ex->getMessage()),
223
            ], 400);
224
        } catch (TransferException $ex) {
225
            Log::warning($ex);
226
            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...
227
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
228
            ], 504);
229
        } catch (\Exception $ex) {
230
            Log::error($ex);
231
            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...
232
                'error' => 'An unhandled exception occured while attemping to modify this server container. Please try again.',
233
            ], 500);
234
        }
235
    }
236
237
    /**
238
     * Toggles the install status for a server.
239
     *
240
     * @param  \Illuminate\Http\Request  $request
241
     * @param  int                       $id
242
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
243
     */
244 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...
245
    {
246
        $this->authorize('server-install', $request->apiKey());
247
248
        $repo = new ServerRepository;
249
        try {
250
            $repo->toggleInstall($id);
251
252
            return response('', 204);
253
        } catch (DisplayException $ex) {
254
            return response()->json([
255
                'error' => $ex->getMessage(),
256
            ], 400);
257
        } catch (\Exception $ex) {
258
            Log::error($ex);
259
            return response()->json([
260
                'error' => 'An unhandled exception occured while attemping to toggle the install status for this server. Please try again.',
261
            ], 500);
262
        }
263
    }
264
265
    /**
266
     * Setup a server to have a container rebuild.
267
     *
268
     * @param  \Illuminate\Http\Request  $request
269
     * @param  int                       $id
270
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
271
     */
272
    public function rebuild(Request $request, $id)
273
    {
274
        $this->authorize('server-rebuild', $request->apiKey());
275
        $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...
276
277
        try {
278
            $server->node->guzzleClient([
279
                'X-Access-Server' => $server->uuid,
280
                'X-Access-Token' => $server->node->daemonSecret,
281
            ])->request('POST', '/server/rebuild');
282
283
            return response('', 204);
284
        } catch (TransferException $ex) {
285
            Log::warning($ex);
286
            return response()->json([
287
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
288
            ], 504);
289
        }
290
    }
291
292
    /**
293
     * Manage the suspension status for a server.
294
     *
295
     * @param  \Illuminate\Http\Request  $request
296
     * @param  int                       $id
297
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
298
     */
299
    public function suspend(Request $request, $id)
300
    {
301
        $this->authorize('server-suspend', $request->apiKey());
302
303
        $repo = new ServerRepository;
304
        $action = $request->input('action');
305
        if (! in_array($action, ['suspend', 'unsuspend'])) {
306
            return response()->json([
307
                'error' => 'The action provided was invalid. Action should be one of: suspend, unsuspend.',
308
            ], 400);
309
        }
310
311
        try {
312
            $repo->$action($id);
313
314
            return response('', 204);
315
        } catch (DisplayException $ex) {
316
            return response()->json([
317
                'error' => $ex->getMessage(),
318
            ], 400);
319
        } catch (TransferException $ex) {
320
            Log::warning($ex);
321
            return response()->json([
322
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
323
            ], 504);
324
        } catch (\Exception $ex) {
325
            Log::error($ex);
326
            return response()->json([
327
                'error' => 'An unhandled exception occured while attemping to ' . $action . ' this server. Please try again.',
328
            ], 500);
329
        }
330
    }
331
332
    /**
333
     * Update the build configuration for a server.
334
     *
335
     * @param  \Illuminate\Http\Request  $request
336
     * @param  int                       $id
337
     * @return \Illuminate\Http\JsonResponse|array
338
     */
339
    public function build(Request $request, $id)
340
    {
341
        $this->authorize('server-edit-build', $request->apiKey());
342
343
        $repo = new ServerRepository;
344
        try {
345
            $server = $repo->changeBuild($id, $request->intersect([
346
                'allocation_id', 'add_allocations', 'remove_allocations',
347
                'memory', 'swap', 'io', 'cpu',
348
            ]));
349
350
            $fractal = Fractal::create()->item($server)->transformWith(new ServerTransformer($request));
351
            if ($request->input('include')) {
352
                $fractal->parseIncludes(explode(',', $request->input('include')));
353
            }
354
355
            return $fractal->withResourceName('server')->toArray();
356
        } catch (DisplayValidationException $ex) {
357
            return response()->json([
358
                'error' => json_decode($ex->getMessage()),
359
            ], 400);
360
        } catch (DisplayException $ex) {
361
            return response()->json([
362
                'error' => $ex->getMessage(),
363
            ], 400);
364
        } catch (TransferException $ex) {
365
            Log::warning($ex);
366
            return response()->json([
367
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
368
            ], 504);
369
        } catch (\Exception $ex) {
370
            Log::error($ex);
371
            return response()->json([
372
                'error' => 'An unhandled exception occured while attemping to modify the build settings for this server. Please try again.',
373
            ], 500);
374
        }
375
    }
376
377
    /**
378
     * Update the startup command as well as variables.
379
     *
380
     * @param  \Illuminate\Http\Request  $request
381
     * @param  int                       $id
382
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
383
     */
384
    public function startup(Request $request, $id)
385
    {
386
        $this->authorize('server-edit-startup', $request->apiKey());
387
388
        $repo = new ServerRepository;
389
        try {
390
            $repo->updateStartup($id, $request->all(), true);
391
392
            return response('', 204);
393
        } catch (DisplayValidationException $ex) {
394
            return response()->json([
395
                'error' => json_decode($ex->getMessage()),
396
            ], 400);
397
        } catch (DisplayException $ex) {
398
            return response()->json([
399
                'error' => $ex->getMessage(),
400
            ], 400);
401
        } catch (TransferException $ex) {
402
            Log::warning($ex);
403
            return response()->json([
404
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
405
            ], 504);
406
        } catch (\Exception $ex) {
407
            Log::error($ex);
408
            return response()->json([
409
                'error' => 'An unhandled exception occured while attemping to modify the startup settings for this server. Please try again.',
410
            ], 500);
411
        }
412
    }
413
}
414