Finish user portion of API

This commit is contained in:
Dane Everitt 2016-01-14 23:13:26 -05:00
parent 4604500349
commit 8c9e797210
5 changed files with 94 additions and 39 deletions

View file

@ -21,7 +21,7 @@ use Pterodactyl\Transformers\UserTransformer;
use Pterodactyl\Models; use Pterodactyl\Models;
/** /**
* @Resource("Auth", uri="/auth") * @Resource("Auth")
*/ */
class AuthController extends BaseController class AuthController extends BaseController
{ {
@ -57,7 +57,7 @@ class AuthController extends BaseController
* *
* Authenticate with the API to recieved a JSON Web Token * Authenticate with the API to recieved a JSON Web Token
* *
* @Post("/login") * @Post("/auth/login")
* @Versions({"v1"}) * @Versions({"v1"})
* @Request({"email": "e@mail.com", "password": "soopersecret"}) * @Request({"email": "e@mail.com", "password": "soopersecret"})
* @Response(200, body={"token": "<jwt-token>"}) * @Response(200, body={"token": "<jwt-token>"})
@ -112,7 +112,7 @@ class AuthController extends BaseController
/** /**
* Check if Authenticated * Check if Authenticated
* *
* @Post("/validate") * @Post("/auth/validate")
* @Versions({"v1"}) * @Versions({"v1"})
* @Request(headers={"Authorization": "Bearer <jwt-token>"}) * @Request(headers={"Authorization": "Bearer <jwt-token>"})
* @Response(204) * @Response(204)

View file

@ -6,12 +6,14 @@ use Illuminate\Http\Request;
use Dingo\Api\Exception\StoreResourceFailedException; use Dingo\Api\Exception\StoreResourceFailedException;
use Pterodactyl\Transformers\UserTransformer;
use Pterodactyl\Models; use Pterodactyl\Models;
use Pterodactyl\Transformers\UserTransformer;
use Pterodactyl\Repositories\UserRepository; use Pterodactyl\Repositories\UserRepository;
use Pterodactyl\Exceptions\DisplayValidationException;
use Pterodactyl\Exceptions\DisplayException;
/** /**
* @Resource("Users", uri="/users") * @Resource("Users")
*/ */
class UserController extends BaseController class UserController extends BaseController
{ {
@ -21,7 +23,7 @@ class UserController extends BaseController
* *
* Lists all users currently on the system. * Lists all users currently on the system.
* *
* @Get("/{?page}") * @Get("/users/{?page}")
* @Versions({"v1"}) * @Versions({"v1"})
* @Parameters({ * @Parameters({
* @Parameter("page", type="integer", description="The page of results to view.", default=1) * @Parameter("page", type="integer", description="The page of results to view.", default=1)
@ -39,7 +41,7 @@ class UserController extends BaseController
* *
* Lists specific fields about a user or all fields pertaining to that user. * Lists specific fields about a user or all fields pertaining to that user.
* *
* @Get("/{id}/{fields}") * @Get("/users/{id}/{fields}")
* @Versions({"v1"}) * @Versions({"v1"})
* @Parameters({ * @Parameters({
* @Parameter("id", type="integer", required=true, description="The ID of the user to get information on."), * @Parameter("id", type="integer", required=true, description="The ID of the user to get information on."),
@ -47,7 +49,7 @@ class UserController extends BaseController
* }) * })
* @Response(200) * @Response(200)
*/ */
public function getUserByID(Request $request, $id, $fields = null) public function getUser(Request $request, $id, $fields = null)
{ {
$query = Models\User::where('id', $id); $query = Models\User::where('id', $id);
@ -65,7 +67,7 @@ class UserController extends BaseController
/** /**
* Create a New User * Create a New User
* *
* @Post("/") * @Post("/users")
* @Versions({"v1"}) * @Versions({"v1"})
* @Transaction({ * @Transaction({
* @Request({ * @Request({
@ -73,26 +75,30 @@ class UserController extends BaseController
* "password": "foopassword", * "password": "foopassword",
* "admin": false * "admin": false
* }, headers={"Authorization": "Bearer <jwt-token>"}), * }, headers={"Authorization": "Bearer <jwt-token>"}),
* @Response(200, body={"id": 1}), * @Response(201),
* @Response(422, body{ * @Response(422, body={
* "message": "A validation error occured.", * "message": "A validation error occured.",
* "errors": { * "errors": {
* "email": ["The email field is required."], * "email": {"The email field is required."},
* "password": ["The password field is required."], * "password": {"The password field is required."},
* "admin": ["The admin field is required."] * "admin": {"The admin field is required."}
* }, * },
* "status_code": 422 * "status_code": 422
* }) * })
* }) * })
*/ */
public function postUsers(Request $request) public function postUser(Request $request)
{ {
try { try {
$user = new UserRepository; $user = new UserRepository;
$create = $user->create($request->input('email'), $request->input('password'), $request->input('admin')); $create = $user->create($request->input('email'), $request->input('password'), $request->input('admin'));
return [ 'id' => $create ]; return $this->response->created(route('api.users.view', [
} catch (\Pterodactyl\Exceptions\DisplayValidationException $ex) { 'id' => $create
]));
} catch (DisplayValidationException $ex) {
throw new StoreResourceFailedException('A validation error occured.', json_decode($ex->getMessage(), true)); throw new StoreResourceFailedException('A validation error occured.', json_decode($ex->getMessage(), true));
} catch (DisplayException $ex) {
throw new StoreResourceFailedException($ex->getMessage());
} catch (\Exception $ex) { } catch (\Exception $ex) {
throw new StoreResourceFailedException('Unable to create a user on the system due to an error.'); throw new StoreResourceFailedException('Unable to create a user on the system due to an error.');
} }
@ -103,7 +109,7 @@ class UserController extends BaseController
* *
* The data sent in the request will be used to update the existing user on the system. * The data sent in the request will be used to update the existing user on the system.
* *
* @Patch("/{id}") * @Patch("/users/{id}")
* @Versions({"v1"}) * @Versions({"v1"})
* @Transaction({ * @Transaction({
* @Request({ * @Request({
@ -118,13 +124,23 @@ class UserController extends BaseController
*/ */
public function patchUser(Request $request, $id) public function patchUser(Request $request, $id)
{ {
// try {
$user = new UserRepository;
$user->update($id, $request->all());
return Models\User::findOrFail($id);
} catch (DisplayValidationException $ex) {
throw new StoreResourceFailedException('A validation error occured.', json_decode($ex->getMessage(), true));
} catch (DisplayException $ex) {
throw new StoreResourceFailedException($ex->getMessage());
} catch (\Exception $ex) {
throw new StoreResourceFailedException('Unable to create a user on the system due to an error.');
}
} }
/** /**
* Delete a User * Delete a User
* *
* @Delete("/{id}") * @Delete("/users/{id}")
* @Versions({"v1"}) * @Versions({"v1"})
* @Transaction({ * @Transaction({
* @Request(headers={"Authorization": "Bearer <jwt-token>"}), * @Request(headers={"Authorization": "Bearer <jwt-token>"}),
@ -137,7 +153,15 @@ class UserController extends BaseController
*/ */
public function deleteUser(Request $request, $id) public function deleteUser(Request $request, $id)
{ {
// try {
$user = new UserRepository;
$user->delete($id);
return $this->response->noContent();
} catch (DisplayException $ex) {
throw new StoreResourceFailedException($ex->getMessage());
} catch (\Exception $ex) {
throw new StoreResourceFailedException('Unable to delete this user due to an error.');
}
} }
} }

View file

@ -30,7 +30,6 @@ class APIRoutes
}); });
$api->version('v1', ['middleware' => 'api.auth'], function ($api) { $api->version('v1', ['middleware' => 'api.auth'], function ($api) {
$api->get('users', [ $api->get('users', [
'as' => 'api.users', 'as' => 'api.users',
'uses' => 'Pterodactyl\Http\Controllers\API\UserController@getUsers' 'uses' => 'Pterodactyl\Http\Controllers\API\UserController@getUsers'
@ -38,14 +37,23 @@ class APIRoutes
$api->post('users', [ $api->post('users', [
'as' => 'api.users.post', 'as' => 'api.users.post',
'uses' => 'Pterodactyl\Http\Controllers\API\UserController@postUsers' 'uses' => 'Pterodactyl\Http\Controllers\API\UserController@postUser'
]); ]);
$api->get('users/{id}/{fields?}', [ $api->get('users/{id}/{fields?}', [
'as' => 'api.users.view', 'as' => 'api.users.view',
'uses' => 'Pterodactyl\Http\Controllers\API\UserController@getUserByID' 'uses' => 'Pterodactyl\Http\Controllers\API\UserController@getUser'
]); ]);
$api->patch('users/{id}/', [
'as' => 'api.users.patch',
'uses' => 'Pterodactyl\Http\Controllers\API\UserController@patchUser'
]);
$api->delete('users/{id}/', [
'as' => 'api.users.delete',
'uses' => 'Pterodactyl\Http\Controllers\API\UserController@deleteUser'
]);
}); });
} }

View file

@ -34,7 +34,7 @@ class User extends Model implements AuthenticatableContract,
* *
* @var array * @var array
*/ */
protected $fillable = ['name', 'email', 'password']; protected $fillable = ['name', 'email', 'password', 'use_totp', 'totp_secret', 'language'];
/** /**
* The attributes excluded from the model's JSON form. * The attributes excluded from the model's JSON form.

View file

@ -2,13 +2,15 @@
namespace Pterodactyl\Repositories; namespace Pterodactyl\Repositories;
use Validator; use DB;
use Hash; use Hash;
use Validator;
use Pterodactyl\Models\User; use Pterodactyl\Models;
use Pterodactyl\Services\UuidService; use Pterodactyl\Services\UuidService;
use Pterodactyl\Exceptions\DisplayValidationException; use Pterodactyl\Exceptions\DisplayValidationException;
use Pterodactyl\Exceptions\DisplayException;
class UserRepository class UserRepository
{ {
@ -27,15 +29,14 @@ class UserRepository
*/ */
public function create($email, $password, $admin = false) public function create($email, $password, $admin = false)
{ {
$validator = Validator::make([ $validator = Validator::make([
'email' => $email, 'email' => $email,
'password' => $password, 'password' => $password,
'admin' => $admin 'root_admin' => $admin
], [ ], [
'email' => 'required|email|unique:users,email', 'email' => 'required|email|unique:users,email',
'password' => 'required|regex:((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,})', 'password' => 'required|regex:((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,})',
'admin' => 'required|boolean' 'root_admin' => 'required|boolean'
]); ]);
// Run validator, throw catchable and displayable exception if it fails. // Run validator, throw catchable and displayable exception if it fails.
@ -44,7 +45,7 @@ class UserRepository
throw new DisplayValidationException($validator->errors()); throw new DisplayValidationException($validator->errors());
} }
$user = new User; $user = new Models\User;
$uuid = new UuidService; $uuid = new UuidService;
$user->uuid = $uuid->generate('users', 'uuid'); $user->uuid = $uuid->generate('users', 'uuid');
@ -64,16 +65,25 @@ class UserRepository
* Updates a user on the panel. * Updates a user on the panel.
* *
* @param integer $id * @param integer $id
* @param array $user An array of columns and their associated values to update for the user. * @param array $data An array of columns and their associated values to update for the user.
* @return boolean * @return boolean
*/ */
public function update($id, array $user) public function update($id, array $data)
{ {
if(array_key_exists('password', $user)) { $validator = Validator::make($data, [
$user['password'] = Hash::make($user['password']); 'email' => 'email|unique:users,email,' . $id,
'password' => 'regex:((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,})',
'root_admin' => 'boolean',
'language' => 'string|min:1|max:5',
'use_totp' => 'boolean',
'totp_secret' => 'size:16'
]);
if(array_key_exists('password', $data)) {
$user['password'] = Hash::make($data['password']);
} }
return User::find($id)->update($user); return Models\User::find($id)->update($data);
} }
/** /**
@ -84,9 +94,22 @@ class UserRepository
*/ */
public function delete($id) public function delete($id)
{ {
// @TODO cannot delete user with associated servers! if(Models\Server::where('owner', $id)->count() > 0) {
// clean up subusers! throw new DisplayException('Cannot delete a user with active servers attached to thier account.');
return User::destroy($id); }
DB::beginTransaction();
Models\Permission::where('user_id', $id)->delete();
Models\Subuser::where('user_id', $id)->delete();
Models\User::destroy($id);
try {
DB::commit();
return true;
} catch (\Exception $ex) {
throw $ex;
}
} }
} }