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
Push — develop ( c3abb3...a85ac8 )
by Dane
11:30
created

APIRepository::create()   D

Complexity

Conditions 18
Paths 98

Size

Total Lines 93
Code Lines 60

Duplication

Lines 32
Ratio 34.41 %

Importance

Changes 0
Metric Value
dl 32
loc 93
rs 4.7996
c 0
b 0
f 0
cc 18
eloc 60
nc 98
nop 1

How to fix   Long Method    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 - 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\Repositories;
26
27
use DB;
28
use Auth;
29
use Crypt;
30
use Validator;
31
use IPTools\Network;
32
use Pterodactyl\Models;
33
use Pterodactyl\Exceptions\DisplayException;
34
use Pterodactyl\Exceptions\DisplayValidationException;
35
36
class APIRepository
37
{
38
    /**
39
     * Valid API permissions.
40
     * @var array
41
     */
42
    protected $permissions = [
43
        'admin' => [
44
            '*',
45
46
            // User Management Routes
47
            'users.list',
48
            'users.create',
49
            'users.view',
50
            'users.update',
51
            'users.delete',
52
53
            // Server Manaement Routes
54
            'servers.list',
55
            'servers.create',
56
            'servers.view',
57
            'servers.config',
58
            'servers.build',
59
            'servers.suspend',
60
            'servers.unsuspend',
61
            'servers.delete',
62
63
            // Node Management Routes
64
            'nodes.list',
65
            'nodes.create',
66
            'nodes.list',
67
            'nodes.allocations',
68
            'nodes.delete',
69
70
            // Service Routes
71
            'services.list',
72
            'services.view',
73
74
            // Location Routes
75
            'locations.list',
76
77
        ],
78
        'user' => [
79
            '*',
80
81
            // Informational
82
            'me',
83
84
            // Server Control
85
            'server',
86
            'server.power',
87
        ],
88
    ];
89
90
    /**
91
     * Holder for listing of allowed IPs when creating a new key.
92
     * @var array
93
     */
94
    protected $allowed = [];
95
96
    protected $user;
97
98
    /**
99
     * Constructor.
100
     */
101
    public function __construct(Models\User $user = null)
102
    {
103
        $this->user = is_null($user) ? Auth::user() : $user;
104
        if (is_null($this->user)) {
105
            throw new \Exception('Cannot access API Repository without passing a user to __construct().');
106
        }
107
    }
108
109
    /**
110
     * Create a New API Keypair on the system.
111
     *
112
     * @param  array $data An array with a permissions and allowed_ips key.
113
     *
114
     * @throws Pterodactyl\Exceptions\DisplayException if there was an error that can be safely displayed to end-users.
115
     * @throws Pterodactyl\Exceptions\DisplayValidationException if there was a validation error.
116
     *
117
     * @return string Returns the generated secret token.
118
     */
119
    public function create(array $data)
120
    {
121
        $validator = Validator::make($data, [
122
            'memo' => 'string|max:500',
123
            'permissions' => 'sometimes|required|array',
124
            'adminPermissions' => 'sometimes|required|array',
125
        ]);
126
127
        $validator->after(function ($validator) use ($data) {
128
            if (array_key_exists('allowed_ips', $data) && ! empty($data['allowed_ips'])) {
129
                foreach (explode("\n", $data['allowed_ips']) as $ip) {
130
                    $ip = trim($ip);
131
                    try {
132
                        Network::parse($ip);
133
                        array_push($this->allowed, $ip);
134
                    } catch (\Exception $ex) {
135
                        $validator->errors()->add('allowed_ips', 'Could not parse IP <' . $ip . '> because it is in an invalid format.');
136
                    }
137
                }
138
            }
139
        });
140
141
        // Run validator, throw catchable and displayable exception if it fails.
142
        // Exception includes a JSON result of failed validation rules.
143
        if ($validator->fails()) {
144
            throw new DisplayValidationException($validator->errors());
145
        }
146
147
        DB::beginTransaction();
148
        try {
149
            $secretKey = str_random(16) . '.' . str_random(7) . '.' . str_random(7);
150
            $key = new Models\APIKey;
151
            $key->fill([
152
                'user' => $this->user->id,
153
                'public' => str_random(16),
154
                'secret' => Crypt::encrypt($secretKey),
155
                'allowed_ips' => empty($this->allowed) ? null : json_encode($this->allowed),
156
                'memo' => $data['memo'],
157
                'expires_at' => null,
158
            ]);
159
            $key->save();
160
161
            $totalPermissions = 0;
162 View Code Duplication
            if (isset($data['permissions'])) {
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...
163
                foreach ($data['permissions'] as $permNode) {
164
                    if (! strpos($permNode, ':')) {
165
                        continue;
166
                    }
167
168
                    list($toss, $permission) = explode(':', $permNode);
0 ignored issues
show
Unused Code introduced by
The assignment to $toss is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
169
                    if (in_array($permission, $this->permissions['user'])) {
170
                        $totalPermissions++;
171
                        $model = new Models\APIPermission;
172
                        $model->fill([
173
                            'key_id' => $key->id,
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Pterodactyl\Models\APIKey>. 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...
174
                            'permission' => 'api.user.' . $permission,
175
                        ]);
176
                        $model->save();
177
                    }
178
                }
179
            }
180
181 View Code Duplication
            if ($this->user->root_admin === 1 && isset($data['adminPermissions'])) {
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...
182
                foreach ($data['adminPermissions'] as $permNode) {
183
                    if (! strpos($permNode, ':')) {
184
                        continue;
185
                    }
186
187
                    list($toss, $permission) = explode(':', $permNode);
0 ignored issues
show
Unused Code introduced by
The assignment to $toss is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
188
                    if (in_array($permission, $this->permissions['admin'])) {
189
                        $totalPermissions++;
190
                        $model = new Models\APIPermission;
191
                        $model->fill([
192
                            'key_id' => $key->id,
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Pterodactyl\Models\APIKey>. 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...
193
                            'permission' => 'api.admin.' . $permission,
194
                        ]);
195
                        $model->save();
196
                    }
197
                }
198
            }
199
200
            if ($totalPermissions < 1) {
201
                throw new DisplayException('No valid permissions were passed.');
202
            }
203
204
            DB::commit();
205
206
            return $secretKey;
207
        } catch (\Exception $ex) {
208
            DB::rollBack();
209
            throw $ex;
210
        }
211
    }
212
213
    /**
214
     * Revokes an API key and associated permissions.
215
     *
216
     * @param  string $key The public key.
217
     *
218
     * @throws Illuminate\Database\Eloquent\ModelNotFoundException
219
     *
220
     * @return void
221
     */
222
    public function revoke($key)
223
    {
224
        DB::beginTransaction();
225
226
        try {
227
            $model = Models\APIKey::where('public', $key)->where('user', $this->user->id)->firstOrFail();
228
            Models\APIPermission::where('key_id', $model->id)->delete();
229
            $model->delete();
230
231
            DB::commit();
232
        } catch (\Exception $ex) {
233
            DB::rollBack();
234
            throw $ex;
235
        }
236
    }
237
}
238