Skip to content

Commit 8c9e797

Browse files
committed
Finish user portion of API
1 parent 4604500 commit 8c9e797

File tree

5 files changed

+94
-39
lines changed

5 files changed

+94
-39
lines changed

app/Http/Controllers/API/AuthController.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
use Pterodactyl\Models;
2222

2323
/**
24-
* @Resource("Auth", uri="/auth")
24+
* @Resource("Auth")
2525
*/
2626
class AuthController extends BaseController
2727
{
@@ -57,7 +57,7 @@ public function __construct()
5757
*
5858
* Authenticate with the API to recieved a JSON Web Token
5959
*
60-
* @Post("/login")
60+
* @Post("/auth/login")
6161
* @Versions({"v1"})
6262
* @Request({"email": "e@mail.com", "password": "soopersecret"})
6363
* @Response(200, body={"token": "<jwt-token>"})
@@ -112,7 +112,7 @@ public function postLogin(Request $request) {
112112
/**
113113
* Check if Authenticated
114114
*
115-
* @Post("/validate")
115+
* @Post("/auth/validate")
116116
* @Versions({"v1"})
117117
* @Request(headers={"Authorization": "Bearer <jwt-token>"})
118118
* @Response(204)

app/Http/Controllers/API/UserController.php

Lines changed: 42 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,14 @@
66

77
use Dingo\Api\Exception\StoreResourceFailedException;
88

9-
use Pterodactyl\Transformers\UserTransformer;
109
use Pterodactyl\Models;
10+
use Pterodactyl\Transformers\UserTransformer;
1111
use Pterodactyl\Repositories\UserRepository;
12+
use Pterodactyl\Exceptions\DisplayValidationException;
13+
use Pterodactyl\Exceptions\DisplayException;
1214

1315
/**
14-
* @Resource("Users", uri="/users")
16+
* @Resource("Users")
1517
*/
1618
class UserController extends BaseController
1719
{
@@ -21,7 +23,7 @@ class UserController extends BaseController
2123
*
2224
* Lists all users currently on the system.
2325
*
24-
* @Get("/{?page}")
26+
* @Get("/users/{?page}")
2527
* @Versions({"v1"})
2628
* @Parameters({
2729
* @Parameter("page", type="integer", description="The page of results to view.", default=1)
@@ -39,15 +41,15 @@ public function getUsers(Request $request)
3941
*
4042
* Lists specific fields about a user or all fields pertaining to that user.
4143
*
42-
* @Get("/{id}/{fields}")
44+
* @Get("/users/{id}/{fields}")
4345
* @Versions({"v1"})
4446
* @Parameters({
4547
* @Parameter("id", type="integer", required=true, description="The ID of the user to get information on."),
4648
* @Parameter("fields", type="string", required=false, description="A comma delimidated list of fields to include.")
4749
* })
4850
* @Response(200)
4951
*/
50-
public function getUserByID(Request $request, $id, $fields = null)
52+
public function getUser(Request $request, $id, $fields = null)
5153
{
5254
$query = Models\User::where('id', $id);
5355

@@ -65,34 +67,38 @@ public function getUserByID(Request $request, $id, $fields = null)
6567
/**
6668
* Create a New User
6769
*
68-
* @Post("/")
70+
* @Post("/users")
6971
* @Versions({"v1"})
7072
* @Transaction({
7173
* @Request({
7274
* "email": "foo@example.com",
7375
* "password": "foopassword",
7476
* "admin": false
7577
* }, headers={"Authorization": "Bearer <jwt-token>"}),
76-
* @Response(200, body={"id": 1}),
77-
* @Response(422, body{
78+
* @Response(201),
79+
* @Response(422, body={
7880
* "message": "A validation error occured.",
7981
* "errors": {
80-
* "email": ["The email field is required."],
81-
* "password": ["The password field is required."],
82-
* "admin": ["The admin field is required."]
82+
* "email": {"The email field is required."},
83+
* "password": {"The password field is required."},
84+
* "admin": {"The admin field is required."}
8385
* },
8486
* "status_code": 422
8587
* })
8688
* })
8789
*/
88-
public function postUsers(Request $request)
90+
public function postUser(Request $request)
8991
{
9092
try {
9193
$user = new UserRepository;
9294
$create = $user->create($request->input('email'), $request->input('password'), $request->input('admin'));
93-
return [ 'id' => $create ];
94-
} catch (\Pterodactyl\Exceptions\DisplayValidationException $ex) {
95+
return $this->response->created(route('api.users.view', [
96+
'id' => $create
97+
]));
98+
} catch (DisplayValidationException $ex) {
9599
throw new StoreResourceFailedException('A validation error occured.', json_decode($ex->getMessage(), true));
100+
} catch (DisplayException $ex) {
101+
throw new StoreResourceFailedException($ex->getMessage());
96102
} catch (\Exception $ex) {
97103
throw new StoreResourceFailedException('Unable to create a user on the system due to an error.');
98104
}
@@ -103,7 +109,7 @@ public function postUsers(Request $request)
103109
*
104110
* The data sent in the request will be used to update the existing user on the system.
105111
*
106-
* @Patch("/{id}")
112+
* @Patch("/users/{id}")
107113
* @Versions({"v1"})
108114
* @Transaction({
109115
* @Request({
@@ -118,13 +124,23 @@ public function postUsers(Request $request)
118124
*/
119125
public function patchUser(Request $request, $id)
120126
{
121-
//
127+
try {
128+
$user = new UserRepository;
129+
$user->update($id, $request->all());
130+
return Models\User::findOrFail($id);
131+
} catch (DisplayValidationException $ex) {
132+
throw new StoreResourceFailedException('A validation error occured.', json_decode($ex->getMessage(), true));
133+
} catch (DisplayException $ex) {
134+
throw new StoreResourceFailedException($ex->getMessage());
135+
} catch (\Exception $ex) {
136+
throw new StoreResourceFailedException('Unable to create a user on the system due to an error.');
137+
}
122138
}
123139

124140
/**
125141
* Delete a User
126142
*
127-
* @Delete("/{id}")
143+
* @Delete("/users/{id}")
128144
* @Versions({"v1"})
129145
* @Transaction({
130146
* @Request(headers={"Authorization": "Bearer <jwt-token>"}),
@@ -137,7 +153,15 @@ public function patchUser(Request $request, $id)
137153
*/
138154
public function deleteUser(Request $request, $id)
139155
{
140-
//
156+
try {
157+
$user = new UserRepository;
158+
$user->delete($id);
159+
return $this->response->noContent();
160+
} catch (DisplayException $ex) {
161+
throw new StoreResourceFailedException($ex->getMessage());
162+
} catch (\Exception $ex) {
163+
throw new StoreResourceFailedException('Unable to delete this user due to an error.');
164+
}
141165
}
142166

143167
}

app/Http/Routes/APIRoutes.php

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,22 +30,30 @@ public function map(Router $router) {
3030
});
3131

3232
$api->version('v1', ['middleware' => 'api.auth'], function ($api) {
33-
3433
$api->get('users', [
3534
'as' => 'api.users',
3635
'uses' => 'Pterodactyl\Http\Controllers\API\UserController@getUsers'
3736
]);
3837

3938
$api->post('users', [
4039
'as' => 'api.users.post',
41-
'uses' => 'Pterodactyl\Http\Controllers\API\UserController@postUsers'
40+
'uses' => 'Pterodactyl\Http\Controllers\API\UserController@postUser'
4241
]);
4342

4443
$api->get('users/{id}/{fields?}', [
4544
'as' => 'api.users.view',
46-
'uses' => 'Pterodactyl\Http\Controllers\API\UserController@getUserByID'
45+
'uses' => 'Pterodactyl\Http\Controllers\API\UserController@getUser'
46+
]);
47+
48+
$api->patch('users/{id}/', [
49+
'as' => 'api.users.patch',
50+
'uses' => 'Pterodactyl\Http\Controllers\API\UserController@patchUser'
4751
]);
4852

53+
$api->delete('users/{id}/', [
54+
'as' => 'api.users.delete',
55+
'uses' => 'Pterodactyl\Http\Controllers\API\UserController@deleteUser'
56+
]);
4957
});
5058
}
5159

app/Models/User.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ class User extends Model implements AuthenticatableContract,
3434
*
3535
* @var array
3636
*/
37-
protected $fillable = ['name', 'email', 'password'];
37+
protected $fillable = ['name', 'email', 'password', 'use_totp', 'totp_secret', 'language'];
3838

3939
/**
4040
* The attributes excluded from the model's JSON form.

app/Repositories/UserRepository.php

Lines changed: 37 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22

33
namespace Pterodactyl\Repositories;
44

5-
use Validator;
5+
use DB;
66
use Hash;
7+
use Validator;
78

8-
use Pterodactyl\Models\User;
9+
use Pterodactyl\Models;
910
use Pterodactyl\Services\UuidService;
1011

1112
use Pterodactyl\Exceptions\DisplayValidationException;
13+
use Pterodactyl\Exceptions\DisplayException;
1214

1315
class UserRepository
1416
{
@@ -27,15 +29,14 @@ public function __construct()
2729
*/
2830
public function create($email, $password, $admin = false)
2931
{
30-
3132
$validator = Validator::make([
3233
'email' => $email,
3334
'password' => $password,
34-
'admin' => $admin
35+
'root_admin' => $admin
3536
], [
3637
'email' => 'required|email|unique:users,email',
3738
'password' => 'required|regex:((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,})',
38-
'admin' => 'required|boolean'
39+
'root_admin' => 'required|boolean'
3940
]);
4041

4142
// Run validator, throw catchable and displayable exception if it fails.
@@ -44,7 +45,7 @@ public function create($email, $password, $admin = false)
4445
throw new DisplayValidationException($validator->errors());
4546
}
4647

47-
$user = new User;
48+
$user = new Models\User;
4849
$uuid = new UuidService;
4950

5051
$user->uuid = $uuid->generate('users', 'uuid');
@@ -64,16 +65,25 @@ public function create($email, $password, $admin = false)
6465
* Updates a user on the panel.
6566
*
6667
* @param integer $id
67-
* @param array $user An array of columns and their associated values to update for the user.
68+
* @param array $data An array of columns and their associated values to update for the user.
6869
* @return boolean
6970
*/
70-
public function update($id, array $user)
71+
public function update($id, array $data)
7172
{
72-
if(array_key_exists('password', $user)) {
73-
$user['password'] = Hash::make($user['password']);
73+
$validator = Validator::make($data, [
74+
'email' => 'email|unique:users,email,' . $id,
75+
'password' => 'regex:((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,})',
76+
'root_admin' => 'boolean',
77+
'language' => 'string|min:1|max:5',
78+
'use_totp' => 'boolean',
79+
'totp_secret' => 'size:16'
80+
]);
81+
82+
if(array_key_exists('password', $data)) {
83+
$user['password'] = Hash::make($data['password']);
7484
}
7585

76-
return User::find($id)->update($user);
86+
return Models\User::find($id)->update($data);
7787
}
7888

7989
/**
@@ -84,9 +94,22 @@ public function update($id, array $user)
8494
*/
8595
public function delete($id)
8696
{
87-
// @TODO cannot delete user with associated servers!
88-
// clean up subusers!
89-
return User::destroy($id);
97+
if(Models\Server::where('owner', $id)->count() > 0) {
98+
throw new DisplayException('Cannot delete a user with active servers attached to thier account.');
99+
}
100+
101+
DB::beginTransaction();
102+
103+
Models\Permission::where('user_id', $id)->delete();
104+
Models\Subuser::where('user_id', $id)->delete();
105+
Models\User::destroy($id);
106+
107+
try {
108+
DB::commit();
109+
return true;
110+
} catch (\Exception $ex) {
111+
throw $ex;
112+
}
90113
}
91114

92115
}

0 commit comments

Comments
 (0)