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
05:00 queued 02:14
created

ServerController::suspend()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 34
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
rs 8.439
c 0
b 0
f 0
cc 5
eloc 25
nc 8
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
117
            return response()->json([
118
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
119
            ], 504);
120
        } catch (\Exception $ex) {
121
            Log::error($ex);
122
123
            return response()->json([
124
                'error' => 'An unhandled exception occured while attemping to add this server. Please try again.',
125
            ], 500);
126
        }
127
    }
128
129
    /**
130
     * Delete a server from the system.
131
     *
132
     * @param  \Illuminate\Http\Request  $request
133
     * @param  int                       $id
134
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
135
     */
136
    public function delete(Request $request, $id)
137
    {
138
        $this->authorize('server-delete', $request->apiKey());
139
140
        $repo = new ServerRepository;
141
        try {
142
            $repo->delete($id, $request->has('force_delete'));
143
144
            return response('', 204);
145
        } catch (DisplayException $ex) {
146
            return response()->json([
147
                'error' => $ex->getMessage(),
148
            ], 400);
149
        } catch (TransferException $ex) {
150
            Log::warning($ex);
151
152
            return response()->json([
153
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
154
            ], 504);
155
        } catch (\Exception $ex) {
156
            Log::error($ex);
157
158
            return response()->json([
159
                'error' => 'An unhandled exception occured while attemping to add this server. Please try again.',
160
            ], 500);
161
        }
162
    }
163
164
    /**
165
     * Update the details for a server.
166
     *
167
     * @param  \Illuminate\Http\Request  $request
168
     * @param  int                       $id
169
     * @return \Illuminate\Http\JsonResponse|array
170
     */
171
    public function details(Request $request, $id)
172
    {
173
        $this->authorize('server-edit-details', $request->apiKey());
174
175
        $repo = new ServerRepository;
176
        try {
177
            $server = $repo->updateDetails($id, $request->intersect([
178
                'owner_id', 'name', 'description', 'reset_token',
179
            ]));
180
181
            $fractal = Fractal::create()->item($server)->transformWith(new ServerTransformer($request));
182
            if ($request->input('include')) {
183
                $fractal->parseIncludes(explode(',', $request->input('include')));
184
            }
185
186
            return $fractal->withResourceName('server')->toArray();
187
        } catch (DisplayValidationException $ex) {
188
            return response()->json([
189
                'error' => json_decode($ex->getMessage()),
190
            ], 400);
191
        } catch (DisplayException $ex) {
192
            return response()->json([
193
                'error' => $ex->getMessage(),
194
            ], 400);
195
        } catch (\Exception $ex) {
196
            Log::error($ex);
197
198
            return response()->json([
199
                'error' => 'An unhandled exception occured while attemping to modify this server. Please try again.',
200
            ], 500);
201
        }
202
    }
203
204
    /**
205
     * Set the new docker container for a server.
206
     *
207
     * @param  \Illuminate\Http\Request  $request
208
     * @param  int                       $id
209
     * @return \Illuminate\Http\RedirectResponse|array
210
     */
211
    public function container(Request $request, $id)
212
    {
213
        $this->authorize('server-edit-container', $request->apiKey());
214
215
        $repo = new ServerRepository;
216
        try {
217
            $server = $repo->updateContainer($id, $request->intersect('docker_image'));
218
219
            $fractal = Fractal::create()->item($server)->transformWith(new ServerTransformer($request));
220
            if ($request->input('include')) {
221
                $fractal->parseIncludes(explode(',', $request->input('include')));
222
            }
223
224
            return $fractal->withResourceName('server')->toArray();
225
        } catch (DisplayValidationException $ex) {
226
            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...
227
                'error' => json_decode($ex->getMessage()),
228
            ], 400);
229
        } catch (TransferException $ex) {
230
            Log::warning($ex);
231
232
            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...
233
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
234
            ], 504);
235
        } catch (\Exception $ex) {
236
            Log::error($ex);
237
238
            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...
239
                'error' => 'An unhandled exception occured while attemping to modify this server container. Please try again.',
240
            ], 500);
241
        }
242
    }
243
244
    /**
245
     * Toggles the install status for a server.
246
     *
247
     * @param  \Illuminate\Http\Request  $request
248
     * @param  int                       $id
249
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
250
     */
251 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...
252
    {
253
        $this->authorize('server-install', $request->apiKey());
254
255
        $repo = new ServerRepository;
256
        try {
257
            $repo->toggleInstall($id);
258
259
            return response('', 204);
260
        } catch (DisplayException $ex) {
261
            return response()->json([
262
                'error' => $ex->getMessage(),
263
            ], 400);
264
        } catch (\Exception $ex) {
265
            Log::error($ex);
266
267
            return response()->json([
268
                'error' => 'An unhandled exception occured while attemping to toggle the install status for this server. Please try again.',
269
            ], 500);
270
        }
271
    }
