More complete implementation of database management in panel.

Still missing ability to change passwords for databases, but that will
come soon.
This commit is contained in:
Dane Everitt 2016-02-14 21:43:20 -05:00
parent e14d1d3c95
commit 217762a2eb
10 changed files with 384 additions and 42 deletions

View File

@ -23,9 +23,14 @@
*/
namespace Pterodactyl\Http\Controllers\Admin;
use Alert;
use DB;
use Log;
use Pterodactyl\Models;
use Pterodactyl\Repositories\DatabaseRepository;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Exceptions\DisplayValidationException;
use Pterodactyl\Http\Controllers\Controller;
use Illuminate\Http\Request;
@ -62,4 +67,64 @@ class DatabaseController extends Controller
]);
}
public function getNew(Request $request)
{
return view('admin.databases.new', [
'nodes' => Models\Node::select('nodes.id', 'nodes.name', 'locations.long as a_location')
->join('locations', 'locations.id', '=', 'nodes.location')
->get()
]);
}
public function postNew(Request $request)
{
try {
$repo = new DatabaseRepository;
$repo->add($request->except([
'_token'
]));
Alert::success('Successfully added a new database server to the system.')->flash();
return redirect()->route('admin.databases', [
'tab' => 'tab_dbservers'
]);
} catch (DisplayValidationException $ex) {
return redirect()->route('admin.databases.new')->withErrors(json_decode($ex->getMessage()))->withInput();
} catch (\Exception $ex) {
if ($ex instanceof DisplayException || $ex instanceof \PDOException) {
Alert::danger($ex->getMessage())->flash();
} else {
Log::error($ex);
Alert::danger('An error occurred while attempting to delete this database server from the system.')->flash();
}
return redirect()->route('admin.databases.new')->withInput();
}
}
public function deleteDatabase(Request $request, $id)
{
try {
$repo = new DatabaseRepository;
$repo->drop($id);
} catch (\Exception $ex) {
Log::error($ex);
return response()->json([
'error' => ($ex instanceof DisplayException) ? $ex->getMessage() : 'An error occurred while attempting to delete this database from the system.'
], 500);
}
}
public function deleteServer(Request $request, $id)
{
try {
$repo = new DatabaseRepository;
$repo->delete($id);
} catch (\Exception $ex) {
Log::error($ex);
return response()->json([
'error' => ($ex instanceof DisplayException) ? $ex->getMessage() : 'An error occurred while attempting to delete this database server from the system.'
], 500);
}
}
}

View File

@ -413,18 +413,4 @@ class ServersController extends Controller
])->withInput();
}
public function deleteDatabase(Request $request, $id, $database)
{
try {
$repo = new DatabaseRepository;
$repo->drop($database);
return response('', 204);
} catch (\Exception $ex) {
Log::error($ex);
return response()->json([
'error' => 'An exception occured while attempting to delete this database.'
], 500);
}
}
}

View File

@ -228,6 +228,10 @@ class ServerController extends Controller
return view('server.settings', [
'server' => $server,
'databases' => Models\Database::select('databases.*', 'database_servers.host as a_host', 'database_servers.port as a_port')
->where('server', $server->id)
->join('database_servers', 'database_servers.id', '=', 'databases.db_server')
->get(),
'node' => Models\Node::find($server->node),
'variables' => $variables->where('user_viewable', 1),
'service' => $service,

View File

@ -158,10 +158,6 @@ class AdminRoutes {
'uses' => 'Admin\ServersController@postDatabase'
]);
$router->delete('/view/{id}/database/{database}', [
'uses' => 'Admin\ServersController@deleteDatabase'
]);
// Change Server Details
$router->post('/view/{id}/details', [
'uses' => 'Admin\ServersController@postUpdateServerDetails'
@ -328,6 +324,14 @@ class AdminRoutes {
$router->post('/new', [
'uses' => 'Admin\DatabaseController@postNew'
]);
$router->delete('/delete/{id}', [
'as' => 'admin.databases.delete',
'uses' => 'Admin\DatabaseController@deleteDatabase'
]);
$router->delete('/delete-server/{id}', [
'as' => 'admin.databases.delete-server',
'uses' => 'Admin\DatabaseController@deleteServer'
]);
});
}

View File

@ -434,4 +434,20 @@ class ServerPolicy
return $user->permissions()->server($server)->permission('reset-sftp')->exists();
}
/**
* Check if user has permission to view databases for a server.
*
* @param Pterodactyl\Models\User $user
* @param Pterodactyl\Models\Server $server
* @return boolean
*/
public function viewDatabases(User $user, Server $server)
{
if ($this->isOwner($user, $server)) {
return true;
}
return $user->permissions()->server($server)->permission('view-databases')->exists();
}
}

