Skip to content

Commit 22b0bbf

Browse files
committed
Model fixing, moving things around to improve code.
Adds unique UUID generator, moves functions into repositories for adding servers and users, cleans up code, adding more comments.
1 parent 01eaeaf commit 22b0bbf

File tree

8 files changed

+333
-250
lines changed

8 files changed

+333
-250
lines changed

app/Http/Controllers/Admin/AccountsController.php

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,9 @@
33
namespace Pterodactyl\Http\Controllers\Admin;
44

55
use Alert;
6-
use Debugbar;
7-
use Hash;
8-
use Uuid;
9-
106
use Pterodactyl\Models\User;
7+
use Pterodactyl\Repositories\UserRepository;
8+
119
use Pterodactyl\Http\Controllers\Controller;
1210
use Illuminate\Http\Request;
1311

@@ -52,18 +50,19 @@ public function postNew(Request $request)
5250
'password_confirmation' => 'required'
5351
]);
5452

55-
//@TODO: re-generate UUID if conflict
56-
$user = new User;
57-
$user->uuid = Uuid::generate(4);
53+
try {
54+
55+
$user = new UserRepository;
56+
$userid = $user->create($request->input('username'), $request->input('email'), $request->input('password'));
5857

59-
$user->username = $request->input('username');
60-
$user->email = $request->input('email');
61-
$user->password = Hash::make($request->input('password'));
58+
Alert::success('Account has been successfully created.')->flash();
59+
return redirect()->route('admin.accounts.view', ['id' => $userid]);
6260

63-
$user->save();
61+
} catch (\Exception $e) {
62+
Alert::danger('An error occured while attempting to add a new user. Please check the logs or try again.')->flash();
63+
return redirect()->route('admin.accounts.new');
64+
}
6465

65-
Alert::success('Account has been successfully created.')->flash();
66-
return redirect()->route('admin.accounts.view', ['id' => $user->id]);
6766
}
6867

6968
}

app/Http/Controllers/Admin/ServersController.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Pterodactyl\Http\Controllers\Admin;
44

