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 (#286)
by Dane
08:45 queued 05:44
created

NodesController::postAllocations()   D

Complexity

Conditions 11
Paths 196

Size

Total Lines 48
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 48
rs 4.9629
c 0
b 0
f 0
cc 11
eloc 32
nc 196
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Admin;
26
27
use DB;
28
use Log;
29
use Alert;
30
use Carbon;
31
use Validator;
32
use Pterodactyl\Models;
33
use Illuminate\Http\Request;
34
use Pterodactyl\Exceptions\DisplayException;
35
use Pterodactyl\Http\Controllers\Controller;
36
use Pterodactyl\Repositories\NodeRepository;
37
use Pterodactyl\Exceptions\DisplayValidationException;
38
39
class NodesController extends Controller
40
{
41
    /**
42
     * Controller Constructor.
43
     */
44
    public function __construct()
45
    {
46
        //
47
    }
48
49
    public function getScript(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...
50
    {
51
        return response()->view('admin.nodes.remote.deploy', [
52
            'node' => Models\Node::findOrFail($id),
53
        ])->header('Content-Type', 'text/plain');
54
    }
55
56
    public function getIndex(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...
57
    {
58
        return view('admin.nodes.index', [
59
            'nodes' => Models\Node::with('location')->withCount('servers')->paginate(20),
0 ignored issues
show
Bug introduced by
The method withCount 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...
60
        ]);
61
    }
62
63
    public function getNew(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...
64
    {
65
        if (! Models\Location::all()->count()) {
66
            Alert::warning('You must add a location before you can add a new node.')->flash();
67
68
            return redirect()->route('admin.locations');
69
        }
70
71
        return view('admin.nodes.new', [
72
            'locations' => Models\Location::all(),
73
        ]);
74
    }
75
76
    public function postNew(Request $request)
77
    {
78
        try {
79
            $repo = new NodeRepository;
80
            $node = $repo->create($request->only([
81
                'name',
82
                'location',
83
                'public',
84
                'fqdn',
85
                'scheme',
86
                'memory',
87
                'memory_overallocate',
88
                'disk',
89
                'disk_overallocate',
90
                'daemonBase',
91
                'daemonSFTP',
92
                'daemonListen',
93
            ]));
94
            Alert::success('Successfully created new node that can be configured automatically on your remote machine by visiting the configuration tab. <strong>Before you can add any servers you need to first assign some IP addresses and ports.</strong>')->flash();
95
96
            return redirect()->route('admin.nodes.view', [
97
                'id' => $node->id,
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Pterodactyl\Models\Node>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
98
                'tab' => 'tab_allocation',
99
            ]);
100
        } catch (DisplayValidationException $e) {
101
            return redirect()->route('admin.nodes.new')->withErrors(json_decode($e->getMessage()))->withInput();
102
        } catch (DisplayException $e) {
103
            Alert::danger($e->getMessage())->flash();
104
        } catch (\Exception $e) {
105
            Log::error($e);
106
            Alert::danger('An unhandled exception occured while attempting to add this node. Please try again.')->flash();
107
        }
108
109
        return redirect()->route('admin.nodes.new')->withInput();
110
    }
111
112
    public function getView(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...
113
    {
114
        $node = Models\Node::with(
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...
115
            'servers.user', 'servers.service',
116
            'servers.allocations', 'location'
117
        )->findOrFail($id);
118
        $node->setRelation('allocations', $node->allocations()->paginate(40));
119
120
        return view('admin.nodes.view', [
121
            'node' => $node,
122
            'stats' => Models\Server::select(DB::raw('SUM(memory) as memory, SUM(disk) as disk'))->where('node_id', $node->id)->first(),
123
            'locations' => Models\Location::all(),
124
        ]);
125
    }
126
127
    public function postView(Request $request, $id)
128
    {
129
        try {
130
            $node = new NodeRepository;
131
            $node->update($id, $request->only([
132
                'name', 'location', 'public',
133
                'fqdn', 'scheme', 'memory',
134
                'memory_overallocate', 'disk',
135
                'disk_overallocate', 'upload_size',
136
                'daemonBase', 'daemonSFTP',
137
                'daemonListen', 'reset_secret',
138
            ]));
139
            Alert::success('Successfully update this node\'s information. If you changed any daemon settings you will need to restart it now.')->flash();
140
141
            return redirect()->route('admin.nodes.view', [
142
                'id' => $id,
143
                'tab' => 'tab_settings',
144
            ]);
145
        } catch (DisplayValidationException $e) {
146
            return redirect()->route('admin.nodes.view', $id)->withErrors(json_decode($e->getMessage()))->withInput();
147
        } catch (DisplayException $e) {
148
            Alert::danger($e->getMessage())->flash();
149
        } catch (\Exception $e) {
150
            Log::error($e);
151
            Alert::danger('An unhandled exception occured while attempting to edit this node. Please try again.')->flash();
152
        }
153
154
        return redirect()->route('admin.nodes.view', [
155
            'id' => $id,
156
            'tab' => 'tab_settings',
157
        ])->withInput();
158
    }
159
160
    public function deallocateSingle(Request $request, $node, $allocation)
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...
161
    {
162
        $query = Models\Allocation::where('node', $node)->whereNull('assigned_to')->where('id', $allocation)->delete();
163
        if ((int) $query === 0) {
164
            return response()->json([
165
                'error' => 'Unable to find an allocation matching those details to delete.',
166
            ], 400);
167
        }
168
169
        return response('', 204);
170
    }
171
172
    public function deallocateBlock(Request $request, $node)
173
    {
174
        $query = Models\Allocation::where('node', $node)->whereNull('assigned_to')->where('ip', $request->input('ip'))->delete();
175
        if ((int) $query === 0) {
176
            Alert::danger('There was an error while attempting to delete allocations on that IP.')->flash();
177
178
            return redirect()->route('admin.nodes.view', [
179
                'id' => $node,
180
                'tab' => 'tab_allocations',
181
            ]);
182
        }
183
        Alert::success('Deleted all unallocated ports for <code>' . $request->input('ip') . '</code>.')->flash();
184
185
        return redirect()->route('admin.nodes.view', [
186
            'id' => $node,
187
            'tab' => 'tab_allocation',
188
        ]);
189
    }
190
191
    public function setAlias(Request $request, $node)
0 ignored issues
show
Unused Code introduced by
The parameter $node 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...
192
    {
193
        if (! $request->input('allocation')) {
194
            return response('Missing required parameters.', 422);
195
        }
196
197
        try {
198
            $update = Models\Allocation::findOrFail($request->input('allocation'));
199
            $update->ip_alias = (empty($request->input('alias'))) ? null : $request->input('alias');
200
            $update->save();
201
202
            return response('', 204);
203
        } catch (\Exception $ex) {
204
            throw $ex;
205
        }
206
    }
207
208
    public function getAllocationsJson(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...
209
    {
210
        $allocations = Models\Allocation::select('ip')->where('node', $id)->groupBy('ip')->get();
211
212
        return response()->json($allocations);
213
    }
214
215
    public function postAllocations(Request $request, $id)
216
    {
217
        $validator = Validator::make($request->all(), [
218
            'allocate_ip.*' => 'required|string',
219
            'allocate_port.*' => 'required',
220
        ]);
221
222
        if ($validator->fails()) {
223
            return redirect()->route('admin.nodes.view', [
224
                'id' => $id,
225
                'tab' => 'tab_allocation',
226
            ])->withErrors($validator->errors())->withInput();
227
        }
228
229
        $processedData = [];
230
        foreach ($request->input('allocate_ip') as $ip) {
0 ignored issues
show
Bug introduced by
The expression $request->input('allocate_ip') of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
231
            if (! array_key_exists($ip, $processedData)) {
232
                $processedData[$ip] = [];
233
            }
234
        }
235
236
        foreach ($request->input('allocate_port') as $portid => $ports) {
0 ignored issues
show
Bug introduced by
The expression $request->input('allocate_port') of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
237
            if (array_key_exists($portid, $request->input('allocate_ip'))) {
238
                $json = json_decode($ports);
239
                if (json_last_error() === 0 && ! empty($json)) {
240
                    foreach ($json as &$parsed) {
241
                        array_push($processedData[$request->input('allocate_ip')[$portid]], $parsed->value);
242
                    }
243
                }
244
            }
245
        }
246
247
        try {
248
            $node = new NodeRepository;
249
            $node->addAllocations($id, $processedData);
250
            Alert::success('Successfully added new allocations to this node.')->flash();
251
        } catch (DisplayException $e) {
252
            Alert::danger($e->getMessage())->flash();
253
        } catch (\Exception $e) {
254
            Log::error($e);
255
            Alert::danger('An unhandled exception occured while attempting to add allocations this node. Please try again.')->flash();
256
        } finally {
257
            return redirect()->route('admin.nodes.view', [
258
                'id' => $id,
259
                'tab' => 'tab_allocation',
260
            ]);
261
        }
262
    }
263
264 View Code Duplication
    public function deleteNode(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...
265
    {
266
        try {
267
            $repo = new NodeRepository;
268
            $repo->delete($id);
269
            Alert::success('Successfully deleted the requested node from the panel.')->flash();
270
271
            return redirect()->route('admin.nodes');
272
        } catch (DisplayException $e) {
273
            Alert::danger($e->getMessage())->flash();
274
        } catch (\Exception $e) {
275
            Log::error($e);
276
            Alert::danger('An unhandled exception occured while attempting to delete this node. Please try again.')->flash();
277
        }
278
279
        return redirect()->route('admin.nodes.view', [
280
            'id' => $id,
281
            'tab' => 'tab_delete',
282
        ]);
283
    }
284
285
    public function getConfigurationToken(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...
286
    {
287
        // Check if Node exists. Will lead to 404 if not.
288
        Models\Node::findOrFail($id);
289
290
        // Create a token
291
        $token = new Models\NodeConfigurationToken();
292
        $token->node = $id;
0 ignored issues
show
Documentation introduced by
The property node does not exist on object<Pterodactyl\Models\NodeConfigurationToken>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
293
        $token->token = str_random(32);
0 ignored issues
show
Documentation introduced by
The property token does not exist on object<Pterodactyl\Models\NodeConfigurationToken>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
294
        $token->expires_at = Carbon::now()->addMinutes(5); // Expire in 5 Minutes
0 ignored issues
show
Documentation introduced by
The property expires_at does not exist on object<Pterodactyl\Models\NodeConfigurationToken>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
295
        $token->save();
296
297
        $token_response = [
298
            'token' => $token->token,
0 ignored issues
show
Documentation introduced by
The property token does not exist on object<Pterodactyl\Models\NodeConfigurationToken>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
299
            'expires_at' => $token->expires_at->toDateTimeString(),
0 ignored issues
show
Documentation introduced by
The property expires_at does not exist on object<Pterodactyl\Models\NodeConfigurationToken>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
300
        ];
301
302
        return response()->json($token_response, 200);
303
    }
304
}
305