View File

@ -24,6 +24,7 @@
namespace Pterodactyl\Repositories;
use Crypt;
use Log;
use DB;
use Validator;
@ -56,21 +57,20 @@ class DatabaseRepository {
DB::beginTransaction();
$db = new Models\Database;
$db->fill([
'server' => $server->id,
'db_server' => $options['db_server'],
'database' => $server->uuidShort . '_' . $options['database'],
'username' => $server->uuidShort . '_' . str_random(7),
'remote' => $options['remote'],
'password' => Crypt::encrypt(str_random(20))
]);
$db->save();
// Contact Remote
$dbr = Models\DatabaseServer::findOrFail($options['db_server']);
try {
$db = new Models\Database;
$db->fill([
'server' => $server->id,
'db_server' => $options['db_server'],
'database' => $server->uuidShort . '_' . $options['database'],
'username' => $server->uuidShort . '_' . str_random(7),
'remote' => $options['remote'],
'password' => Crypt::encrypt(str_random(20))
]);
$db->save();
// Contact Remote
$dbr = Models\DatabaseServer::findOrFail($options['db_server']);
$capsule = new Capsule;
$capsule->addConnection([
@ -82,7 +82,10 @@ class DatabaseRepository {
'password' => Crypt::decrypt($dbr->password),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => ''
'prefix' => '',
'options' => [
\PDO::ATTR_TIMEOUT => 3,
]
]);
$capsule->setAsGlobal();
@ -110,10 +113,9 @@ class DatabaseRepository {
$db = Models\Database::findOrFail($database);
$dbr = Models\DatabaseServer::findOrFail($db->db_server);
DB::beginTransaction();
try {
DB::beginTransaction();
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'mysql',
@ -124,7 +126,10 @@ class DatabaseRepository {
'password' => Crypt::decrypt($dbr->password),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => ''
'prefix' => '',
'options' => [
\PDO::ATTR_TIMEOUT => 3,
]
]);
$capsule->setAsGlobal();
@ -143,4 +148,83 @@ class DatabaseRepository {
}
/**
* Deletes a database server from the system if it is empty.
* @param int $server The ID of the Database Server.
* @return
*/
public function delete($server)
{
$dbh = Models\DatabaseServer::findOrFail($server);
$databases = Models\Database::where('db_server', $dbh->id)->count();
if ($databases > 0) {
throw new DisplayException('You cannot delete a database server that has active databases attached to it.');
}
return $dbh->delete();
}
/**
* Adds a new Database Server to the system.
* @param array $data
*/
public function add(array $data)
{
$validator = Validator::make($data, [
'name' => 'required|string|max:255',
'host' => 'required|ip|unique:database_servers,host',
'port' => 'required|numeric|between:1,65535',
'username' => 'required|string|max:32',
'password' => 'required|string',
'linked_node' => 'sometimes',
]);
if ($validator->fails()) {
throw new DisplayValidationException($validator->errors());
}
DB::beginTransaction();
try {
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'mysql',
'host' => $data['host'],
'port' => $data['port'],
'database' => 'mysql',
'username' => $data['username'],
'password' => $data['password'],
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'options' => [
\PDO::ATTR_TIMEOUT => 3,
]
]);
$capsule->setAsGlobal();
// Allows us to check that we can connect to things.
Capsule::select('SELECT 1 FROM dual');
$dbh = new Models\DatabaseServer;
$dbh->fill([
'name' => $data['name'],
'host' => $data['host'],
'port' => $data['port'],
'username' => $data['username'],
'password' => Crypt::encrypt($data['password']),
'max_databases' => NULL,
'linked_node' => (!empty($data['linked_node']) && $data['linked_node'] > 0) ? $data['linked_node'] : NULL
]);
$dbh->save();
DB::commit();
} catch (\Exception $ex) {
DB::rollBack();
throw $ex;
}
}
}

View File

@ -20,7 +20,7 @@
@extends('layouts.admin')
@section('title')
Server List
Database Management
@endsection
@section('content')
@ -32,7 +32,8 @@
<h3>Manage Databases</h3><hr />
<ul class="nav nav-tabs tabs_with_panel" id="config_tabs">
<li class="active"><a href="#tab_databases" data-toggle="tab">Databases</a></li>
<li><a href="#tb_dbservers" data-toggle="tab">Database Servers</a></li>
<li><a href="#tab_dbservers" data-toggle="tab">Database Servers</a></li>
<li><a href="{{ route('admin.databases.new') }}"><i class="fa fa-plus"></i></a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab_databases">
@ -47,6 +48,7 @@
<th>Username</th>
<th>Connection</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
@ -57,6 +59,7 @@
<td>{{ $db->username }} ({{ $db->remote }})</td>
<td><code>{{ $db->a_host }}:{{ $db->a_port }}</code></td>
<td class="text-center"><a href="/admin/servers/view/{{ $db->a_serverId }}?tab=tab_database"><i class="fa fa-search"></i></a></td>
<td class="text-center"><a href="#" data-action="delete" data-type="delete" data-attr="{{ $db->id }}" class="text-danger"><i class="fa fa-trash-o"></i></a></td>
</tr>
@endforeach
</tbody>
@ -67,7 +70,7 @@
</div>
</div>
</div>
<div class="tab-pane" id="tb_dbservers">
<div class="tab-pane" id="tab_dbservers">
<div class="panel panel-default">
<div class="panel-heading"></div>
<div class="panel-body">
@ -90,7 +93,7 @@
<td>{{ $db->username }}</td>
<td class="text-center">{{ $db->c_databases }}</td>
<td>@if(is_null($db->a_linkedNode))<em>unlinked</em>@else{{ $db->a_linkedNode }}@endif</td>
<td class="text-center"><a href="#" class="text-danger"><i class="fa fa-trash-o"></i></a></td>
<td class="text-center"><a href="#" class="text-danger" data-action="delete" data-type="delete-dbserver" data-attr="{{ $db->id }}"><i class="fa fa-trash-o"></i></a></td>
</tr>
@endforeach
</tbody>
@ -106,6 +109,41 @@
<script>
$(document).ready(function () {
$('#sidebar_links').find("a[href='/admin/databases']").addClass('active');
$('[data-action="delete"]').click(function (event) {
event.preventDefault();
var self = $(this);
swal({
title: '',
type: 'warning',
text: 'Are you sure that you want to remove this database from the system?',
showCancelButton: true,
confirmButtonText: 'Delete',
confirmButtonColor: '#d9534f',
closeOnConfirm: false
}, function () {
$.ajax({
method: 'DELETE',
url: '{{ route('admin.databases') }}/' + self.data('type') + '/' + self.data('attr'),
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
}).done(function () {
self.parent().parent().slideUp();
swal({
title: '',
type: 'success',
text: ''
});
}).fail(function (jqXHR) {
console.error(jqXHR);
swal({
type: 'error',
title: 'Whoops!',
text: (typeof jqXHR.responseJSON.error !== 'undefined') ? jqXHR.responseJSON.error : 'An error occured while processing this request.'
});
});
});
});
});
</script>
@endsection

View File

@ -0,0 +1,103 @@
{{-- Copyright (c) 2015 - 2016 Dane Everitt <dane@daneeveritt.com> --}}
{{-- Permission is hereby granted, free of charge, to any person obtaining a copy --}}
{{-- of this software and associated documentation files (the "Software"), to deal --}}
{{-- in the Software without restriction, including without limitation the rights --}}
{{-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell --}}
{{-- copies of the Software, and to permit persons to whom the Software is --}}
{{-- furnished to do so, subject to the following conditions: --}}
{{-- The above copyright notice and this permission notice shall be included in all --}}
{{-- copies or substantial portions of the Software. --}}
{{-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR --}}
{{-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, --}}
{{-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE --}}
{{-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER --}}
{{-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, --}}
{{-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE --}}
{{-- SOFTWARE. --}}
@extends('layouts.admin')
@section('title')
Add New Database Server
@endsection
@section('content')
<div class="col-md-12">
<ul class="breadcrumb">
<li><a href="/admin">Admin Control</a></li>
<li><a href="/admin/databases">Databases</a></li>
<li class="active">New Database Server</li>
</ul>
<h3>New Database Server</h3><hr />
<div class="alert alert-info">If you are trying to add a new database to an existing server please visit that server's control page and visit the 'Databases' tab. This page is for adding a new database server that individual per-server databases can be deployed to.</div>
<form action="{{ route('admin.databases.new') }}" method="POST">
<div class="row">
<div class="form-group col-xs-6">
<label class="control-label">Descriptive Name:</label>
<div>
<input type="text" class="form-control" name="name" value="{{ old('name') }}" />
<p class="text-muted"><small>Enter a descriptive name for this database server.</small></p>
</div>
</div>
<div class="form-group col-xs-6">
<label class="control-label">Linked Node:</label>
<div>
<select name="linked_node" class="form-control">
<option>None</option>
@foreach($nodes as $node)
<option value="{{ $node->id }}" @if((int) old('linked_node') === $node->id) selected="selected" @endif>{{ $node->name }} ({{ $node->a_location }})</option>
@endforeach
</select>
<p class="text-muted"><small>A linked node implies that this Database Server is running on that node and it will be auto-selected when adding a database to servers on that node.</small></p>
</div>
</div>
</div>
<hr />
<div class="row">
<div class="form-group col-xs-6">
<label class="control-label">Database Host:</label>
<div>
<input type="text" class="form-control" name="host" value="{{ old('host') }}" />
<p class="text-muted"><small>Enter the IP address that this database server is listening on.</small></p>
</div>
</div>
<div class="form-group col-xs-6">
<label class="control-label">Database Port:</label>
<div>
<input type="text" class="form-control" name="port" value="{{ old('port', 3306) }}" />
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label class="control-label">Database Username:</label>
<div>
<input type="text" class="form-control" name="username" value="{{ old('username') }}" />
<p class="text-muted"><small>The panel must be able to access this database, you may need to allow access from <code>{{ Request::server('SERVER_ADDR') }}</code> for this user.</small></p>
</div>
</div>
<div class="form-group col-md-6">
<label class="control-label">Database User Passwod:</label>
<div>
<input type="password" class="form-control" autocomplete="off" name="password" />
</div>
</div>
</div>
<div class="well well-sm">
<div class="row">
<div class="col-md-12">
{!! csrf_field() !!}
<input type="submit" value="Add Database Server" class="btn btn-sm btn-primary" />
</div>
</div>
</div>
</form>
</div>
<script>
$(document).ready(function () {
$('#sidebar_links').find("a[href='/admin/databases']").addClass('active');
});
</script>
@endsection

View File

@ -509,7 +509,7 @@ $(document).ready(function () {
}, function () {
$.ajax({
method: 'DELETE',
url: '{{ route('admin.servers.database', $server->id) }}/' + self.data('database'),
url: '{{ route('admin.databases') }}/delete/' + self.data('database'),
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}

View File

@ -29,6 +29,7 @@
<ul class="nav nav-tabs tabs_with_panel" id="config_tabs">
@can('view-sftp', $server)<li class="active"><a href="#tab_sftp" data-toggle="tab">SFTP Settings</a></li>@endcan
@can('view-startup', $server)<li><a href="#tab_startup" data-toggle="tab">Startup Configuration</a></li>@endcan
@can('view-databases', $server)<li><a href="#tab_databases" data-toggle="tab">Databases</a></li>@endcan
</ul>
<div class="tab-content">
@can('view-sftp', $server)
@ -128,6 +129,47 @@
</form>
</div>
@endcan
@can('view-databases', $server)
<div class="tab-pane active" id="tab_databases">
<div class="panel panel-default">
<div class="panel-heading"></div>
<div class="panel-body">
@if(count($databases) > 0)
<table class="table table-bordered table-hover" style="margin-bottom:0;">
<thead>
<tr>
<th>Database</th>
<th>User (Connections From)</th>
<th>Password</th>
<th>DB Server</th>
</th>
</thead>
<tbody>
@foreach($databases as $database)
<tr>
<td>{{ $database->database }}</td>
<td>{{ $database->username }} ({{ $database->remote }})</td>
<td><code>{{ Crypt::decrypt($database->password) }}</code></td>
<td><code>{{ $database->a_host }}:{{ $database->a_port }}</code></td>
</tr>
@endforeach
</tbody>
</table>
@else
<div class="alert alert-info" style="margin-bottom:0;">
There are no databases configured for this server.
@if(Auth::user()->root_admin === 1)
<a href="{{ route('admin.servers.view', [
'id' => $server->id,
'tab' => 'tab_database'
]) }}" target="_blank">Add a new database.</a>
@endif
</div>
@endif
</div>
</div>
</div>
@endcan
</div>
</div>
<script>