272
273
    /**
274
     * Setup a server to have a container rebuild.
275
     *
276
     * @param  \Illuminate\Http\Request  $request
277
     * @param  int                       $id
278
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
279
     */
280
    public function rebuild(Request $request, $id)
281
    {
282
        $this->authorize('server-rebuild', $request->apiKey());
283
        $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...
284
285
        try {
286
            $server->node->guzzleClient([
287
                'X-Access-Server' => $server->uuid,
288
                'X-Access-Token' => $server->node->daemonSecret,
289
            ])->request('POST', '/server/rebuild');
290
291
            return response('', 204);
292
        } catch (TransferException $ex) {
293
            Log::warning($ex);
294
295
            return response()->json([
296
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
297
            ], 504);
298
        }
299
    }
300
301
    /**
302
     * Manage the suspension status for a server.
303
     *
304
     * @param  \Illuminate\Http\Request  $request
305
     * @param  int                       $id
306
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
307
     */
308
    public function suspend(Request $request, $id)
309
    {
310
        $this->authorize('server-suspend', $request->apiKey());
311
312
        $repo = new ServerRepository;
313
        $action = $request->input('action');
314
        if (! in_array($action, ['suspend', 'unsuspend'])) {
315
            return response()->json([
316
                'error' => 'The action provided was invalid. Action should be one of: suspend, unsuspend.',
317
            ], 400);
318
        }
319
320
        try {
321
            $repo->$action($id);
322
323
            return response('', 204);
324
        } catch (DisplayException $ex) {
325
            return response()->json([
326
                'error' => $ex->getMessage(),
327
            ], 400);
328
        } catch (TransferException $ex) {
329
            Log::warning($ex);
330
331
            return response()->json([
332
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
333
            ], 504);
334
        } catch (\Exception $ex) {
335
            Log::error($ex);
336
337
            return response()->json([
338
                'error' => 'An unhandled exception occured while attemping to ' . $action . ' this server. Please try again.',
339
            ], 500);
340
        }
341
    }
342
343
    /**
344
     * Update the build configuration for a server.
345
     *
346
     * @param  \Illuminate\Http\Request  $request
347
     * @param  int                       $id
348
     * @return \Illuminate\Http\JsonResponse|array
349
     */
350
    public function build(Request $request, $id)
351
    {
352
        $this->authorize('server-edit-build', $request->apiKey());
353
354
        $repo = new ServerRepository;
355
        try {
356
            $server = $repo->changeBuild($id, $request->intersect([
357
                'allocation_id', 'add_allocations', 'remove_allocations',
358
                'memory', 'swap', 'io', 'cpu',
359
            ]));
360
361
            $fractal = Fractal::create()->item($server)->transformWith(new ServerTransformer($request));
362
            if ($request->input('include')) {
363
                $fractal->parseIncludes(explode(',', $request->input('include')));
364
            }
365
366
            return $fractal->withResourceName('server')->toArray();
367
        } catch (DisplayValidationException $ex) {
368
            return response()->json([
369
                'error' => json_decode($ex->getMessage()),
370
            ], 400);
371
        } catch (DisplayException $ex) {
372
            return response()->json([
373
                'error' => $ex->getMessage(),
374
            ], 400);
375
        } catch (TransferException $ex) {
376
            Log::warning($ex);
377
378
            return response()->json([
379
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
380
            ], 504);
381
        } catch (\Exception $ex) {
382
            Log::error($ex);
383
384
            return response()->json([
385
                'error' => 'An unhandled exception occured while attemping to modify the build settings for this server. Please try again.',
386
            ], 500);
387
        }
388
    }
389
390
    /**
391
     * Update the startup command as well as variables.
392
     *
393
     * @param  \Illuminate\Http\Request  $request
394
     * @param  int                       $id
395
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
396
     */
397
    public function startup(Request $request, $id)
398
    {
399
        $this->authorize('server-edit-startup', $request->apiKey());
400
401
        $repo = new ServerRepository;
402
        try {
403
            $repo->updateStartup($id, $request->all(), true);
404
405
            return response('', 204);
406
        } catch (DisplayValidationException $ex) {
407
            return response()->json([
408
                'error' => json_decode($ex->getMessage()),
409
            ], 400);
410
        } catch (DisplayException $ex) {
411
            return response()->json([
412
                'error' => $ex->getMessage(),
413
            ], 400);
414
        } catch (TransferException $ex) {
415
            Log::warning($ex);
416
417
            return response()->json([
418
                'error' => 'A TransferException was encountered while trying to contact the daemon, please ensure it is online and accessible. This error has been logged.',
419
            ], 504);
420
        } catch (\Exception $ex) {
421
            Log::error($ex);
422
423
            return response()->json([
424
                'error' => 'An unhandled exception occured while attemping to modify the startup settings for this server. Please try again.',
425
            ], 500);
426
        }
427
    }
428
}
429