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
04:53 queued 02:03
created

SubuserRepository   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 286
Duplicated Lines 8.74 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 24
lcom 1
cbo 7
dl 25
loc 286
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
C create() 13 87 11
B delete() 0 36 4
C update() 12 63 8

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\Repositories;
26
27
use DB;
28
use Validator;
29
use Pterodactyl\Models;
30
use Pterodactyl\Services\UuidService;
31
use Pterodactyl\Exceptions\DisplayException;
32
use Pterodactyl\Exceptions\DisplayValidationException;
33
34
class SubuserRepository
35
{
36
    /**
37
     * Core permissions required for every subuser on the daemon.
38
     * Without this we cannot connect the websocket or get basic
39
     * information about the server.
40
     * @var array
41
     */
42
    protected $coreDaemonPermissions = [
43
        's:get',
44
        's:console',
45
    ];
46
47
    /**
48
     * Allowed permissions and their related daemon permission.
49
     * @var array
50
     */
51
    protected $permissions = [
52
        // Power Permissions
53
        'power-start' => 's:power:start',
54
        'power-stop' => 's:power:stop',
55
        'power-restart' => 's:power:restart',
56
        'power-kill' => 's:power:kill',
57
58
        // Commands
59
        'send-command' => 's:command',
60
61
        // File Manager
62
        'list-files' => 's:files:get',
63
        'edit-files' => 's:files:read',
64
        'save-files' => 's:files:post',
65
        'create-files' => 's:files:post',
66
        'download-files' => null,
67
        'upload-files' => 's:files:upload',
68
        'delete-files' => 's:files:delete',
69
        'move-files' => 's:files:move',
70
        'copy-files' => 's:files:copy',
71
        'compress-files' => 's:files:compress',
72
        'decompress-files' => 's:files:decompress',
73
74
        // Subusers
75
        'list-subusers' => null,
76
        'view-subuser' => null,
77
        'edit-subuser' => null,
78
        'create-subuser' => null,
79
        'delete-subuser' => null,
80
81
        // Tasks
82
        'list-tasks' => null,
83
        'view-task' => null,
84
        'toggle-task' => null,
85
        'delete-task' => null,
86
        'create-task' => null,
87
        'queue-task' => null,
88
89
        // Management
90
        'set-connection' => null,
91
        'view-startup' => null,
92
        'edit-startup' => null,
93
        'view-sftp' => null,
94
        'reset-sftp' => 's:set-password',
95
        'view-sftp-password' => null,
96
97
        // Databases
98
        'view-databases' => null,
99
        'reset-db-password' => null,
100
    ];
101
102
    public function __construct()
103
    {
104
        //
105
    }
106
107
    /**
108
     * Creates a new subuser on the server.
109
     * @param  int $id     The ID of the server to add this subuser to.
0 ignored issues
show
Bug introduced by
There is no parameter named $id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
110
     * @param  array  $data
111
     * @throws DisplayValidationException
112
     * @throws DisplayException
113
     * @return \Pterodactyl\Models\Subuser
114
     */
115
    public function create($sid, array $data)
116
    {
117
        $server = Models\Server::with('node')->findOrFail($sid);
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...
118
119
        $validator = Validator::make($data, [
120
            'permissions' => 'required|array',
121
            'email' => 'required|email',
122
        ]);
123
124
        if ($validator->fails()) {
125
            throw new DisplayValidationException(json_encode($validator->errors()));
126
        }
127
128
        DB::beginTransaction();
129
130
        try {
131
            // Determine if this user exists or if we need to make them an account.
132
            $user = Models\User::where('email', $data['email'])->first();
133
            if (! $user) {
134
                try {
135
                    $repo = new UserRepository;
136
                    $user = $repo->create([
137
                        'email' => $data['email'],
138
                        'username' => str_random(8),
139
                        'name_first' => 'Unassigned',
140
                        'name_last' => 'Name',
141
                        'root_admin' => false,
142
                    ]);
143
                } catch (\Exception $ex) {
144
                    throw $ex;
145
                }
146
            } elseif ($server->owner_id === $user->id) {
147
                throw new DisplayException('You cannot add the owner of a server as a subuser.');
148
            } elseif (Models\Subuser::select('id')->where('user_id', $user->id)->where('server_id', $server->id)->first()) {
149
                throw new DisplayException('A subuser with that email already exists for this server.');
150
            }
151
152
            $uuid = new UuidService;
153
            $subuser = Models\Subuser::create([
154
                'user_id' => $user->id,
155
                'server_id' => $server->id,
156
                'daemonSecret' => (string) $uuid->generate('servers', 'uuid'),
157
            ]);
158
159
            $daemonPermissions = $this->coreDaemonPermissions;
160 View Code Duplication
            foreach ($data['permissions'] as $permission) {
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...
161
                if (array_key_exists($permission, $this->permissions)) {
162
                    // Build the daemon permissions array for sending.
163
                    if (! is_null($this->permissions[$permission])) {
164
                        array_push($daemonPermissions, $this->permissions[$permission]);
165
                    }
166
167
                    Models\Permission::create([
168
                        'subuser_id' => $subuser->id,
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Pterodactyl\Models\Subuser>. 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...
169
                        'permission' => $permission,
170
                    ]);
171
                }
172
            }
173
174
            // Contact Daemon
175
            // We contact even if they don't have any daemon permissions to overwrite
176
            // if they did have them previously.
177
178
            $server->node->guzzleClient([
179
                'X-Access-Server' => $server->uuid,
180
                'X-Access-Token' => $node->daemonSecret,
0 ignored issues
show
Bug introduced by
The variable $node does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
181
            ])->request('PATCH', '/server', [
182
                'json' => [
183
                    'keys' => [
184
                        $subuser->daemonSecret => $daemonPermissions,
0 ignored issues
show
Documentation introduced by
The property daemonSecret does not exist on object<Pterodactyl\Models\Subuser>. 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...
185
                    ],
186
                ],
187
            ]);
188
189
            DB::commit();
190
191
            return $subuser;
192
        } catch (\GuzzleHttp\Exception\TransferException $ex) {
193
            DB::rollBack();
194
            throw new DisplayException('There was an error attempting to connect to the daemon to add this user.', $ex);
195
        } catch (\Exception $ex) {
196
            DB::rollBack();
197
            throw $ex;
198
        }
199
200
        return false;
0 ignored issues
show
Unused Code introduced by
return false; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
201
    }
202
203
    /**
204
     * Revokes a users permissions on a server.
205
     * @param  int  $id  The ID of the subuser row in MySQL.
206
     * @param  array    $data
0 ignored issues
show
Bug introduced by
There is no parameter named $data. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
207
     * @throws DisplayValidationException
208
     * @throws DisplayException
209
     * @return void
210
     */
211
    public function delete($id)
212
    {
213
        $subuser = Models\Subuser::with('server.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...
214
        $server = $subuser->server;
215
216
        DB::beginTransaction();
217
218
        try {
219
            $server->node->guzzleClient([
220
                'X-Access-Server' => $server->uuid,
221
                'X-Access-Token' => $server->node->daemonSecret,
222
            ])->request('PATCH', '/server', [
223
                'json' => [
224
                    'keys' => [
225
                        $subuser->daemonSecret => [],
226
                    ],
227
                ],
228
            ]);
229
230
            foreach ($subuser->permissions as &$permission) {
231
                $permission->delete();
232
            }
233
            $subuser->delete();
234
            DB::commit();
235
236
            return true;
237
        } catch (\GuzzleHttp\Exception\TransferException $ex) {
238
            DB::rollBack();
239
            throw new DisplayException('There was an error attempting to connect to the daemon to delete this subuser.', $ex);
240
        } catch (\Exception $ex) {
241
            DB::rollBack();
242
            throw $ex;
243
        }
244
245
        return false;
0 ignored issues
show
Unused Code introduced by
return false; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
246
    }
247
248
    /**
249
     * Updates permissions for a given subuser.
250
     * @param  int $id  The ID of the subuser row in MySQL. (Not the user ID)
251
     * @param  array  $data
252
     * @throws DisplayValidationException
253
     * @throws DisplayException
254
     * @return void
255
     */
256
    public function update($id, array $data)
257
    {
258
        $validator = Validator::make($data, [
259
            'permissions' => 'required|array',
260
            'user' => 'required|exists:users,id',
261
            'server' => 'required|exists:servers,id',
262
        ]);
263
264
        if ($validator->fails()) {
265
            throw new DisplayValidationException(json_encode($validator->all()));
266
        }
267
268
        $subuser = Models\Subuser::with('server.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...
269
        $server = $subuser->server;
270
271
        DB::beginTransaction();
272
273
        try {
274
            foreach ($subuser->permissions as &$permission) {
275
                $permission->delete();
276
            }
277
278
            $daemonPermissions = $this->coreDaemonPermissions;
279 View Code Duplication
            foreach ($data['permissions'] as $permission) {
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...
280
                if (array_key_exists($permission, $this->permissions)) {
281
                    // Build the daemon permissions array for sending.
282
                    if (! is_null($this->permissions[$permission])) {
283
                        array_push($daemonPermissions, $this->permissions[$permission]);
284
                    }
285
                    Models\Permission::create([
286
                        'subuser_id' => $subuser->id,
287
                        'permission' => $permission,
288
                    ]);
289
                }
290
            }
291
292
            // Contact Daemon
293
            // We contact even if they don't have any daemon permissions to overwrite
294
            // if they did have them previously.
295
            $server->node->guzzleClient([
296
                'X-Access-Server' => $server->uuid,
297
                'X-Access-Token' => $server->node->daemonSecret,
298
            ])->request('PATCH', '/server', [
299
                'json' => [
300
                    'keys' => [
301
                        $subuser->daemonSecret => $daemonPermissions,
302
                    ],
303
                ],
304
            ]);
305
306
            DB::commit();
307
308
            return true;
309
        } catch (\GuzzleHttp\Exception\TransferException $ex) {
310
            DB::rollBack();
311
            throw new DisplayException('There was an error attempting to connect to the daemon to update permissions.', $ex);
312
        } catch (\Exception $ex) {
313
            DB::rollBack();
314
            throw $ex;
315
        }
316
317
        return false;
0 ignored issues
show
Unused Code introduced by
return false; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
318
    }
319
}
320