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 (#206)
by
unknown
02:27
created

ServerController::lists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * Pterodactyl - Panel
4
 * Copyright (c) 2015 - 2016 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;
26
27
use Log;
28
use Pterodactyl\Models;
29
use Illuminate\Http\Request;
30
use Dingo\Api\Exception\ResourceException;
31
use Pterodactyl\Exceptions\DisplayException;
32
use Pterodactyl\Repositories\ServerRepository;
33
use Pterodactyl\Exceptions\DisplayValidationException;
34
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
35
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
36
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
37
38
/**
39
 * @Resource("Servers")
40
 */
41
class ServerController extends BaseController
42
{
43
    public function __construct()
44
    {
45
        //
46
    }
47
48
    /**
49
     * List All Servers.
50
     *
51
     * Lists all servers currently on the system.
52
     *
53
     * @Get("/servers/{?page}")
54
     * @Versions({"v1"})
55
     * @Parameters({
56
     *      @Parameter("page", type="integer", description="The page of results to view.", default=1)
57
     * })
58
     * @Response(200)
59
     */
60
    public function lists(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
61
    {
62
        return Models\Server::all()->toArray();
63
    }
64
65
    /**
66
     * Create Server.
67
     *
68
     * @Post("/servers")
69
     * @Versions({"v1"})
70
     * @Response(201)
71
     */
72 View Code Duplication
    public function create(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...
73
    {
74
        try {
75
            $server = new ServerRepository;
76
            $new = $server->create($request->all());
77
78
            return ['id' => $new];
79
        } catch (DisplayValidationException $ex) {
80
            throw new ResourceException('A validation error occured.', json_decode($ex->getMessage(), true));
81
        } catch (DisplayException $ex) {
82
            throw new ResourceException($ex->getMessage());
83
        } catch (\Exception $ex) {
84
            Log::error($ex);
85
            throw new BadRequestHttpException('There was an error while attempting to add this server to the system.');
86
        }
87
    }
88
89
    /**
90
     * List Specific Server.
91
     *
92
     * Lists specific fields about a server or all fields pertaining to that server.
93
     *
94
     * @Get("/servers/{id}{?fields}")
95
     * @Versions({"v1"})
96
     * @Parameters({
97
     *      @Parameter("id", type="integer", required=true, description="The ID of the server to get information on."),
98
     *      @Parameter("fields", type="string", required=false, description="A comma delimidated list of fields to include.")
99
     * })
100
     * @Response(200)
101
     */
102
    public function view(Request $request, $id)
103
    {
104
        $query = Models\Server::where('id', $id);
105
106 View Code Duplication
        if (! is_null($request->input('fields'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
107
            foreach (explode(',', $request->input('fields')) as $field) {
108
                if (! empty($field)) {
109
                    $query->addSelect($field);
110
                }
111
            }
112
        }
113
114
        try {
115
            if (! $query->first()) {
116
                throw new NotFoundHttpException('No server by that ID was found.');
117
            }
118
119
            // Requested Daemon Stats
120
            $server = $query->first();
121
            if ($request->input('daemon') === 'true') {
122
                $node = Models\Node::findOrFail($server->node);
123
                $client = Models\Node::guzzleRequest($node->id);
124
125
                $response = $client->request('GET', '/servers', [
126
                    'headers' => [
127
                        'X-Access-Token' => $node->daemonSecret,
128
                    ],
129
                ]);
130
131
                // Only return the daemon token if the request is using HTTPS
132
                if ($request->secure()) {
133
                    $server->daemon_token = $server->daemonSecret;
134
                }
135
                $server->daemon = json_decode($response->getBody())->{$server->uuid};
136
137
                return $server->toArray();
138
            }
139
140
            return $server->toArray();
141
        } catch (NotFoundHttpException $ex) {
142
            throw $ex;
143
        } catch (\GuzzleHttp\Exception\TransferException $ex) {
144
            // Couldn't hit the daemon, return what we have though.
145
            $server->daemon = [
0 ignored issues
show
Bug introduced by
The variable $server does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
146
                'error' => 'There was an error encountered while attempting to connect to the remote daemon.',
147
            ];
148
149
            return $server->toArray();
150
        } catch (\Exception $ex) {
151
            throw new BadRequestHttpException('There was an issue with the fields passed in the request.');
152
        }
153
    }
154
155
    /**
156
     * Update Server configuration.
157
     *
158
     * Updates display information on panel.
159
     *
160
     * @Patch("/servers/{id}/config")
161
     * @Versions({"v1"})
162
     * @Transaction({
163
     *      @Request({
164
     *          "owner": "[email protected]",
165
     *          "name": "New Name",
166
     *          "reset_token": true
167
     *      }, headers={"Authorization": "Bearer <token>"}),
168
     *      @Response(200, body={"name": "New Name"}),
169
     *      @Response(422)
170
     * })
171
     * @Parameters({
172
     *      @Parameter("id", type="integer", required=true, description="The ID of the server to modify.")
173
     * })
174
     */
175 View Code Duplication
    public function config(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...
176
    {
177
        try {
178
            $server = new ServerRepository;
179
            $server->updateDetails($id, $request->all());
180
181
            return Models\Server::findOrFail($id);
182
        } catch (DisplayValidationException $ex) {
183
            throw new ResourceException('A validation error occured.', json_decode($ex->getMessage(), true));
184
        } catch (DisplayException $ex) {
185
            throw new ResourceException($ex->getMessage());
186
        } catch (\Exception $ex) {
187
            throw new ServiceUnavailableHttpException('Unable to update server on system due to an error.');
188
        }
189
    }
190
191
    /**
192
     * Update Server Build Configuration.
193
     *
194
     * Updates server build information on panel and on node.
195
     *
196
     * @Patch("/servers/{id}/build")
197
     * @Versions({"v1"})
198
     * @Transaction({
199
     *      @Request({
200
     *          "default": "192.168.0.1:25565",
201
     *          "add_additional": [
202
     *              "192.168.0.1:25566",
203
     *              "192.168.0.1:25567",
204
     *              "192.168.0.1:25568"
205
     *          ],
206
     *          "remove_additional": [],
207
     *          "memory": 1024,
208
     *          "swap": 0,
209
     *          "io": 500,
210
     *          "cpu": 0,
211
     *          "disk": 1024
212
     *      }, headers={"Authorization": "Bearer <token>"}),
213
     *      @Response(200, body={"name": "New Name"}),
214
     *      @Response(422)
215
     * })
216
     * @Parameters({
217
     *      @Parameter("id", type="integer", required=true, description="The ID of the server to modify.")
218
     * })
219
     */
220 View Code Duplication
    public function build(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...
221
    {
222
        try {
223
            $server = new ServerRepository;
224
            $server->changeBuild($id, $request->all());
225
226
            return Models\Server::findOrFail($id);
227
        } catch (DisplayValidationException $ex) {
228
            throw new ResourceException('A validation error occured.', json_decode($ex->getMessage(), true));
229
        } catch (DisplayException $ex) {
230
            throw new ResourceException($ex->getMessage());
231
        } catch (\Exception $ex) {
232
            throw new ServiceUnavailableHttpException('Unable to update server on system due to an error.');
233
        }
234
    }
235
236
    /**
237
     * Suspend Server.
238
     *
239
     * @Post("/servers/{id}/suspend")
240
     * @Versions({"v1"})
241
     * @Parameters({
242
     *      @Parameter("id", type="integer", required=true, description="The ID of the server."),
243
     * })
244
     * @Response(204)
245
     */
246 View Code Duplication
    public function suspend(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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...
247
    {
248
        try {
249
            $server = new ServerRepository;
250
            $server->suspend($id);
251
252
            return $this->response->noContent();
253
        } catch (DisplayException $ex) {
254
            throw new ResourceException($ex->getMessage());
255
        } catch (\Exception $ex) {
256
            throw new ServiceUnavailableHttpException('An error occured while attempting to suspend this server instance.');
257
        }
258
    }
259
260
    /**
261
     * Unsuspend Server.
262
     *
263
     * @Post("/servers/{id}/unsuspend")
264
     * @Versions({"v1"})
265
     * @Parameters({
266
     *      @Parameter("id", type="integer", required=true, description="The ID of the server."),
267
     * })
268
     * @Response(204)
269
     */
270 View Code Duplication
    public function unsuspend(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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...
271
    {
272
        try {
273
            $server = new ServerRepository;
274
            $server->unsuspend($id);
275
276
            return $this->response->noContent();
277
        } catch (DisplayException $ex) {
278
            throw new ResourceException($ex->getMessage());
279
        } catch (\Exception $ex) {
280
            throw new ServiceUnavailableHttpException('An error occured while attempting to unsuspend this server instance.');
281
        }
282
    }
283
284
    /**
285
     * Delete Server.
286
     *
287
     * @Delete("/servers/{id}/{force}")
288
     * @Versions({"v1"})
289
     * @Parameters({
290
     *      @Parameter("id", type="integer", required=true, description="The ID of the server."),
291
     *      @Parameter("force", type="string", required=false, description="Use 'force' if the server should be removed regardless of daemon response."),
292
     * })
293
     * @Response(204)
294
     */
295 View Code Duplication
    public function delete(Request $request, $id, $force = null)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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...
296
    {
297
        try {
298
            $server = new ServerRepository;
299
            $server->deleteServer($id, $force);
300
301
            return $this->response->noContent();
302
        } catch (DisplayException $ex) {
303
            throw new ResourceException($ex->getMessage());
304
        } catch (\Exception $e) {
305
            throw new ServiceUnavailableHttpException('An error occured while attempting to delete this server.');
306
        }
307
    }
308
}
309