55
use Debugbar;
6+
use Pterodactyl\Repositories\ServerRepository;
67
use Pterodactyl\Models\Server;
78
use Pterodactyl\Models\Node;
89
use Pterodactyl\Models\Location;
@@ -56,7 +57,8 @@ public function postNewServer(Request $request)
5657
{
5758

5859
try {
59-
$resp = Server::addServer($request->all());
60+
$server = new ServerRepository;
61+
$resp = $server->create($request->all());
6062
echo $resp . '<br />';
6163
} catch (\Exception $e) {
6264
Debugbar::addException($e);

app/Http/Controllers/Base/IndexController.php

Lines changed: 38 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,12 @@
33
namespace Pterodactyl\Http\Controllers\Base;
44

55
use Auth;
6-
use Debugbar;
6+
use Hash;
77
use Google2FA;
8-
use Log;
98
use Alert;
10-
use Pterodactyl\Exceptions\AccountNotFoundException;
11-
use Pterodactyl\Exceptions\DisplayException;
12-
use Pterodactyl\Models\User;
9+
1310
use Pterodactyl\Models\Server;
11+
use Pterodactyl\Exceptions\DisplayException;
1412

1513
use Pterodactyl\Http\Controllers\Controller;
1614
use Illuminate\Http\Request;
@@ -74,22 +72,18 @@ public function getAccountTotp(Request $request)
7472
public function putAccountTotp(Request $request)
7573
{
7674

77-
try {
78-
$totpSecret = User::setTotpSecret(Auth::user()->id);
79-
} catch (\Exception $e) {
80-
if ($e instanceof AccountNotFoundException) {
81-
return response($e->getMessage(), 500);
82-
}
83-
throw $e;
84-
}
75+
$user = $request->user();
76+
77+
$user->totp_secret = Google2FA::generateSecretKey();
78+
$user->save();
8579

8680
return response()->json([
8781
'qrImage' => Google2FA::getQRCodeGoogleUrl(
8882
'Pterodactyl',
89-
Auth::user()->email,
90-
$totpSecret
83+
$user->email,
84+
$user->totp_secret
9185
),
92-
'secret' => $totpSecret
86+
'secret' => $user->totp_secret
9387
]);
9488

9589
}
@@ -104,21 +98,16 @@ public function postAccountTotp(Request $request)
10498
{
10599

106100
if (!$request->has('token')) {
107-
return response('No input \'token\' defined.', 500);
101+
return response(null, 500);
108102
}
109103

110-
try {
111-
if(User::toggleTotp(Auth::user()->id, $request->input('token'))) {
112-
return response('true');
113-
}
114-
return response('false');
115-
} catch (\Exception $e) {
116-
if ($e instanceof AccountNotFoundException) {
117-
return response($e->getMessage(), 500);
118-
}
119-
throw $e;
104+
$user = $request->user();
105+
if($user->toggleTotp($request->input('token'))) {
106+
return response('true');
120107
}
121108

109+
return response('false');
110+
122111
}
123112

124113
/**
@@ -135,21 +124,14 @@ public function deleteAccountTotp(Request $request)
135124
return redirect()->route('account.totp');
136125
}
137126

138-
try {
139-
if(User::toggleTotp(Auth::user()->id, $request->input('token'))) {
140-
return redirect()->route('account.totp');
141-
}
142-
143-
Alert::danger('Unable to disable TOTP on this account, was the token correct?')->flash();
127+
$user = $request->user();
128+
if($user->toggleTotp($request->input('token'))) {
144129
return redirect()->route('account.totp');
145-
} catch (\Exception $e) {
146-
if ($e instanceof AccountNotFoundException) {
147-
Alert::danger('An error occured while attempting to perform this action.')->flash();
148-
return redirect()->route('account.totp');
149-
}
150-
throw $e;
151130
}
152131

132+
Alert::danger('The TOTP token provided was invalid.')->flash();
133+
return redirect()->route('account.totp');
134+
153135
}
154136

155137
/**
@@ -177,23 +159,19 @@ public function postAccountEmail(Request $request)
177159
'password' => 'required'
178160
]);
179161

180-
if (!password_verify($request->input('password'), Auth::user()->password)) {
162+
$user = $request->user();
163+
164+
if (!password_verify($request->input('password'), $user->password)) {
181165
Alert::danger('The password provided was not valid for this account.')->flash();
182166
return redirect()->route('account');
183167
}
184168

185-
// Met Validation, lets roll out.
186-
try {
187-
User::setEmail(Auth::user()->id, $request->input('new_email'));
188-
Alert::success('Your email address has successfully been updated.')->flash();
189-
return redirect()->route('account');
190-
} catch (\Exception $e) {
191-
if ($e instanceof AccountNotFoundException || $e instanceof DisplayException) {
192-
Alert::danger($e->getMessage())->flash();
193-
return redirect()->route('account');
194-
}
195-
throw $e;
196-
}
169+
$user->email = $request->input('new_email');
170+
$user->save();
171+
172+
Alert::success('Your email address has successfully been updated.')->flash();
173+
return redirect()->route('account');
174+
197175
}
198176

199177
/**
@@ -211,24 +189,22 @@ public function postAccountPassword(Request $request)
211189
'new_password_confirmation' => 'required'
212190
]);
213191

214-
if (!password_verify($request->input('current_password'), Auth::user()->password)) {
192+
$user = $request->user();
193+
194+
if (!password_verify($request->input('current_password'), $user->password)) {
215195
Alert::danger('The password provided was not valid for this account.')->flash();
216196
return redirect()->route('account');
217197
}
218198

219-
// Met Validation, lets roll out.
220199
try {
221-
User::setPassword(Auth::user()->id, $request->input('new_password'));
200+
$user->setPassword($request->input('new_password'));
222201
Alert::success('Your password has successfully been updated.')->flash();
223-
return redirect()->route('account');
224-
} catch (\Exception $e) {
225-
if ($e instanceof AccountNotFoundException || $e instanceof DisplayException) {
226-
Alert::danger($e->getMessage())->flash();
227-
return redirect()->route('account');
228-
}
229-
throw $e;
202+
} catch (DisplayException $e) {
203+
Alert::danger($e->getMessage())->flash();
230204
}
231205

206+
return redirect()->route('account');
207+
232208
}
233209

234210
}

app/Models/Server.php

Lines changed: 4 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,8 @@
33
namespace Pterodactyl\Models;
44

55
use Auth;
6-
use DB;
7-
use Debugbar;
8-
use Validator;
9-
10-
use Pterodactyl\Exceptions\DisplayException;
11-
use Pterodactyl\Exceptions\AccountNotFoundException;
12-
use Pterodactyl\Exceptions\DisplayValidationException;
13-
14-
use Pterodactyl\Models;
156

7+
use Pterodactyl\Models\Subuser;
168
use Illuminate\Database\Eloquent\Model;
179

1810
class Server extends Model
@@ -50,18 +42,6 @@ public function __construct()
5042
self::$user = Auth::user();
5143
}
5244

53-
protected static function generateSFTPUsername($name)
54-
{
55-
56-
$name = preg_replace('/\s+/', '', $name);
57-
if (strlen($name) > 6) {
58-
return strtolower('ptdl-' . substr($name, 0, 6) . '_' . str_random(5));
59-
}
60-
61-
return strtolower('ptdl-' . $name . '_' . str_random((11 - strlen($name))));
62-
63-
}
64-
6545
/**
6646
* Determine if we need to change the server's daemonSecret value to
6747
* match that of the user if they are a subuser.
@@ -76,7 +56,7 @@ protected static function getUserDaemonSecret(Server $server)
7656
return $server->daemonSecret;
7757
}
7858

79-
$subuser = Models\Subuser::where('server_id', $server->id)->where('user_id', self::$user->id)->first();
59+
$subuser = Subuser::where('server_id', $server->id)->where('user_id', self::$user->id)->first();
8060

8161
if (is_null($subuser)) {
8262
return null;
@@ -101,7 +81,7 @@ public static function getUserServers()
10181
->where('active', 1);
10282

10383
if (self::$user->root_admin !== 1) {
104-
$query->whereIn('servers.id', Models\Subuser::accessServers());
84+
$query->whereIn('servers.id', Subuser::accessServers());
10585
}
10686

10787
return $query->get();
@@ -124,7 +104,7 @@ public static function getByUUID($uuid)
124104
$query = self::where('uuidShort', $uuid)->where('active', 1);
125105

126106
if (self::$user->root_admin !== 1) {
127-
$query->whereIn('servers.id', Models\Subuser::accessServers());
107+
$query->whereIn('servers.id', Subuser::accessServers());
128108
}
129109

130110
$result = $query->first();
@@ -158,84 +138,4 @@ public static function getGuzzleHeaders($uuid)
158138

159139
}
160140

161-
/**
162-
* Adds a new server to the system.
163-
* @param array $data An array of data descriptors for creating the server. These should align to the columns in the database.
164-
*/
165-
public static function addServer(array $data)
166-
{
167-
168-
// Validate Fields
169-
$validator = Validator::make($data, [
170-
'owner' => 'required|email|exists:users,email',
171-
'node' => 'required|numeric|min:1|exists:nodes,id',
172-
'name' => 'required|regex:([\w -]{4,35})',
173-
'memory' => 'required|numeric|min:1',
174-
'disk' => 'required|numeric|min:1',
175-
'cpu' => 'required|numeric|min:0',
176-
'io' => 'required|numeric|min:10|max:1000',
177-
'ip' => 'required|ip',
178-
'port' => 'required|numeric|min:1|max:65535',
179-
'service' => 'required|numeric|min:1|exists:services,id',
180-
'option' => 'required|numeric|min:1|exists:service_options,id',
181-
'custom_image_name' => 'required_if:use_custom_image,on',
182-
]);
183-
184-
// Run validator, throw catchable and displayable exception if it fails.
185-
// Exception includes a JSON result of failed validation rules.
186-
if ($validator->fails()) {
187-
throw new DisplayValidationException(json_encode($validator->errors()->all()));
188-
}
189-
190-
// Get the User ID; user exists since we passed the 'exists:users,email' part of the validation
191-
$user = Models\User::select('id')->where('email', $data['owner'])->first();
192-
193-
// Verify IP & Port are a.) free and b.) assigned to the node.
194-
// We know the node exists because of 'exists:nodes,id' in the validation
195-
$node = Models\Node::find($data['node']);
196-
$allocation = Models\Allocation::where('ip', $data['ip'])->where('port', $data['port'])->where('node', $data['node'])->whereNull('assigned_to')->first();
197-
198-
// Something failed in the query, either that combo doesn't exist, or it is in use.
199-
if (!$allocation) {
200-
throw new DisplayException('The selected IP/Port combination (' . $data['ip'] . ':' . $data['port'] . ') is either already in use, or unavaliable for this node.');
201-
}
202-
203-
// Validate those Service Option Variables
204-
// We know the service and option exists because of the validation.
205-
// We need to verify that the option exists for the service, and then check for
206-
// any required variable fields. (fields are labeled env_<env_variable>)
207-
$option = Models\ServiceOptions::where('id', $data['option'])->where('parent_service', $data['service'])->first();
208-
if (!$option) {
209-
throw new DisplayException('The requested service option does not exist for the specified service.');
210-
}
211-
212-
// Check those Variables
213-
$variables = Models\ServiceVariables::where('option_id', $data['option'])->get();
214-
if ($variables) {
215-
foreach($variables as $variable) {
216-
217-
// Is the variable required?
218-
if (!$data['env_' . $variable->env_variable]) {
219-
if ($variable->required === 1) {
220-
throw new DisplayException('A required service option variable field (env_' . $variable->env_variable . ') was missing from the request.');
221-
}
222-
223-
$data['env_' . $variable->env_variable] = $variable->default_value;
224-
continue;
225-
}
226-
227-
// Check aganist Regex Pattern
228-
if (!is_null($variable->regex) && !preg_match($variable->regex, $data['env_' . $variable->env_variable])) {
229-
throw new DisplayException('Failed to validate service option variable field (env_' . $variable->env_variable . ') aganist regex (' . $variable->regex . ').');
230-
}
231-
232-
continue;
233-
234-
}
235-
}
236-
237-
return self::generateSFTPUsername($data['name']);
238-
239-
}
240-
241141
}

0 commit comments

Comments
 (0)