Move everything back to vue SFCs

This commit is contained in:
Dane Everitt 2019-02-09 21:14:58 -08:00
parent 761704408e
commit 5bff8d99cc
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
58 changed files with 2558 additions and 2518 deletions

View file

@ -1,89 +0,0 @@
import Vue from 'vue';
import MessageBox from "./MessageBox";
export default Vue.component('flash', {
components: {
MessageBox
},
props: {
container: {type: String, default: ''},
timeout: {type: Number, default: 0},
types: {
type: Object,
default: function () {
return {
base: 'alert',
success: 'alert success',
info: 'alert info',
warning: 'alert warning',
error: 'alert error',
}
}
}
},
data: function () {
return {
notifications: [],
};
},
/**
* Listen for flash events.
*/
created: function () {
const self = this;
window.events.$on('flash', function (data: any) {
self.flash(data.message, data.title, data.severity);
});
window.events.$on('clear-flashes', function () {
self.clear();
});
},
methods: {
/**
* Flash a message to the screen when a flash event is emitted over
* the global event stream.
*/
flash: function (message: string, title: string, severity: string) {
this.$data.notifications.push({
message, severity, title, class: this.$props.types[severity] || this.$props.types.base,
});
if (this.$props.timeout > 0) {
setTimeout(this.hide, this.$props.timeout);
}
},
/**
* Clear all of the flash messages from the screen.
*/
clear: function () {
this.notifications = [];
window.events.$emit('flashes-cleared');
},
/**
* Hide a notification after a given amount of time.
*/
hide: function (item?: number) {
let key = this.$data.notifications.indexOf(item || this.$data.notifications[0]);
this.$data.notifications.splice(key, 1);
},
},
template: `
<div v-if="notifications.length > 0" :class="this.container">
<transition-group tag="div" name="fade">
<div v-for="(item, index) in notifications" :key="index">
<message-box
:class="[item.class, {'mb-2': index < notifications.length - 1}]"
:title="item.title"
:message="item.message"
/>
</div>
</transition-group>
</div>
`,
})

View file

@ -0,0 +1,103 @@
<template>
<div v-if="notifications.length > 0" :class="this.container">
<transition-group tag="div" name="fade">
<div v-for="(item, index) in notifications" :key="item.title">
<MessageBox
:class="[item.class, {'mb-2': index < notifications.length - 1}]"
:title="item.title"
:message="item.message"
/>
</div>
</transition-group>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import MessageBox from './MessageBox.vue';
type DataStructure = {
notifications: Array<{
message: string,
severity: string,
title: string,
class: string,
}>,
}
export default Vue.extend({
name: 'Flash',
components: {
MessageBox
},
props: {
container: {type: String, default: ''},
timeout: {type: Number, default: 0},
types: {
type: Object,
default: function () {
return {
base: 'alert',
success: 'alert success',
info: 'alert info',
warning: 'alert warning',
error: 'alert error',
}
}
}
},
data: function (): DataStructure {
return {
notifications: [],
};
},
/**
* Listen for flash events.
*/
created: function () {
const self = this;
window.events.$on('flash', function (data: any) {
self.flash(data.message, data.title, data.severity);
});
window.events.$on('clear-flashes', function () {
self.clear();
});
},
methods: {
/**
* Flash a message to the screen when a flash event is emitted over
* the global event stream.
*/
flash: function (message: string, title: string, severity: string) {
this.notifications.push({
message, severity, title, class: this.$props.types[severity] || this.$props.types.base,
});
if (this.$props.timeout > 0) {
setTimeout(this.hide, this.$props.timeout);
}
},
/**
* Clear all of the flash messages from the screen.
*/
clear: function () {
this.notifications = [];
window.events.$emit('flashes-cleared');
},
/**
* Hide a notification after a given amount of time.
*/
hide: function (item?: number) {
// @ts-ignore
let key = this.notifications.indexOf(item || this.notifications[0]);
this.notifications.splice(key, 1);
},
},
});
</script>

View file

@ -1,14 +0,0 @@
import Vue from 'vue';
export default Vue.component('message-box', {
props: {
title: {type: String, required: false},
message: {type: String, required: true}
},
template: `
<div class="lg:inline-flex" role="alert">
<span class="title" v-html="title" v-if="title && title.length > 0"></span>
<span class="message" v-html="message"></span>
</div>
`,
})

View file

@ -0,0 +1,18 @@
<template>
<div class="lg:inline-flex" role="alert">
<span class="title" v-html="title" v-if="title && title.length > 0"></span>
<span class="message" v-html="message"></span>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
export default Vue.extend({
name: 'MessageBox',
props: {
title: {type: String, required: false},
message: {type: String, required: true}
},
});
</script>

View file

@ -1,93 +0,0 @@
import Vue from 'vue';
import {isObject} from 'lodash';
import {AxiosError, AxiosResponse} from "axios";
export default Vue.component('forgot-password', {
props: {
email: {type: String, required: true},
},
mounted: function () {
(this.$refs.email as HTMLElement).focus();
},
data: function () {
return {
X_CSRF_TOKEN: window.X_CSRF_TOKEN,
errors: [],
submitDisabled: false,
showSpinner: false,
};
},
methods: {
updateEmail: function (event: { target: HTMLInputElement }) {
this.$data.submitDisabled = false;
this.$emit('update-email', event.target.value);
},
submitForm: function () {
this.$data.submitDisabled = true;
this.$data.showSpinner = true;
this.$data.errors = [];
this.$flash.clear();
window.axios.post(this.route('auth.forgot-password'), {
email: this.$props.email,
})
.then((response: AxiosResponse) => {
if (!(response.data instanceof Object)) {
throw new Error('An error was encountered while processing this request.');
}
this.$data.submitDisabled = false;
this.$data.showSpinner = false;
this.$flash.success(response.data.status);
this.$router.push({name: 'login'});
})
.catch((err: AxiosError) => {
this.$data.showSpinner = false;
if (!err.response) {
return console.error(err);
}
const response = err.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
}
});
}
},
template: `
<form class="login-box" method="post" v-on:submit.prevent="submitForm">
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input open-label" id="grid-email" type="email" aria-labelledby="grid-email-label" required
ref="email"
v-bind:class="{ 'has-content': email.length > 0 }"
v-bind:readonly="showSpinner"
v-bind:value="email"
v-on:input="updateEmail($event)"
/>
<label for="grid-email" id="grid-email-label">{{ $t('strings.email') }}</label>
<p class="text-neutral-800 text-xs">{{ $t('auth.forgot_password.label_help') }}</p>
</div>
</div>
<div>
<button class="btn btn-primary btn-jumbo" type="submit" v-bind:disabled="submitDisabled">
<span class="spinner white" v-bind:class="{ hidden: ! showSpinner }">&nbsp;</span>
<span v-bind:class="{ hidden: showSpinner }">
{{ $t('auth.forgot_password.button') }}
</span>
</button>
</div>
<div class="pt-6 text-center">
<router-link class="text-xs text-neutral-500 tracking-wide no-underline uppercase hover:text-neutral-600"
aria-label="Go to login"
:to="{ name: 'login' }"
>
{{ $t('auth.go_to_login') }}
</router-link>
</div>
</form>
`,
})

View file

@ -0,0 +1,100 @@
<template>
<form class="login-box" method="post" v-on:submit.prevent="submitForm">
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input open-label" id="grid-email" type="email" aria-labelledby="grid-email-label" required
ref="email"
v-bind:class="{ 'has-content': email.length > 0 }"
v-bind:readonly="showSpinner"
v-bind:value="email"
v-on:input="updateEmail($event)"
/>
<label for="grid-email" id="grid-email-label">{{ $t('strings.email') }}</label>
<p class="text-neutral-800 text-xs">{{ $t('auth.forgot_password.label_help') }}</p>
</div>
</div>
<div>
<button class="btn btn-primary btn-jumbo" type="submit" v-bind:disabled="submitDisabled">
<span class="spinner white" v-bind:class="{ hidden: ! showSpinner }">&nbsp;</span>
<span v-bind:class="{ hidden: showSpinner }">
{{ $t('auth.forgot_password.button') }}
</span>
</button>
</div>
<div class="pt-6 text-center">
<router-link class="text-xs text-neutral-500 tracking-wide no-underline uppercase hover:text-neutral-600"
aria-label="Go to login"
:to="{ name: 'login' }"
>
{{ $t('auth.go_to_login') }}
</router-link>
</div>
</form>
</template>
<script lang="ts">
import Vue from 'vue';
import {isObject} from 'lodash';
import {AxiosError, AxiosResponse} from "axios";
export default Vue.extend({
name: 'ForgotPassword',
mounted: function () {
if (this.$refs.email) {
(this.$refs.email as HTMLElement).focus();
}
},
data: function () {
return {
X_CSRF_TOKEN: window.X_CSRF_TOKEN,
errors: [],
submitDisabled: false,
showSpinner: false,
email: '',
};
},
methods: {
updateEmail: function (event: { target: HTMLInputElement }) {
this.submitDisabled = false;
this.$emit('update-email', event.target.value);
},
submitForm: function () {
this.submitDisabled = true;
this.showSpinner = true;
this.errors = [];
this.$flash.clear();
window.axios.post(this.route('auth.forgot-password'), {
email: this.email,
})
.then((response: AxiosResponse) => {
if (!(response.data instanceof Object)) {
throw new Error('An error was encountered while processing this request.');
}
this.submitDisabled = false;
this.showSpinner = false;
this.$flash.success(response.data.status);
this.$router.push({name: 'login'});
})
.catch((err: AxiosError) => {
this.showSpinner = false;
if (!err.response) {
return console.error(err);
}
const response = err.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
}
});
}
},
});
</script>

View file

@ -1,42 +0,0 @@
import Vue from 'vue';
import LoginForm from "./LoginForm";
import ForgotPassword from "./ForgotPassword";
import TwoFactorForm from "./TwoFactorForm";
import Flash from "../Flash";
export default Vue.component('login', {
data: function () {
return {
user: {
email: ''
},
};
},
components: {
Flash,
LoginForm,
ForgotPassword,
TwoFactorForm,
},
methods: {
onUpdateEmail: function (value: string) {
this.$data.user.email = value;
},
},
template: `
<div>
<flash container="mb-2"/>
<login-form
v-if="this.$route.name === 'login'"
v-bind:user="user"
v-on:update-email="onUpdateEmail"
/>
<forgot-password
v-if="this.$route.name === 'forgot-password'"
v-bind:email="user.email"
v-on:update-email="onUpdateEmail"
/>
<two-factor-form v-if="this.$route.name === 'checkpoint'" />
</div>
`,
});

View file

@ -0,0 +1,18 @@
<template>
<div>
<Flash container="mb-2"/>
<div>
<router-view/>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import Flash from "../Flash.vue";
export default Vue.extend({
name: 'Login',
components: {Flash},
});
</script>

View file

@ -1,112 +0,0 @@
import Vue from 'vue';
import {isObject} from 'lodash';
export default Vue.component('login-form', {
props: {
user: {
type: Object,
required: false,
default: function () {
return {
email: '',
password: '',
};
},
}
},
data: function () {
return {
showSpinner: false,
}
},
mounted: function () {
(this.$refs.email as HTMLElement).focus();
},
methods: {
// Handle a login request eminating from the form. If 2FA is required the
// user will be presented with the 2FA modal window.
submitForm: function () {
this.$data.showSpinner = true;
this.$flash.clear();
this.$store.dispatch('auth/login', {user: this.$props.user.email, password: this.$props.user.password})
.then(response => {
if (response.complete) {
return window.location = response.intended;
}
this.$props.user.password = '';
this.$data.showSpinner = false;
this.$router.push({name: 'checkpoint', query: {token: response.token}});
})
.catch(err => {
this.$props.user.password = '';
this.$data.showSpinner = false;
(this.$refs.password as HTMLElement).focus();
this.$store.commit('auth/logout');
if (!err.response) {
this.$flash.error('There was an error with the network request. Please try again.');
return console.error(err);
}
const response = err.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
}
});
},
// Update the email address associated with the login form
// so that it is populated in the parent model automatically.
updateEmail: function (event: { target: HTMLInputElement }) {
this.$emit('update-email', event.target.value);
}
},
template: `
<form class="login-box" method="post"
v-on:submit.prevent="submitForm"
>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input open-label" id="grid-username" type="text" name="user" aria-labelledby="grid-username-label" required
ref="email"
:class="{ 'has-content' : user.email.length > 0 }"
:readonly="showSpinner"
:value="user.email"
v-on:input="updateEmail($event)"
/>
<label id="grid-username-label" for="grid-username">{{ $t('strings.user_identifier') }}</label>
</div>
</div>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input open-label" id="grid-password" type="password" name="password" aria-labelledby="grid-password-label" required
ref="password"
:class="{ 'has-content' : user.password && user.password.length > 0 }"
:readonly="showSpinner"
v-model="user.password"
/>
<label id="grid-password-label" for="grid-password">{{ $t('strings.password') }}</label>
</div>
</div>
<div>
<button id="grid-login-button" class="btn btn-primary btn-jumbo" type="submit" aria-label="Log in"
v-bind:disabled="showSpinner">
<span class="spinner white" v-bind:class="{ hidden: ! showSpinner }">&nbsp;</span>
<span v-bind:class="{ hidden: showSpinner }">
{{ $t('auth.sign_in') }}
</span>
</button>
</div>
<div class="pt-6 text-center">
<router-link class="text-xs text-neutral-500 tracking-wide no-underline uppercase hover:text-neutral-600" aria-label="Forgot password"
:to="{ name: 'forgot-password' }">
{{ $t('auth.forgot_password.label') }}
</router-link>
</div>
</form>
`,
});

View file

@ -0,0 +1,104 @@
<template>
<form class="login-box" method="post"
v-on:submit.prevent="submitForm"
>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input open-label" id="grid-username" type="text" name="user" aria-labelledby="grid-username-label" required
ref="email"
:class="{ 'has-content' : user.email.length > 0 }"
:readonly="showSpinner"
v-model="user.email"
/>
<label id="grid-username-label" for="grid-username">{{ $t('strings.user_identifier') }}</label>
</div>
</div>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input open-label" id="grid-password" type="password" name="password" aria-labelledby="grid-password-label" required
ref="password"
:class="{ 'has-content' : user.password && user.password.length > 0 }"
:readonly="showSpinner"
v-model="user.password"
/>
<label id="grid-password-label" for="grid-password">{{ $t('strings.password') }}</label>
</div>
</div>
<div>
<button id="grid-login-button" class="btn btn-primary btn-jumbo" type="submit" aria-label="Log in"
v-bind:disabled="showSpinner">
<span class="spinner white" v-bind:class="{ hidden: ! showSpinner }">&nbsp;</span>
<span v-bind:class="{ hidden: showSpinner }">
{{ $t('auth.sign_in') }}
</span>
</button>
</div>
<div class="pt-6 text-center">
<router-link class="text-xs text-neutral-500 tracking-wide no-underline uppercase hover:text-neutral-600" aria-label="Forgot password"
:to="{ name: 'forgot-password' }">
{{ $t('auth.forgot_password.label') }}
</router-link>
</div>
</form>
</template>
<script lang="ts">
import Vue from 'vue';
import {isObject} from 'lodash';
export default Vue.extend({
name: 'LoginForm',
data: function () {
return {
showSpinner: false,
user: {
email: '',
password: '',
}
}
},
mounted: function () {
(this.$refs.email as HTMLElement).focus();
},
methods: {
// Handle a login request eminating from the form. If 2FA is required the
// user will be presented with the 2FA modal window.
submitForm: function () {
this.showSpinner = true;
this.$flash.clear();
this.$store.dispatch('auth/login', {user: this.user.email, password: this.user.password})
.then(response => {
if (response.complete) {
return window.location = response.intended;
}
this.user.password = '';
this.showSpinner = false;
this.$router.push({name: 'checkpoint', query: {token: response.token}});
})
.catch(err => {
this.user.password = '';
this.showSpinner = false;
(this.$refs.password as HTMLElement).focus();
this.$store.commit('auth/logout');
if (!err.response) {
this.$flash.error('There was an error with the network request. Please try again.');
return console.error(err);
}
const response = err.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
}
});
},
},
});
</script>

View file

@ -1,121 +0,0 @@
import Vue from 'vue';
import {isObject} from 'lodash';
import {AxiosError, AxiosResponse} from "axios";
export default Vue.component('reset-password', {
props: {
token: {type: String, required: true},
email: {type: String, required: false},
},
mounted: function () {
if (this.$props.email.length > 0) {
(this.$refs.email as HTMLElement).setAttribute('value', this.$props.email);
(this.$refs.password as HTMLElement).focus();
}
},
data: function () {
return {
errors: [],
showSpinner: false,
password: '',
passwordConfirmation: '',
};
},
methods: {
updateEmailField: function (event: { target: HTMLInputElement }) {
this.$data.submitDisabled = event.target.value.length === 0;
},
submitForm: function () {
this.$data.showSpinner = true;
this.$flash.clear();
window.axios.post(this.route('auth.reset-password'), {
email: this.$props.email,
password: this.$data.password,
password_confirmation: this.$data.passwordConfirmation,
token: this.$props.token,
})
.then((response: AxiosResponse) => {
if (!(response.data instanceof Object)) {
throw new Error('An error was encountered while processing this login.');
}
if (response.data.send_to_login) {
this.$flash.success('Your password has been reset, please login to continue.');
return this.$router.push({ name: 'login' });
}
return window.location = response.data.redirect_to;
})
.catch((err: AxiosError) => {
this.$data.showSpinner = false;
if (!err.response) {
return console.error(err);
}
const response = err.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
(this.$refs.password as HTMLElement).focus();
}
});
}
},
template: `
<form class="bg-white shadow-lg rounded-lg pt-10 px-8 pb-6 mb-4 animate fadein" method="post"
v-on:submit.prevent="submitForm"
>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input open-label" id="grid-email" type="email" aria-labelledby="grid-email" required
ref="email"
:class="{ 'has-content': email.length > 0 }"
:readonly="showSpinner"
v-on:input="updateEmailField"
/>
<label for="grid-email">{{ $t('strings.email') }}</label>
</div>
</div>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input open-label" id="grid-password" type="password" aria-labelledby="grid-password" required
ref="password"
:class="{ 'has-content' : password.length > 0 }"
:readonly="showSpinner"
v-model="password"
/>
<label for="grid-password">{{ $t('strings.password') }}</label>
<p class="text-neutral-800 text-xs">{{ $t('auth.password_requirements') }}</p>
</div>
</div>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input open-label" id="grid-password-confirmation" type="password" aria-labelledby="grid-password-confirmation" required
:class="{ 'has-content' : passwordConfirmation.length > 0 }"
:readonly="showSpinner"
v-model="passwordConfirmation"
/>
<label for="grid-password-confirmation">{{ $t('strings.confirm_password') }}</label>
</div>
</div>
<div>
<button class="btn btn-primary btn-jumbo" type="submit" v-bind:class="{ disabled: showSpinner }">
<span class="spinner white" v-bind:class="{ hidden: ! showSpinner }">&nbsp;</span>
<span v-bind:class="{ hidden: showSpinner }">
{{ $t('auth.reset_password.button') }}
</span>
</button>
</div>
<div class="pt-6 text-center">
<router-link class="text-xs text-neutral-500 tracking-wide no-underline uppercase hover:text-neutral-600"
:to="{ name: 'login' }"
>
{{ $t('auth.go_to_login') }}
</router-link>
</div>
</form>
`,
})

View file

@ -0,0 +1,128 @@
<template>
<form class="bg-white shadow-lg rounded-lg pt-10 px-8 pb-6 mb-4 animate fadein" method="post"
v-on:submit.prevent="submitForm"
>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input open-label" id="grid-email" type="email" aria-labelledby="grid-email" required
ref="email"
:class="{ 'has-content': email.length > 0 }"
:readonly="showSpinner"
v-on:input="updateEmailField"
/>
<label for="grid-email">{{ $t('strings.email') }}</label>
</div>
</div>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input open-label" id="grid-password" type="password" aria-labelledby="grid-password" required
ref="password"
:class="{ 'has-content' : password.length > 0 }"
:readonly="showSpinner"
v-model="password"
/>
<label for="grid-password">{{ $t('strings.password') }}</label>
<p class="text-neutral-800 text-xs">{{ $t('auth.password_requirements') }}</p>
</div>
</div>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input open-label" id="grid-password-confirmation" type="password" aria-labelledby="grid-password-confirmation" required
:class="{ 'has-content' : passwordConfirmation.length > 0 }"
:readonly="showSpinner"
v-model="passwordConfirmation"
/>
<label for="grid-password-confirmation">{{ $t('strings.confirm_password') }}</label>
</div>
</div>
<div>
<button class="btn btn-primary btn-jumbo" type="submit" v-bind:class="{ disabled: showSpinner }">
<span class="spinner white" v-bind:class="{ hidden: ! showSpinner }">&nbsp;</span>
<span v-bind:class="{ hidden: showSpinner }">
{{ $t('auth.reset_password.button') }}
</span>
</button>
</div>
<div class="pt-6 text-center">
<router-link class="text-xs text-neutral-500 tracking-wide no-underline uppercase hover:text-neutral-600"
:to="{ name: 'login' }"
>
{{ $t('auth.go_to_login') }}
</router-link>
</div>
</form>
</template>
<script lang="ts">
import Vue from 'vue';
import {isObject} from 'lodash';
import {AxiosError, AxiosResponse} from "axios";
export default Vue.component('reset-password', {
props: {
token: {type: String, required: true},
email: {type: String, required: false},
},
mounted: function () {
if (this.$props.email.length > 0) {
(this.$refs.email as HTMLElement).setAttribute('value', this.$props.email);
(this.$refs.password as HTMLElement).focus();
}
},
data: function () {
return {
errors: [],
showSpinner: false,
password: '',
passwordConfirmation: '',
submitDisabled: true,
};
},
methods: {
updateEmailField: function (event: { target: HTMLInputElement }) {
this.submitDisabled = event.target.value.length === 0;
},
submitForm: function () {
this.showSpinner = true;
this.$flash.clear();
window.axios.post(this.route('auth.reset-password'), {
email: this.$props.email,
password: this.password,
password_confirmation: this.passwordConfirmation,
token: this.$props.token,
})
.then((response: AxiosResponse) => {
if (!(response.data instanceof Object)) {
throw new Error('An error was encountered while processing this login.');
}
if (response.data.send_to_login) {
this.$flash.success('Your password has been reset, please login to continue.');
return this.$router.push({ name: 'login' });
}
return window.location = response.data.redirect_to;
})
.catch((err: AxiosError) => {
this.showSpinner = false;
if (!err.response) {
return console.error(err);
}
const response = err.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
(this.$refs.password as HTMLElement).focus();
}
});
}
},
});
</script>

View file

@ -1,80 +0,0 @@
import Vue from 'vue';
import {AxiosError, AxiosResponse} from "axios";
import {isObject} from 'lodash';
export default Vue.component('two-factor-form', {
data: function () {
return {
code: '',
};
},
mounted: function () {
if ((this.$route.query.token || '').length < 1) {
return this.$router.push({ name: 'login' });
}
(this.$refs.code as HTMLElement).focus();
},
methods: {
submitToken: function () {
this.$flash.clear();
window.axios.post(this.route('auth.login-checkpoint'), {
confirmation_token: this.$route.query.token,
authentication_code: this.$data.code,
})
.then((response: AxiosResponse) => {
if (!(response.data instanceof Object)) {
throw new Error('An error was encountered while processing this login.');
}
localStorage.setItem('token', response.data.token);
this.$store.dispatch('login');
window.location = response.data.intended;
})
.catch((err: AxiosError) => {
this.$store.dispatch('logout');
if (!err.response) {
return console.error(err);
}
const response = err.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
this.$router.push({ name: 'login' });
}
});
}
},
template: `
<form class="login-box" method="post"
v-on:submit.prevent="submitToken"
>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input open-label" id="grid-code" type="number" name="token" aria-labelledby="grid-username" required
ref="code"
:class="{ 'has-content' : code.length > 0 }"
v-model="code"
/>
<label for="grid-code">{{ $t('auth.two_factor.label') }}</label>
<p class="text-neutral-800 text-xs">{{ $t('auth.two_factor.label_help') }}</p>
</div>
</div>
<div>
<button class="btn btn-primary btn-jumbo" type="submit">
{{ $t('auth.sign_in') }}
</button>
</div>
<div class="pt-6 text-center">
<router-link class="text-xs text-neutral-500 tracking-wide no-underline uppercase hover:text-neutral-600"
:to="{ name: 'login' }"
>
Back to Login
</router-link>
</div>
</form>
`,
});

View file

@ -0,0 +1,87 @@
<template>
<form class="login-box" method="post"
v-on:submit.prevent="submitToken"
>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input open-label" id="grid-code" type="number" name="token" aria-labelledby="grid-username" required
ref="code"
:class="{ 'has-content' : code.length > 0 }"
v-model="code"
/>
<label for="grid-code">{{ $t('auth.two_factor.label') }}</label>
<p class="text-neutral-800 text-xs">{{ $t('auth.two_factor.label_help') }}</p>
</div>
</div>
<div>
<button class="btn btn-primary btn-jumbo" type="submit">
{{ $t('auth.sign_in') }}
</button>
</div>
<div class="pt-6 text-center">
<router-link class="text-xs text-neutral-500 tracking-wide no-underline uppercase hover:text-neutral-600"
:to="{ name: 'login' }"
>
Back to Login
</router-link>
</div>
</form>
</template>
<script lang="ts">
import Vue from 'vue';
import {AxiosError, AxiosResponse} from "axios";
import {isObject} from 'lodash';
export default Vue.extend({
name: 'TwoFactorForm',
data: function () {
return {
code: '',
};
},
mounted: function () {
if ((this.$route.query.token || '').length < 1) {
return this.$router.push({name: 'login'});
}
(this.$refs.code as HTMLElement).focus();
},
methods: {
submitToken: function () {
this.$flash.clear();
window.axios.post(this.route('auth.login-checkpoint'), {
confirmation_token: this.$route.query.token,
authentication_code: this.$data.code,
})
.then((response: AxiosResponse) => {
if (!(response.data instanceof Object)) {
throw new Error('An error was encountered while processing this login.');
}
localStorage.setItem('token', response.data.token);
this.$store.dispatch('login');
window.location = response.data.intended;
})
.catch((err: AxiosError) => {
this.$store.dispatch('logout');
if (!err.response) {
return console.error(err);
}
const response = err.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
this.$router.push({name: 'login'});
}
});
}
},
});
</script>

View file

@ -1,14 +0,0 @@
import Vue from 'vue';
import { replace } from 'feather-icons';
export default Vue.component('icon', {
props: {
name: {type: String, default: 'circle'},
},
mounted: function () {
replace();
},
template: `
<i :data-feather="name"></i>
`,
});

View file

@ -0,0 +1,18 @@
<template>
<i :data-feather="name"></i>
</template>
<script lang="ts">
import Vue from 'vue';
import { replace } from 'feather-icons';
export default Vue.extend({
name: 'Icon',
props: {
name: {type: String, default: 'circle'},
},
mounted: function () {
replace();
},
});
</script>

View file

@ -1,47 +0,0 @@
import Vue from 'vue';
import Icon from "./Icon";
export default Vue.component('modal', {
components: {
Icon,
},
props: {
modalName: { type: String, default: 'modal' },
show: { type: Boolean, default: false },
closeOnEsc: { type: Boolean, default: true },
},
mounted: function () {
if (this.$props.closeOnEsc) {
document.addEventListener('keydown', e => {
if (this.show && e.key === 'Escape') {
this.close();
}
})
}
},
methods: {
close: function () {
this.$emit('close', this.$props.modalName);
}
},
template: `
<transition name="modal">
<div class="modal-mask" v-show="show" v-on:click="close">
<div class="modal-container" @click.stop>
<div v-on:click="close">
<icon name="x"
class="absolute pin-r pin-t m-2 text-neutral-500 cursor-pointer"
aria-label="Close modal"
role="button"
/>
</div>
<slot/>
</div>
</div>
</transition>
`
})

View file

@ -0,0 +1,48 @@
<template>
<transition name="modal">
<div class="modal-mask" v-show="show" v-on:click="close">
<div class="modal-container" @click.stop>
<div v-on:click="close">
<Icon name="x"
class="absolute pin-r pin-t m-2 text-neutral-500 cursor-pointer"
aria-label="Close modal"
role="button"
/>
</div>
<slot/>
</div>
</div>
</transition>
</template>
<script lang="ts">
import Vue from 'vue';
import Icon from "./Icon.vue";
export default Vue.extend({
name: 'Modal',
components: {Icon},
props: {
modalName: { type: String, default: 'modal' },
show: { type: Boolean, default: false },
closeOnEsc: { type: Boolean, default: true },
},
mounted: function () {
if (this.$props.closeOnEsc) {
document.addEventListener('keydown', e => {
if (this.show && e.key === 'Escape') {
this.close();
}
})
}
},
methods: {
close: function () {
this.$emit('close', this.$props.modalName);
}
},
});
</script>

View file

@ -1,135 +0,0 @@
import Vue from 'vue';
import { debounce, isObject } from 'lodash';
import { mapState } from 'vuex';
import {AxiosError} from "axios";
export default Vue.component('navigation', {
data: function () {
return {
loadingResults: false,
searchActive: false,
};
},
computed: {
...mapState('dashboard', ['servers']),
searchTerm: {
get: function (): string {
return this.$store.getters['dashboard/getSearchTerm'];
},
set: function (value: string): void {
this.$store.dispatch('dashboard/setSearchTerm', value);
}
}
},
created: function () {
document.addEventListener('click', this.documentClick);
},
beforeDestroy: function () {
document.removeEventListener('click', this.documentClick);
},
methods: {
search: debounce(function (this: any): void {
if (this.searchTerm.length >= 3) {
this.loadingResults = true;
this.gatherSearchResults();
}
}, 500),
gatherSearchResults: function (): void {
this.$store.dispatch('dashboard/loadServers')
.catch((err: AxiosError) => {
console.error(err);
const response = err.response;
if (response && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
}
})
.then(() => {
this.loadingResults = false;
});
},
doLogout: function () {
this.$store.commit('auth/logout');
window.location.assign(this.route('auth.logout'));
},
documentClick: function (e: Event) {
if (this.$refs.searchContainer) {
if (this.$refs.searchContainer !== e.target && !(this.$refs.searchContainer as HTMLElement).contains(e.target as HTMLElement)) {
this.searchActive = false;
}
}
},
},
template: `
<div class="nav flex flex-grow">
<div class="flex flex-1 justify-center items-center container">
<div class="logo">
<router-link :to="{ name: 'dashboard' }">
Pterodactyl
</router-link>
</div>
<div class="menu flex-1">
<router-link :to="{ name: 'dashboard' }">
<icon name="server" aria-label="Server dashboard" class="h-4 self-center"/>
</router-link>
<router-link :to="{ name: 'account' }">
<icon name="user" aria-label="Profile management" class="h-4"/>
</router-link>
<a :href="this.route('admin.index')">
<icon name="settings" aria-label="Administrative controls" class="h-4"/>
</a>
</div>
<div class="search-box flex-none" v-if="$route.name !== 'dashboard'" ref="searchContainer">
<input type="text" class="search-input" id="searchInput" placeholder="Search..."
:class="{ 'has-search-results': ((servers.length > 0 && searchTerm.length >= 3) || loadingResults) && searchActive }"
v-on:focus="searchActive = true"
v-on:input="search"
v-model="searchTerm"
/>
<div class="search-results select-none" :class="{ 'hidden': (servers.length === 0 && !loadingResults) || !searchActive || searchTerm.length < 3 }">
<div v-if="loadingResults">
<a href="#" class="no-hover cursor-default">
<div class="flex items-center">
<div class="flex-1">
<span class="text-sm text-neutral-500">Loading...</span>
</div>
<div class="flex-none">
<span class="spinner spinner-relative"></span>
</div>
</div>
</a>
</div>
<div v-else v-for="server in servers" :key="server.identifier">
<router-link :to="{ name: 'server', params: { id: server.identifier }}" v-on:click.native="searchActive = false">
<div class="flex items-center">
<div class="flex-1">
<span class="font-bold text-neutral-900">{{ server.name }}</span><br />
<span class="text-neutral-600 text-sm" v-if="server.description.length > 0">{{ server.description }}</span>
</div>
<div class="flex-none">
<span class="pillbox bg-neutral-900">{{ server.node }}</span>
</div>
</div>
</router-link>
</div>
</div>
</div>
<div class="menu">
<a :href="this.route('auth.logout')" v-on:click.prevent="doLogout">
<icon name="log-out" aria-label="Sign out" class="h-4"/>
</a>
</div>
</div>
</div>
`
})

View file

@ -0,0 +1,142 @@
<template>
<div class="nav flex flex-grow">
<div class="flex flex-1 justify-center items-center container">
<div class="logo">
<router-link :to="{ name: 'dashboard' }">
Pterodactyl
</router-link>
</div>
<div class="menu flex-1">
<router-link :to="{ name: 'dashboard' }">
<Icon name="server" aria-label="Server dashboard" class="h-4 self-center"/>
</router-link>
<router-link :to="{ name: 'account' }">
<Icon name="user" aria-label="Profile management" class="h-4"/>
</router-link>
<a :href="this.route('admin.index')">
<Icon name="settings" aria-label="Administrative controls" class="h-4"/>
</a>
</div>
<div class="search-box flex-none" v-if="$route.name !== 'dashboard'" ref="searchContainer">
<input type="text" class="search-input" id="searchInput" placeholder="Search..."
:class="{ 'has-search-results': ((servers.length > 0 && searchTerm.length >= 3) || loadingResults) && searchActive }"
v-on:focus="searchActive = true"
v-on:input="search"
v-model="searchTerm"
/>
<div class="search-results select-none" :class="{ 'hidden': (servers.length === 0 && !loadingResults) || !searchActive || searchTerm.length < 3 }">
<div v-if="loadingResults">
<a href="#" class="no-hover cursor-default">
<div class="flex items-center">
<div class="flex-1">
<span class="text-sm text-neutral-500">Loading...</span>
</div>
<div class="flex-none">
<span class="spinner spinner-relative"></span>
</div>
</div>
</a>
</div>
<div v-else v-for="server in servers" :key="server.identifier">
<router-link :to="{ name: 'server', params: { id: server.identifier }}" v-on:click.native="searchActive = false">
<div class="flex items-center">
<div class="flex-1">
<span class="font-bold text-neutral-900">{{ server.name }}</span><br/>
<span class="text-neutral-600 text-sm" v-if="server.description.length > 0">{{ server.description }}</span>
</div>
<div class="flex-none">
<span class="pillbox bg-neutral-900">{{ server.node }}</span>
</div>
</div>
</router-link>
</div>
</div>
</div>
<div class="menu">
<a :href="this.route('auth.logout')" v-on:click.prevent="doLogout">
<Icon name="log-out" aria-label="Sign out" class="h-4"/>
</a>
</div>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import {debounce, isObject} from 'lodash';
import {mapState} from 'vuex';
import {AxiosError} from "axios";
import Icon from "@/components/core/Icon.vue";
export default Vue.extend({
name: 'Navigation',
components: {Icon},
data: function () {
return {
loadingResults: false,
searchActive: false,
};
},
computed: {
...mapState('dashboard', ['servers']),
searchTerm: {
get: function (): string {
return this.$store.getters['dashboard/getSearchTerm'];
},
set: function (value: string): void {
this.$store.dispatch('dashboard/setSearchTerm', value);
}
}
},
created: function () {
document.addEventListener('click', this.documentClick);
},
beforeDestroy: function () {
document.removeEventListener('click', this.documentClick);
},
methods: {
search: debounce(function (this: any): void {
if (this.searchTerm.length >= 3) {
this.loadingResults = true;
this.gatherSearchResults();
}
}, 500),
gatherSearchResults: function (): void {
this.$store.dispatch('dashboard/loadServers')
.catch((err: AxiosError) => {
console.error(err);
const response = err.response;
if (response && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
}
})
.then(() => {
this.loadingResults = false;
});
},
doLogout: function () {
this.$store.commit('auth/logout');
window.location.assign(this.route('auth.logout'));
},
documentClick: function (e: Event) {
if (this.$refs.searchContainer) {
if (this.$refs.searchContainer !== e.target && !(this.$refs.searchContainer as HTMLElement).contains(e.target as HTMLElement)) {
this.searchActive = false;
}
}
},
},
})
</script>

View file

@ -1,58 +0,0 @@
import Vue from 'vue';
import Navigation from "../core/Navigation";
import Flash from "../Flash";
import UpdateEmail from "./account/UpdateEmail";
import ChangePassword from "./account/ChangePassword";
import TwoFactorAuthentication from "./account/TwoFactorAuthentication";
import Modal from "../core/Modal";
export default Vue.component('account', {
components: {
TwoFactorAuthentication,
Modal,
ChangePassword,
UpdateEmail,
Flash,
Navigation
},
data: function () {
return {
modalVisible: false,
};
},
methods: {
openModal: function () {
this.modalVisible = true;
window.events.$emit('two_factor:open');
},
},
template: `
<div>
<navigation/>
<div class="container animate fadein mt-2 sm:mt-6">
<modal :show="modalVisible" v-on:close="modalVisible = false">
<TwoFactorAuthentication v-on:close="modalVisible = false"/>
</modal>
<flash container="mt-2 sm:mt-6 mb-2"/>
<div class="flex flex-wrap">
<div class="w-full md:w-1/2">
<div class="sm:m-4 md:ml-0">
<update-email class="mb-4 sm:mb-8"/>
<div class="content-box text-center mb-4 sm:mb-0">
<button class="btn btn-green btn-sm" type="submit" id="grid-open-two-factor-modal"
v-on:click="openModal"
>Configure 2-Factor Authentication</button>
</div>
</div>
</div>
<div class="w-full md:w-1/2">
<change-password class="sm:m-4 md:mr-0"/>
</div>
</div>
</div>
</div>
`,
})

View file

@ -0,0 +1,62 @@
<template>
<div>
<Navigation/>
<div class="container animate fadein mt-2 sm:mt-6">
<Modal :show="modalVisible" v-on:close="modalVisible = false">
<TwoFactorAuthentication v-on:close="modalVisible = false"/>
</Modal>
<Flash container="mt-2 sm:mt-6 mb-2"/>
<div class="flex flex-wrap">
<div class="w-full md:w-1/2">
<div class="sm:m-4 md:ml-0">
<UpdateEmail class="mb-4 sm:mb-8"/>
<div class="content-box text-center mb-4 sm:mb-0">
<button class="btn btn-green btn-sm" type="submit" id="grid-open-two-factor-modal"
v-on:click="openModal"
>Configure 2-Factor Authentication
</button>
</div>
</div>
</div>
<div class="w-full md:w-1/2">
<ChangePassword class="sm:m-4 md:mr-0"/>
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import Navigation from "../core/Navigation.vue";
import Flash from "@/components/Flash.vue";
import UpdateEmail from "./account/UpdateEmail.vue";
import ChangePassword from "./account/ChangePassword.vue";
import TwoFactorAuthentication from "./account/TwoFactorAuthentication.vue";
import Modal from "../core/Modal.vue";
export default Vue.extend({
name: 'Account',
components: {
TwoFactorAuthentication,
Modal,
ChangePassword,
UpdateEmail,
Flash,
Navigation
},
data: function () {
return {
modalVisible: false,
};
},
methods: {
openModal: function () {
this.modalVisible = true;
window.events.$emit('two_factor:open');
},
},
});
</script>

View file

@ -1,125 +0,0 @@
import Vue from 'vue';
import { debounce, isObject } from 'lodash';
import { mapState } from 'vuex';
import Flash from "./../Flash";
import Navigation from "./../core/Navigation";
import {AxiosError} from "axios";
import ServerBox from "./ServerBox";
type DataStructure = {
backgroundedAt: Date,
documentVisible: boolean,
loading: boolean,
servers?: Array<any>,
searchTerm?: string,
}
export default Vue.component('dashboard', {
components: {
ServerBox,
Navigation,
Flash
},
data: function (): DataStructure {
return {
backgroundedAt: new Date(),
documentVisible: true,
loading: false,
}
},
/**
* Start loading the servers before the DOM $.el is created. If we already have servers
* stored in vuex shows those and don't fire another API call just to load them again.
*/
created: function () {
if (!this.servers || this.servers.length === 0) {
this.loadServers();
}
},
/**
* Once the page is mounted set a function to run every 10 seconds that will
* iterate through the visible servers and fetch their resource usage.
*/
mounted: function () {
(this.$refs.search as HTMLElement).focus();
},
computed: {
...mapState('dashboard', ['servers']),
searchTerm: {
get: function (): string {
return this.$store.getters['dashboard/getSearchTerm'];
},
set: function (value: string): void {
this.$store.dispatch('dashboard/setSearchTerm', value);
},
},
},
methods: {
/**
* Load the user's servers and render them onto the dashboard.
*/
loadServers: function () {
this.loading = true;
this.$flash.clear();
this.$store.dispatch('dashboard/loadServers')
.then(() => {
if (!this.servers || this.servers.length === 0) {
this.$flash.info(this.$t('dashboard.index.no_matches'));
}
})
.catch((err: AxiosError) => {
console.error(err);
const response = err.response;
if (response && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
}
})
.then(() => this.loading = false);
},
/**
* Handle a search for servers but only call the search function every 500ms
* at the fastest.
*/
onChange: debounce(function (this: any): void {
this.loadServers();
}, 500),
},
template: `
<div>
<navigation/>
<div class="container">
<flash container="mt-4"/>
<div class="server-search animate fadein">
<input type="text"
:placeholder="$t('dashboard.index.search')"
@input="onChange"
v-model="searchTerm"
ref="search"
/>
</div>
<div v-if="this.loading" class="my-4 animate fadein">
<div class="text-center h-16 my-20">
<span class="spinner spinner-xl spinner-thick blue"></span>
</div>
</div>
<transition-group class="flex flex-wrap justify-center sm:justify-start" v-else>
<server-box
v-for="(server, index) in servers"
:key="index"
:server="server"
/>
</transition-group>
</div>
</div>
`
});

View file

@ -0,0 +1,128 @@
<template>
<div>
<Navigation/>
<div class="container">
<Flash container="mt-4"/>
<div class="server-search animate fadein">
<input type="text"
:placeholder="$t('dashboard.index.search')"
@input="onChange"
v-model="searchTerm"
ref="search"
/>
</div>
<div v-if="this.loading" class="my-4 animate fadein">
<div class="text-center h-16 my-20">
<span class="spinner spinner-xl spinner-thick blue"></span>
</div>
</div>
<TransitionGroup class="flex flex-wrap justify-center sm:justify-start" v-else>
<ServerBox
v-for="(server, index) in servers"
:key="index"
:server="server"
/>
</TransitionGroup>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import {debounce, isObject} from 'lodash';
import {mapState} from 'vuex';
import Flash from "./../Flash.vue";
import Navigation from "./../core/Navigation.vue";
import {AxiosError} from "axios";
import ServerBox from "./ServerBox.vue";
type DataStructure = {
backgroundedAt: Date,
documentVisible: boolean,
loading: boolean,
servers?: Array<any>,
searchTerm?: string,
}
export default Vue.extend({
name: 'Dashboard',
components: {
ServerBox,
Navigation,
Flash
},
data: function (): DataStructure {
return {
backgroundedAt: new Date(),
documentVisible: true,
loading: false,
}
},
/**
* Start loading the servers before the DOM $.el is created. If we already have servers
* stored in vuex shows those and don't fire another API call just to load them again.
*/
created: function () {
if (!this.servers || this.servers.length === 0) {
this.loadServers();
}
},
/**
* Once the page is mounted set a function to run every 10 seconds that will
* iterate through the visible servers and fetch their resource usage.
*/
mounted: function () {
(this.$refs.search as HTMLElement).focus();
},
computed: {
...mapState('dashboard', ['servers']),
searchTerm: {
get: function (): string {
return this.$store.getters['dashboard/getSearchTerm'];
},
set: function (value: string): void {
this.$store.dispatch('dashboard/setSearchTerm', value);
},
},
},
methods: {
/**
* Load the user's servers and render them onto the dashboard.
*/
loadServers: function () {
this.loading = true;
this.$flash.clear();
this.$store.dispatch('dashboard/loadServers')
.then(() => {
if (!this.servers || this.servers.length === 0) {
this.$flash.info(this.$t('dashboard.index.no_matches'));
}
})
.catch((err: AxiosError) => {
console.error(err);
const response = err.response;
if (response && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
}
})
.then(() => this.loading = false);
},
/**
* Handle a search for servers but only call the search function every 500ms
* at the fastest.
*/
onChange: debounce(function (this: any): void {
this.loadServers();
}, 500),
},
});
</script>

View file

@ -1,197 +0,0 @@
import Vue from 'vue';
import { get } from 'lodash';
import { differenceInSeconds } from 'date-fns';
import {AxiosError, AxiosResponse} from "axios";
type DataStructure = {
backgroundedAt: Date,
documentVisible: boolean,
resources: null | { [s: string]: any },
cpu: number,
memory: number,
status: string,
link: { name: string, params: { id: string } },
dataGetTimeout: undefined | number,
}
export default Vue.component('server-box', {
props: {
server: { type: Object, required: true },
},
data: function (): DataStructure {
return {
backgroundedAt: new Date(),
documentVisible: true,
resources: null,
cpu: 0,
memory: 0,
status: '',
link: { name: 'server', params: { id: this.server.identifier }},
dataGetTimeout: undefined,
};
},
watch: {
/**
* Watch the documentVisible item and perform actions when it is changed. If it becomes
* true, we want to check how long ago the last poll was, if it was more than 30 seconds
* we want to immediately trigger the resourceUse api call, otherwise we just want to restart
* the time.
*
* If it is now false, we want to clear the timer that checks resource use, since we know
* we won't be doing anything with them anyways. Might as well avoid extraneous resource
* usage by the browser.
*/
documentVisible: function (value) {
if (!value) {
window.clearTimeout(this.dataGetTimeout);
return;
}
if (differenceInSeconds(new Date(), this.backgroundedAt) >= 30) {
this.getResourceUse();
}
this.dataGetTimeout = window.setInterval(() => {
this.getResourceUse();
}, 10000);
},
},
/**
* Grab the initial resource usage for this specific server instance and add a listener
* to monitor when this window is no longer visible. We don't want to needlessly poll the
* API when we aren't looking at the page.
*/
created: function () {
this.getResourceUse();
document.addEventListener('visibilitychange', this._visibilityChange.bind(this));
},
/**
* Poll the API for changes every 10 seconds when the component is mounted.
*/
mounted: function () {
this.dataGetTimeout = window.setInterval(() => {
this.getResourceUse();
}, 10000);
},
/**
* Clear the timer and event listeners when we destroy the component.
*/
beforeDestroy: function () {
window.clearInterval(this.$data.dataGetTimeout);
document.removeEventListener('visibilitychange', this._visibilityChange.bind(this), false);
},
methods: {
/**
* Query the resource API to determine what this server's state and resource usage is.
*/
getResourceUse: function () {
window.axios.get(this.route('api.client.servers.resources', { server: this.server.identifier }))
.then((response: AxiosResponse) => {
if (!(response.data instanceof Object)) {
throw new Error('Received an invalid response object back from status endpoint.');
}
this.resources = response.data.attributes;
this.status = this.getServerStatus();
this.memory = parseInt(parseFloat(get(this.resources, 'memory.current', '0')).toFixed(0));
this.cpu = this._calculateCpu(
parseFloat(get(this.resources, 'cpu.current', '0')),
parseFloat(this.server.limits.cpu)
);
})
.catch((err: AxiosError) => console.warn('Error fetching server resource usage', { ...err }));
},
/**
* Set the CSS to use for displaying the server's current status.
*/
getServerStatus: function () {
if (!this.resources || !this.resources.installed || this.resources.suspended) {
return '';
}
switch (this.resources.state) {
case 'off':
return 'offline';
case 'on':
case 'starting':
case 'stopping':
return 'online';
default:
return '';
}
},
/**
* Calculate the CPU usage for a given server relative to their set maximum.
*
* @private
*/
_calculateCpu: function (current: number, max: number) {
if (max === 0) {
return parseFloat(current.toFixed(1));
}
return parseFloat((current / max * 100).toFixed(1));
},
/**
* Handle document visibility changes.
*
* @private
*/
_visibilityChange: function () {
this.documentVisible = document.visibilityState === 'visible';
if (!this.documentVisible) {
this.backgroundedAt = new Date();
}
},
},
template: `
<div class="server-card-container animated-fade-in">
<div>
<div class="server-card">
<router-link :to="link" class="block">
<h2 class="text-xl flex flex-row items-center mb-2">
<div class="identifier-icon select-none" :class="{
'bg-neutral-400': status === '',
'bg-red-500': status === 'offline',
'bg-green-500': status === 'online'
}">
{{ server.name[0] }}
</div>
{{ server.name }}
</h2>
</router-link>
<div class="flex-1 py-3">
<p v-if="server.description.length" class="text-neutral-500 text-sm">{{ server.description }}</p>
</div>
<div class="flex flex-none pt-2">
<div class="flex-1">
<span class="font-semibold text-cyan-800">{{ server.node }}</span>
</div>
<div>
<span class="text-neutral-300">{{ server.allocation.ip }}:{{ server.allocation.port }}</span>
</div>
</div>
</div>
<div class="footer p-4 text-sm">
<div class="inline-block pr-2">
<div class="pillbox bg-neutral-700"><span class="select-none">MEM:</span> {{ memory }} Mb</div>
</div>
<div class="inline-block">
<div class="pillbox bg-neutral-700"><span class="select-none">CPU:</span> {{ cpu }} %</div>
</div>
</div>
</div>
</div>
`
});

View file

@ -0,0 +1,200 @@
<template>
<div class="server-card-container animated-fade-in">
<div>
<div class="server-card">
<router-link :to="link" class="block">
<h2 class="text-xl flex flex-row items-center mb-2">
<div class="identifier-icon select-none" :class="{
'bg-neutral-400': status === '',
'bg-red-500': status === 'offline',
'bg-green-500': status === 'online'
}">
{{ server.name[0] }}
</div>
{{ server.name }}
</h2>
</router-link>
<div class="flex-1 py-3">
<p v-if="server.description.length" class="text-neutral-500 text-sm">{{ server.description }}</p>
</div>
<div class="flex flex-none pt-2">
<div class="flex-1">
<span class="font-semibold text-cyan-800">{{ server.node }}</span>
</div>
<div>
<span class="text-neutral-300">{{ server.allocation.ip }}:{{ server.allocation.port }}</span>
</div>
</div>
</div>
<div class="footer p-4 text-sm">
<div class="inline-block pr-2">
<div class="pillbox bg-neutral-700"><span class="select-none">MEM:</span> {{ memory }} Mb</div>
</div>
<div class="inline-block">
<div class="pillbox bg-neutral-700"><span class="select-none">CPU:</span> {{ cpu }} %</div>
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import {get} from 'lodash';
import {differenceInSeconds} from 'date-fns';
import {AxiosError, AxiosResponse} from "axios";
type DataStructure = {
backgroundedAt: Date,
documentVisible: boolean,
resources: null | { [s: string]: any },
cpu: number,
memory: number,
status: string,
link: { name: string, params: { id: string } },
dataGetTimeout: undefined | number,
}
export default Vue.extend({
name: 'ServerBox',
props: {
server: {type: Object, required: true},
},
data: function (): DataStructure {
return {
backgroundedAt: new Date(),
documentVisible: true,
resources: null,
cpu: 0,
memory: 0,
status: '',
link: {name: 'server', params: {id: this.server.identifier}},
dataGetTimeout: undefined,
};
},
watch: {
/**
* Watch the documentVisible item and perform actions when it is changed. If it becomes
* true, we want to check how long ago the last poll was, if it was more than 30 seconds
* we want to immediately trigger the resourceUse api call, otherwise we just want to restart
* the time.
*
* If it is now false, we want to clear the timer that checks resource use, since we know
* we won't be doing anything with them anyways. Might as well avoid extraneous resource
* usage by the browser.
*/
documentVisible: function (value) {
if (!value) {
window.clearTimeout(this.dataGetTimeout);
return;
}
if (differenceInSeconds(new Date(), this.backgroundedAt) >= 30) {
this.getResourceUse();
}
this.dataGetTimeout = window.setInterval(() => {
this.getResourceUse();
}, 10000);
},
},
/**
* Grab the initial resource usage for this specific server instance and add a listener
* to monitor when this window is no longer visible. We don't want to needlessly poll the
* API when we aren't looking at the page.
*/
created: function () {
this.getResourceUse();
document.addEventListener('visibilitychange', this._visibilityChange.bind(this));
},
/**
* Poll the API for changes every 10 seconds when the component is mounted.
*/
mounted: function () {
this.dataGetTimeout = window.setInterval(() => {
this.getResourceUse();
}, 10000);
},
/**
* Clear the timer and event listeners when we destroy the component.
*/
beforeDestroy: function () {
window.clearInterval(this.dataGetTimeout);
document.removeEventListener('visibilitychange', this._visibilityChange.bind(this), false);
},
methods: {
/**
* Query the resource API to determine what this server's state and resource usage is.
*/
getResourceUse: function () {
window.axios.get(this.route('api.client.servers.resources', {server: this.server.identifier}))
.then((response: AxiosResponse) => {
if (!(response.data instanceof Object)) {
throw new Error('Received an invalid response object back from status endpoint.');
}
this.resources = response.data.attributes;
this.status = this.getServerStatus();
this.memory = parseInt(parseFloat(get(this.resources, 'memory.current', '0')).toFixed(0));
this.cpu = this._calculateCpu(
parseFloat(get(this.resources, 'cpu.current', '0')),
parseFloat(this.server.limits.cpu)
);
})
.catch((err: AxiosError) => console.warn('Error fetching server resource usage', {...err}));
},
/**
* Set the CSS to use for displaying the server's current status.
*/
getServerStatus: function () {
if (!this.resources || !this.resources.installed || this.resources.suspended) {
return '';
}
switch (this.resources.state) {
case 'off':
return 'offline';
case 'on':
case 'starting':
case 'stopping':
return 'online';
default:
return '';
}
},
/**
* Calculate the CPU usage for a given server relative to their set maximum.
*
* @private
*/
_calculateCpu: function (current: number, max: number) {
if (max === 0) {
return parseFloat(current.toFixed(1));
}
return parseFloat((current / max * 100).toFixed(1));
},
/**
* Handle document visibility changes.
*
* @private
*/
_visibilityChange: function () {
this.documentVisible = document.visibilityState === 'visible';
if (!this.documentVisible) {
this.backgroundedAt = new Date();
}
},
},
});
</script>

View file

@ -1,91 +0,0 @@
import Vue from 'vue';
import { isObject } from 'lodash';
import {AxiosError} from "axios";
export default Vue.component('change-password', {
data: function () {
return {
current: '',
newPassword: '',
confirmNew: '',
};
},
methods: {
submitForm: function () {
this.$flash.clear();
this.$validator.pause();
window.axios.put(this.route('api.client.account.update-password'), {
current_password: this.current,
password: this.newPassword,
password_confirmation: this.confirmNew,
})
.then(() => this.current = '')
.then(() => {
this.newPassword = '';
this.confirmNew = '';
this.$flash.success(this.$t('dashboard.account.password.updated'));
})
.catch((err: AxiosError) => {
if (!err.response) {
this.$flash.error('There was an error with the network request. Please try again.');
console.error(err);
return;
}
const response = err.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
}
})
.then(() => {
this.$validator.resume();
(this.$refs.current as HTMLElement).focus();
})
}
},
template: `
<div id="change-password-container" :class>
<form method="post" v-on:submit.prevent="submitForm">
<div class="content-box">
<h2 class="mb-6 text-neutral-900 font-medium">{{ $t('dashboard.account.password.title') }}</h2>
<div class="mt-6">
<label for="grid-password-current" class="input-label">{{ $t('strings.password') }}</label>
<input id="grid-password-current" name="current_password" type="password" class="input" required
ref="current"
v-model="current"
>
</div>
<div class="mt-6">
<label for="grid-password-new" class="input-label">{{ $t('strings.new_password') }}</label>
<input id="grid-password-new" name="password" type="password" class="input" required
:class="{ error: errors.has('password') }"
v-model="newPassword"
v-validate="'min:8'"
>
<p class="input-help error" v-show="errors.has('password')">{{ errors.first('password') }}</p>
<p class="input-help">{{ $t('dashboard.account.password.requirements') }}</p>
</div>
<div class="mt-6">
<label for="grid-password-new-confirm" class="input-label">{{ $t('strings.confirm_password') }}</label>
<input id="grid-password-new-confirm" name="password_confirmation" type="password" class="input" required
:class="{ error: errors.has('password_confirmation') }"
v-model="confirmNew"
v-validate="{is: newPassword}"
data-vv-as="password"
>
<p class="input-help error" v-show="errors.has('password_confirmation')">{{ errors.first('password_confirmation') }}</p>
</div>
<div class="mt-6 text-right">
<button class="btn btn-primary btn-sm text-right" type="submit">{{ $t('strings.save') }}</button>
</div>
</div>
</form>
</div>
`,
});

View file

@ -0,0 +1,94 @@
<template>
<div id="change-password-container" :class>
<form method="post" v-on:submit.prevent="submitForm">
<div class="content-box">
<h2 class="mb-6 text-neutral-900 font-medium">{{ $t('dashboard.account.password.title') }}</h2>
<div class="mt-6">
<label for="grid-password-current" class="input-label">{{ $t('strings.password') }}</label>
<input id="grid-password-current" name="current_password" type="password" class="input" required
ref="current"
v-model="current"
>
</div>
<div class="mt-6">
<label for="grid-password-new" class="input-label">{{ $t('strings.new_password') }}</label>
<input id="grid-password-new" name="password" type="password" class="input" required
:class="{ error: errors.has('password') }"
v-model="newPassword"
v-validate="'min:8'"
>
<p class="input-help error" v-show="errors.has('password')">{{ errors.first('password') }}</p>
<p class="input-help">{{ $t('dashboard.account.password.requirements') }}</p>
</div>
<div class="mt-6">
<label for="grid-password-new-confirm" class="input-label">{{ $t('strings.confirm_password') }}</label>
<input id="grid-password-new-confirm" name="password_confirmation" type="password" class="input" required
:class="{ error: errors.has('password_confirmation') }"
v-model="confirmNew"
v-validate="{is: newPassword}"
data-vv-as="password"
>
<p class="input-help error" v-show="errors.has('password_confirmation')">{{ errors.first('password_confirmation') }}</p>
</div>
<div class="mt-6 text-right">
<button class="btn btn-primary btn-sm text-right" type="submit">{{ $t('strings.save') }}</button>
</div>
</div>
</form>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import { isObject } from 'lodash';
import {AxiosError} from "axios";
export default Vue.extend({
name: 'ChangePassword',
data: function () {
return {
current: '',
newPassword: '',
confirmNew: '',
};
},
methods: {
submitForm: function () {
this.$flash.clear();
this.$validator.pause();
window.axios.put(this.route('api.client.account.update-password'), {
current_password: this.current,
password: this.newPassword,
password_confirmation: this.confirmNew,
})
.then(() => this.current = '')
.then(() => {
this.newPassword = '';
this.confirmNew = '';
this.$flash.success(this.$t('dashboard.account.password.updated'));
})
.catch((err: AxiosError) => {
if (!err.response) {
this.$flash.error('There was an error with the network request. Please try again.');
console.error(err);
return;
}
const response = err.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
}
})
.then(() => {
this.$validator.resume();
(this.$refs.current as HTMLElement).focus();
})
}
},
});
</script>

View file

@ -1,188 +0,0 @@
import Vue from 'vue';
import {isObject} from 'lodash';
import {AxiosError, AxiosResponse} from "axios";
export default Vue.component('two-factor-authentication', {
data: function () {
return {
spinner: true,
token: '',
submitDisabled: true,
response: {
enabled: false,
qr_image: '',
secret: '',
},
};
},
/**
* Before the component is mounted setup the event listener. This event is fired when a user
* presses the 'Configure 2-Factor' button on their account page. Once this happens we fire off
* a HTTP request to get their information.
*/
mounted: function () {
window.events.$on('two_factor:open', () => {
this.prepareModalContent();
});
},
watch: {
token: function (value) {
this.submitDisabled = value.length !== 6;
},
},
methods: {
/**
* Determine the correct content to show in the modal.
*/
prepareModalContent: function () {
// Reset the data object when the modal is opened again.
// @ts-ignore
Object.assign(this.$data, this.$options.data());
this.$flash.clear();
window.axios.get(this.route('account.two_factor'))
.then((response: AxiosResponse) => {
this.response = response.data;
this.spinner = false;
Vue.nextTick().then(() => {
(this.$refs.token as HTMLElement).focus();
})
})
.catch((err: AxiosError) => {
if (!err.response) {
this.$flash.error(err.message);
console.error(err);
return;
}
const response = err.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
}
this.$emit('close');
});
},
/**
* Enable two-factor authentication on the account by validating the token provided by the user.
* Close the modal once the request completes so that the success or error message can be shown
* to the user.
*/
enableTwoFactor: function () {
return this._callInternalApi('account.two_factor.enable', 'enabled');
},
/**
* Disables two-factor authentication for the client account and closes the modal.
*/
disableTwoFactor: function () {
return this._callInternalApi('account.two_factor.disable', 'disabled');
},
/**
* Call the Panel API endpoint and handle errors.
*
* @private
*/
_callInternalApi: function (route: string, langKey: string) {
this.$flash.clear();
this.spinner = true;
window.axios.post(this.route(route), {token: this.token})
.then((response: AxiosResponse) => {
if (response.data.success) {
this.$flash.success(this.$t(`dashboard.account.two_factor.${langKey}`));
} else {
this.$flash.error(this.$t('dashboard.account.two_factor.invalid'));
}
})
.catch((error: AxiosError) => {
if (!error.response) {
this.$flash.error(error.message);
return;
}
const response = error.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((e: any) => {
this.$flash.error(e.detail);
});
}
})
.then(() => {
this.spinner = false;
this.$emit('close');
});
}
},
template: `
<div id="configure-two-factor">
<div class="h-16 text-center" v-show="spinner">
<span class="spinner spinner-xl text-primary-500"></span>
</div>
<div id="container-disable-two-factor" v-if="response.enabled" v-show="!spinner">
<h2 class="font-medium text-neutral-900">{{ $t('dashboard.account.two_factor.disable.title') }}</h2>
<div class="mt-6">
<label class="input-label" for="grid-two-factor-token-disable">{{ $t('dashboard.account.two_factor.disable.field') }}</label>
<input id="grid-two-factor-token-disable" type="number" class="input"
name="token"
v-model="token"
ref="token"
v-validate="'length:6'"
:class="{ error: errors.has('token') }"
>
<p class="input-help error" v-show="errors.has('token')">{{ errors.first('token') }}</p>
</div>
<div class="mt-6 w-full text-right">
<button class="btn btn-sm btn-secondary mr-4" v-on:click="$emit('close')">
Cancel
</button>
<button class="btn btn-sm btn-red" type="submit"
:disabled="submitDisabled"
v-on:click.prevent="disableTwoFactor"
>{{ $t('strings.disable') }}</button>
</div>
</div>
<div id="container-enable-two-factor" v-else v-show="!spinner">
<h2 class="font-medium text-neutral-900">{{ $t('dashboard.account.two_factor.setup.title') }}</h2>
<div class="flex mt-6">
<div class="flex-none w-full sm:w-1/2 text-center">
<div class="h-48">
<img :src="response.qr_image" id="grid-qr-code" alt="Two-factor qr image" class="h-48">
</div>
<div>
<p class="text-xs text-neutral-800 mb-2">{{ $t('dashboard.account.two_factor.setup.help') }}</p>
<p class="text-xs"><code>{{response.secret}}</code></p>
</div>
</div>
<div class="flex-none w-full sm:w-1/2">
<div>
<label class="input-label" for="grid-two-factor-token">{{ $t('dashboard.account.two_factor.setup.field') }}</label>
<input id="grid-two-factor-token" type="number" class="input"
name="token"
v-model="token"
ref="token"
v-validate="'length:6'"
:class="{ error: errors.has('token') }"
>
<p class="input-help error" v-show="errors.has('token')">{{ errors.first('token') }}</p>
</div>
<div class="mt-6">
<button class="btn btn-primary btn-jumbo" type="submit"
:disabled="submitDisabled"
v-on:click.prevent="enableTwoFactor"
>{{ $t('strings.enable') }}</button>
</div>
</div>
</div>
</div>
</div>
`
})

View file

@ -0,0 +1,193 @@
<template>
<div id="configure-two-factor">
<div class="h-16 text-center" v-show="spinner">
<span class="spinner spinner-xl text-primary-500"></span>
</div>
<div id="container-disable-two-factor" v-if="response.enabled" v-show="!spinner">
<h2 class="font-medium text-neutral-900">{{ $t('dashboard.account.two_factor.disable.title') }}</h2>
<div class="mt-6">
<label class="input-label" for="grid-two-factor-token-disable">{{ $t('dashboard.account.two_factor.disable.field') }}</label>
<input id="grid-two-factor-token-disable" type="number" class="input"
name="token"
v-model="token"
ref="token"
v-validate="'length:6'"
:class="{ error: errors.has('token') }"
>
<p class="input-help error" v-show="errors.has('token')">{{ errors.first('token') }}</p>
</div>
<div class="mt-6 w-full text-right">
<button class="btn btn-sm btn-secondary mr-4" v-on:click="$emit('close')">
Cancel
</button>
<button class="btn btn-sm btn-red" type="submit"
:disabled="submitDisabled"
v-on:click.prevent="disableTwoFactor"
>{{ $t('strings.disable') }}
</button>
</div>
</div>
<div id="container-enable-two-factor" v-else v-show="!spinner">
<h2 class="font-medium text-neutral-900">{{ $t('dashboard.account.two_factor.setup.title') }}</h2>
<div class="flex mt-6">
<div class="flex-none w-full sm:w-1/2 text-center">
<div class="h-48">
<img :src="response.qr_image" id="grid-qr-code" alt="Two-factor qr image" class="h-48">
</div>
<div>
<p class="text-xs text-neutral-800 mb-2">{{ $t('dashboard.account.two_factor.setup.help') }}</p>
<p class="text-xs"><code>{{response.secret}}</code></p>
</div>
</div>
<div class="flex-none w-full sm:w-1/2">
<div>
<label class="input-label" for="grid-two-factor-token">{{ $t('dashboard.account.two_factor.setup.field') }}</label>
<input id="grid-two-factor-token" type="number" class="input"
name="token"
v-model="token"
ref="token"
v-validate="'length:6'"
:class="{ error: errors.has('token') }"
>
<p class="input-help error" v-show="errors.has('token')">{{ errors.first('token') }}</p>
</div>
<div class="mt-6">
<button class="btn btn-primary btn-jumbo" type="submit"
:disabled="submitDisabled"
v-on:click.prevent="enableTwoFactor"
>{{ $t('strings.enable') }}
</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import {isObject} from 'lodash';
import {AxiosError, AxiosResponse} from "axios";
export default Vue.extend({
name: 'TwoFactorAuthentication',
data: function () {
return {
spinner: true,
token: '',
submitDisabled: true,
response: {
enabled: false,
qr_image: '',
secret: '',
},
};
},
/**
* Before the component is mounted setup the event listener. This event is fired when a user
* presses the 'Configure 2-Factor' button on their account page. Once this happens we fire off
* a HTTP request to get their information.
*/
mounted: function () {
window.events.$on('two_factor:open', () => {
this.prepareModalContent();
});
},
watch: {
token: function (value) {
this.submitDisabled = value.length !== 6;
},
},
methods: {
/**
* Determine the correct content to show in the modal.
*/
prepareModalContent: function () {
// Reset the data object when the modal is opened again.
// @ts-ignore
Object.assign(this.$data, this.$options.data());
this.$flash.clear();
window.axios.get(this.route('account.two_factor'))
.then((response: AxiosResponse) => {
this.response = response.data;
this.spinner = false;
Vue.nextTick().then(() => {
(this.$refs.token as HTMLElement).focus();
})
})
.catch((err: AxiosError) => {
if (!err.response) {
this.$flash.error(err.message);
console.error(err);
return;
}
const response = err.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
}
this.$emit('close');
});
},
/**
* Enable two-factor authentication on the account by validating the token provided by the user.
* Close the modal once the request completes so that the success or error message can be shown
* to the user.
*/
enableTwoFactor: function () {
return this._callInternalApi('account.two_factor.enable', 'enabled');
},
/**
* Disables two-factor authentication for the client account and closes the modal.
*/
disableTwoFactor: function () {
return this._callInternalApi('account.two_factor.disable', 'disabled');
},
/**
* Call the Panel API endpoint and handle errors.
*
* @private
*/
_callInternalApi: function (route: string, langKey: string) {
this.$flash.clear();
this.spinner = true;
window.axios.post(this.route(route), {token: this.token})
.then((response: AxiosResponse) => {
if (response.data.success) {
this.$flash.success(this.$t(`dashboard.account.two_factor.${langKey}`));
} else {
this.$flash.error(this.$t('dashboard.account.two_factor.invalid'));
}
})
.catch((error: AxiosError) => {
if (!error.response) {
this.$flash.error(error.message);
return;
}
const response = error.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((e: any) => {
this.$flash.error(e.detail);
});
}
})
.then(() => {
this.spinner = false;
this.$emit('close');
});
}
},
})
</script>

View file

@ -1,77 +0,0 @@
import Vue from 'vue';
import { get, isObject } from 'lodash';
import { mapState } from 'vuex';
import {ApplicationState} from "../../../store/types";
import {AxiosError} from "axios";
export default Vue.component('update-email', {
data: function () {
return {
email: get(this.$store.state, 'auth.user.email', ''),
password: '',
};
},
computed: {
...mapState({
user: (state: ApplicationState) => state.auth.user,
})
},
methods: {
/**
* Update a user's email address on the Panel.
*/
submitForm: function () {
this.$flash.clear();
this.$store.dispatch('auth/updateEmail', { email: this.email, password: this.password })
.then(() => {
this.$flash.success(this.$t('dashboard.account.email.updated'));
})
.catch((error: AxiosError) => {
if (!error.response) {
this.$flash.error(error.message);
return;
}
const response = error.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((e: any) => {
this.$flash.error(e.detail);
});
}
})
.then(() => {
this.$data.password = '';
});
},
},
template: `
<div id="update-email-container" :class>
<form method="post" v-on:submit.prevent="submitForm">
<div class="content-box">
<h2 class="mb-6 text-neutral-900 font-medium">{{ $t('dashboard.account.email.title') }}</h2>
<div>
<label for="grid-email" class="input-label">{{ $t('strings.email_address') }}</label>
<input id="grid-email" name="email" type="email" class="input" required
:class="{ error: errors.has('email') }"
v-validate
v-model="email"
>
<p class="input-help error" v-show="errors.has('email')">{{ errors.first('email') }}</p>
</div>
<div class="mt-6">
<label for="grid-password" class="input-label">{{ $t('strings.password') }}</label>
<input id="grid-password" name="password" type="password" class="input" required
v-model="password"
>
</div>
<div class="mt-6 text-right">
<button class="btn btn-primary btn-sm text-right" type="submit">{{ $t('strings.save') }}</button>
</div>
</div>
</form>
</div>
`,
});

View file

@ -0,0 +1,80 @@
<template>
<div id="update-email-container" :class>
<form method="post" v-on:submit.prevent="submitForm">
<div class="content-box">
<h2 class="mb-6 text-neutral-900 font-medium">{{ $t('dashboard.account.email.title') }}</h2>
<div>
<label for="grid-email" class="input-label">{{ $t('strings.email_address') }}</label>
<input id="grid-email" name="email" type="email" class="input" required
:class="{ error: errors.has('email') }"
v-validate
v-model="email"
>
<p class="input-help error" v-show="errors.has('email')">{{ errors.first('email') }}</p>
</div>
<div class="mt-6">
<label for="grid-password" class="input-label">{{ $t('strings.password') }}</label>
<input id="grid-password" name="password" type="password" class="input" required
v-model="password"
>
</div>
<div class="mt-6 text-right">
<button class="btn btn-primary btn-sm text-right" type="submit">{{ $t('strings.save') }}</button>
</div>
</div>
</form>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import {get, isObject} from 'lodash';
import {mapState} from 'vuex';
import {ApplicationState} from "@/store/types";
import {AxiosError} from "axios";
export default Vue.extend({
name: 'UpdateEmail',
data: function () {
return {
email: get(this.$store.state, 'auth.user.email', ''),
password: '',
};
},
computed: {
...mapState({
user: (state: ApplicationState) => state.auth.user,
})
},
methods: {
/**
* Update a user's email address on the Panel.
*/
submitForm: function () {
this.$flash.clear();
this.$store.dispatch('auth/updateEmail', {email: this.email, password: this.password})
.then(() => {
this.$flash.success(this.$t('dashboard.account.email.updated'));
})
.catch((error: AxiosError) => {
if (!error.response) {
this.$flash.error(error.message);
return;
}
const response = error.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach((e: any) => {
this.$flash.error(e.detail);
});
}
})
.then(() => {
this.password = '';
});
},
},
});
</script>

View file

@ -1,11 +0,0 @@
import Vue from 'vue';
export default Vue.component('csrf', {
data: function () {
return {
X_CSRF_TOKEN: window.X_CSRF_TOKEN,
};
},
template: `<input type="hidden" name="_token" v-bind:value="X_CSRF_TOKEN" />`,
});

View file

@ -0,0 +1,16 @@
<template>
<input type="hidden" name="_token" v-bind:value="X_CSRF_TOKEN" />
</template>
<script lang="ts">
import Vue from 'vue';
export default Vue.extend({
name: 'CSRF',
data: function () {
return {
X_CSRF_TOKEN: window.X_CSRF_TOKEN,
};
},
});
</script>

View file

@ -1,121 +0,0 @@
import Vue from 'vue';
import Navigation from '@/components/core/Navigation';
import ProgressBar from './components/ProgressBar';
import { mapState } from 'vuex';
import * as io from 'socket.io-client';
import { Socketio } from "@/mixins/socketio";
import Icon from "@/components/core/Icon";
import PowerButtons from "@/components/server/components/PowerButtons";
export default Vue.component('server', {
components: { ProgressBar, PowerButtons, Navigation, Icon },
computed: {
...mapState('server', ['server', 'credentials']),
...mapState('socket', ['connected', 'connectionError']),
},
mixins: [ Socketio ],
// Watch for route changes that occur with different server parameters. This occurs when a user
// uses the search bar. Because of the way vue-router works, it won't re-mount the server component
// so we will end up seeing the wrong server data if we don't perform this watch.
watch: {
'$route': function (toRoute, fromRoute) {
if (toRoute.params.id !== fromRoute.params.id) {
this.loadingServerData = true;
this.loadServer();
}
}
},
data: function () {
return {
loadingServerData: true,
};
},
mounted: function () {
this.loadServer();
},
beforeDestroy: function () {
this.removeSocket();
},
methods: {
/**
* Load the core server information needed for these pages to be functional.
*/
loadServer: function () {
Promise.all([
this.$store.dispatch('server/getServer', {server: this.$route.params.id}),
this.$store.dispatch('server/getCredentials', {server: this.$route.params.id})
])
.then(() => {
// Configure the socket.io implementation. This is a really ghetto way of handling things
// but all of these plugins assume you have some constant connection, which we don't.
const socket = io(`${this.credentials.node}/v1/ws/${this.server.uuid}`, {
query: `token=${this.credentials.key}`,
});
this.$socket().connect(socket);
this.loadingServerData = false;
})
.catch(err => {
console.error('There was an error performing Server::loadServer', { err });
});
},
},
template: `
<div>
<navigation></navigation>
<flash class="m-6"/>
<div v-if="loadingServerData" class="container">
<div class="mt-6 h-16">
<div class="spinner spinner-xl spinner-thick blue"></div>
</div>
</div>
<div v-else class="container">
<div class="my-6 flex flex-no-shrink rounded animate fadein">
<div class="sidebar flex-no-shrink w-1/3 max-w-xs">
<div class="mr-6">
<div class="p-6 text-center bg-white rounded shadow">
<h3 class="mb-2 text-primary-500 font-medium">{{server.name}}</h3>
<span class="text-neutral-600 text-sm">{{server.node}}</span>
<power-buttons class="mt-6 pt-6 text-center border-t border-neutral-100"/>
</div>
</div>
<div class="sidenav mt-6 mr-6">
<ul>
<li>
<router-link :to="{ name: 'server', params: { id: $route.params.id } }">
Console
</router-link>
</li>
<li>
<router-link :to="{ name: 'server-files' }">
File Manager
</router-link>
</li>
<li>
<router-link :to="{ name: 'server-databases' }">
Databases
</router-link>
</li>
</ul>
</div>
</div>
<div class="h-full w-full">
<router-view :key="server.identifier"></router-view>
</div>
</div>
</div>
<div class="fixed pin-r pin-b m-6 max-w-sm" v-show="connectionError">
<div class="alert error">
There was an error while attempting to connect to the Daemon websocket. Error reported was: "{{connectionError.message}}"
</div>
</div>
</div>
`,
});

View file

@ -0,0 +1,123 @@
<template>
<div>
<Navigation/>
<Flash class="m-6"/>
<div v-if="loadingServerData" class="container">
<div class="mt-6 h-16">
<div class="spinner spinner-xl spinner-thick blue"></div>
</div>
</div>
<div v-else class="container">
<div class="my-6 flex flex-no-shrink rounded animate fadein">
<div class="sidebar flex-no-shrink w-1/3 max-w-xs">
<div class="mr-6">
<div class="p-6 text-center bg-white rounded shadow">
<h3 class="mb-2 text-primary-500 font-medium">{{server.name}}</h3>
<span class="text-neutral-600 text-sm">{{server.node}}</span>
<PowerButtons class="mt-6 pt-6 text-center border-t border-neutral-100"/>
</div>
</div>
<div class="sidenav mt-6 mr-6">
<ul>
<li>
<router-link :to="{ name: 'server', params: { id: $route.params.id } }">
Console
</router-link>
</li>
<li>
<router-link :to="{ name: 'server-files' }">
File Manager
</router-link>
</li>
<li>
<router-link :to="{ name: 'server-databases' }">
Databases
</router-link>
</li>
</ul>
</div>
</div>
<div class="h-full w-full">
<router-view :key="server.identifier"></router-view>
</div>
</div>
</div>
<div class="fixed pin-r pin-b m-6 max-w-sm" v-show="connectionError">
<div class="alert error">
There was an error while attempting to connect to the Daemon websocket. Error reported was: "{{connectionError.message}}"
</div>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import Navigation from '@/components/core/Navigation.vue';
import {mapState} from 'vuex';
import * as io from 'socket.io-client';
import {Socketio} from "@/mixins/socketio";
import PowerButtons from "@/components/server/components/PowerButtons.vue";
import Flash from "@/components/Flash.vue";
export default Vue.extend({
name: 'Server',
components: {Flash, PowerButtons, Navigation},
computed: {
...mapState('server', ['server', 'credentials']),
...mapState('socket', ['connected', 'connectionError']),
},
mixins: [Socketio],
// Watch for route changes that occur with different server parameters. This occurs when a user
// uses the search bar. Because of the way vue-router works, it won't re-mount the server component
// so we will end up seeing the wrong server data if we don't perform this watch.
watch: {
'$route': function (toRoute, fromRoute) {
if (toRoute.params.id !== fromRoute.params.id) {
this.loadingServerData = true;
this.loadServer();
}
}
},
data: function () {
return {
loadingServerData: true,
};
},
mounted: function () {
this.loadServer();
},
beforeDestroy: function () {
this.removeSocket();
},
methods: {
/**
* Load the core server information needed for these pages to be functional.
*/
loadServer: function () {
Promise.all([
this.$store.dispatch('server/getServer', {server: this.$route.params.id}),
this.$store.dispatch('server/getCredentials', {server: this.$route.params.id})
])
.then(() => {
// Configure the socket.io implementation. This is a really ghetto way of handling things
// but all of these plugins assume you have some constant connection, which we don't.
const socket = io(`${this.credentials.node}/v1/ws/${this.server.uuid}`, {
query: `token=${this.credentials.key}`,
});
this.$socket().connect(socket);
this.loadingServerData = false;
})
.catch(err => {
console.error('There was an error performing Server::loadServer', {err});
});
},
},
});
</script>

View file

@ -1,48 +0,0 @@
import Vue from 'vue';
import {mapState} from 'vuex';
import Status from '../../../helpers/statuses';
import {Socketio} from "@/mixins/socketio";
export default Vue.component('power-buttons', {
computed: {
...mapState('socket', ['connected', 'status']),
},
mixins: [Socketio],
data: function () {
return {
statuses: Status,
};
},
methods: {
sendPowerAction: function (action: string) {
this.$socket().instance().emit('set status', action)
},
},
template: `
<div>
<div v-if="connected">
<transition name="slide-fade" mode="out-in">
<button class="btn btn-green uppercase text-xs px-4 py-2"
v-if="status === statuses.STATUS_OFF"
v-on:click.prevent="sendPowerAction('start')"
>Start</button>
<div v-else>
<button class="btn btn-red uppercase text-xs px-4 py-2" v-on:click.prevent="sendPowerAction('stop')">Stop</button>
<button class="btn btn-secondary uppercase text-xs px-4 py-2" v-on:click.prevent="sendPowerAction('restart')">Restart</button>
<button class="btn btn-secondary btn-red uppercase text-xs px-4 py-2" v-on:click.prevent="sendPowerAction('kill')">Kill</button>
</div>
</transition>
</div>
<div v-else>
<div class="text-center">
<div class="spinner"></div>
<div class="pt-2 text-xs text-neutral-400">Connecting to node</div>
</div>
</div>
</div>
`
});

View file

@ -0,0 +1,51 @@
<template>
<div>
<div v-if="connected">
<transition name="slide-fade" mode="out-in">
<button class="btn btn-green uppercase text-xs px-4 py-2"
v-if="status === statuses.STATUS_OFF"
v-on:click.prevent="sendPowerAction('start')"
>Start</button>
<div v-else>
<button class="btn btn-red uppercase text-xs px-4 py-2" v-on:click.prevent="sendPowerAction('stop')">Stop</button>
<button class="btn btn-secondary uppercase text-xs px-4 py-2" v-on:click.prevent="sendPowerAction('restart')">Restart</button>
<button class="btn btn-secondary btn-red uppercase text-xs px-4 py-2" v-on:click.prevent="sendPowerAction('kill')">Kill</button>
</div>
</transition>
</div>
<div v-else>
<div class="text-center">
<div class="spinner"></div>
<div class="pt-2 text-xs text-neutral-400">Connecting to node</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import {mapState} from 'vuex';
import Status from '../../../helpers/statuses';
import {Socketio} from "@/mixins/socketio";
export default Vue.extend({
name: 'PowerButtons',
computed: {
...mapState('socket', ['connected', 'status']),
},
mixins: [Socketio],
data: function () {
return {
statuses: Status,
};
},
methods: {
sendPowerAction: function (action: string) {
this.$socket().instance().emit('set status', action)
},
},
});
</script>

View file

@ -1,42 +0,0 @@
import Vue from 'vue';
export default Vue.component('progress-bar', {
props: {
percent: {type: Number, default: 0},
title: {type: String}
},
computed: {
backgroundColor: function () {
if (this.percent < 70) {
return "bg-green-600";
} else if (this.percent >= 70 && this.percent < 90) {
return "bg-yellow-dark";
} else {
return "bg-red-600";
}
},
borderColor: function () {
if (this.percent < 70) {
return "border-green-600";
} else if (this.percent >= 70 && this.percent < 90) {
return "border-yellow-dark";
} else {
return "border-red-600";
}
}
},
template: `
<div>
<div class="text-right mb-1" v-if="title.length > 0">
<span class="text-neutral-600 text-xs uppercase">{{ title }}</span>
</div>
<div class="w-full border rounded h-4" :class="borderColor">
<div class="h-full w-1/3 text-center" :style="{ width: percent + '%' }" :class="backgroundColor">
<span class="mt-1 text-xs text-white leading-none">{{ percent }} %</span>
</div>
</div>
</div>
`,
});

View file

@ -1,86 +0,0 @@
import Vue from 'vue';
import MessageBox from "@/components/MessageBox";
import {createDatabase} from "@/api/server/createDatabase";
export default Vue.component('CreateDatabaseModal', {
components: {MessageBox},
data: function () {
return {
loading: false,
showSpinner: false,
database: '',
remote: '%',
errorMessage: '',
};
},
computed: {
canSubmit: function () {
return this.database.length && this.remote.length;
},
},
methods: {
submit: function () {
this.showSpinner = true;
this.errorMessage = '';
this.loading = true;
createDatabase(this.$route.params.id, this.database, this.remote)
.then((response) => {
this.$emit('database', response);
this.$emit('close');
})
.catch((err: Error | string): void => {
if (typeof err === 'string') {
this.errorMessage = err;
return;
}
console.error('A network error was encountered while processing this request.', { err });
})
.then(() => {
this.loading = false;
this.showSpinner = false;
});
}
},
template: `
<div>
<message-box class="alert error mb-6" :message="errorMessage" v-show="errorMessage.length"/>
<h2 class="font-medium text-neutral-900 mb-6">Create a new database</h2>
<div class="mb-6">
<label class="input-label" for="grid-database-name">Database name</label>
<input id="grid-database-name" type="text" class="input" name="database_name" required
v-model="database"
v-validate="{ alpha_dash: true, max: 100 }"
:class="{ error: errors.has('database_name') }"
>
<p class="input-help error" v-show="errors.has('database_name')">{{ errors.first('database_name') }}</p>
</div>
<div class="mb-6">
<label class="input-label" for="grid-database-remote">Allow connections from</label>
<input id="grid-database-remote" type="text" class="input" name="remote" required
v-model="remote"
v-validate="{ regex: /^[0-9%.]{1,15}$/ }"
:class="{ error: errors.has('remote') }"
>
<p class="input-help error" v-show="errors.has('remote')">{{ errors.first('remote') }}</p>
</div>
<div class="text-right">
<button class="btn btn-secondary btn-sm mr-2" v-on:click.once="$emit('close')">Cancel</button>
<button class="btn btn-primary btn-sm"
:disabled="errors.any() || !canSubmit || showSpinner"
v-on:click="submit"
>
<span class="spinner white" v-bind:class="{ hidden: !showSpinner }">&nbsp;</span>
<span :class="{ hidden: showSpinner }">
Create
</span>
</button>
</div>
</div>
`
});

View file

@ -0,0 +1,89 @@
<template>
<div>
<MessageBox class="alert error mb-6" :message="errorMessage" v-show="errorMessage.length"/>
<h2 class="font-medium text-neutral-900 mb-6">Create a new database</h2>
<div class="mb-6">
<label class="input-label" for="grid-database-name">Database name</label>
<input id="grid-database-name" type="text" class="input" name="database_name" required
v-model="database"
v-validate="{ alpha_dash: true, max: 100 }"
:class="{ error: errors.has('database_name') }"
>
<p class="input-help error" v-show="errors.has('database_name')">{{ errors.first('database_name') }}</p>
</div>
<div class="mb-6">
<label class="input-label" for="grid-database-remote">Allow connections from</label>
<input id="grid-database-remote" type="text" class="input" name="remote" required
v-model="remote"
v-validate="{ regex: /^[0-9%.]{1,15}$/ }"
:class="{ error: errors.has('remote') }"
>
<p class="input-help error" v-show="errors.has('remote')">{{ errors.first('remote') }}</p>
</div>
<div class="text-right">
<button class="btn btn-secondary btn-sm mr-2" v-on:click.once="$emit('close')">Cancel</button>
<button class="btn btn-primary btn-sm"
:disabled="errors.any() || !canSubmit || showSpinner"
v-on:click="submit"
>
<span class="spinner white" v-bind:class="{ hidden: !showSpinner }">&nbsp;</span>
<span :class="{ hidden: showSpinner }">
Create
</span>
</button>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import MessageBox from "@/components/MessageBox.vue";
import {createDatabase} from "@/api/server/createDatabase";
export default Vue.extend({
name: 'CreateDatabaseModal',
components: {MessageBox},
data: function () {
return {
loading: false,
showSpinner: false,
database: '',
remote: '%',
errorMessage: '',
};
},
computed: {
canSubmit: function () {
return this.database.length && this.remote.length;
},
},
methods: {
submit: function () {
this.showSpinner = true;
this.errorMessage = '';
this.loading = true;
createDatabase(this.$route.params.id, this.database, this.remote)
.then((response) => {
this.$emit('database', response);
this.$emit('close');
})
.catch((err: Error | string): void => {
if (typeof err === 'string') {
this.errorMessage = err;
return;
}
console.error('A network error was encountered while processing this request.', {err});
})
.then(() => {
this.loading = false;
this.showSpinner = false;
});
}
},
});
</script>

View file

@ -1,70 +0,0 @@
import Vue from 'vue';
import Icon from "@/components/core/Icon";
import Modal from "@/components/core/Modal";
import {ServerDatabase} from "@/api/server/types";
import DeleteDatabaseModal from "@/components/server/components/database/DeleteDatabaseModal";
export default Vue.component('DatabaseRow', {
components: {DeleteDatabaseModal, Modal, Icon},
props: {
database: {
type: Object as () => ServerDatabase,
required: true,
}
},
data: function () {
return {
showDeleteModal: false,
};
},
methods: {
revealPassword: function () {
this.database.showPassword = !this.database.showPassword;
},
},
template: `
<div class="content-box mb-6 hover:border-neutral-200">
<div class="flex items-center text-neutral-800">
<icon name="database" class="flex-none text-green-500"></icon>
<div class="flex-1 px-4">
<p class="uppercase text-xs text-neutral-500 pb-1 select-none">Database Name</p>
<p>{{database.name}}</p>
</div>
<div class="flex-1 px-4">
<p class="uppercase text-xs text-neutral-500 pb-1 select-none">Username</p>
<p>{{database.username}}</p>
</div>
<div class="flex-1 px-4">
<p class="uppercase text-xs text-neutral-500 pb-1 select-none">Password</p>
<p>
<code class="text-sm cursor-pointer" v-on:click="revealPassword">
<span class="select-none" v-if="!database.showPassword">
<icon name="lock" class="h-3"/> &bull;&bull;&bull;&bull;&bull;&bull;
</span>
<span v-else>{{database.password}}</span>
</code>
</p>
</div>
<div class="flex-1 px-4">
<p class="uppercase text-xs text-neutral-500 pb-1 select-none">Server</p>
<p><code class="text-sm">{{database.host.address}}:{{database.host.port}}</code></p>
</div>
<div class="flex-none px-4">
<button class="btn btn-xs btn-secondary btn-red" v-on:click="showDeleteModal = true">
<icon name="trash-2" class="w-3 h-3 mx-1"/>
</button>
</div>
</div>
<modal :show="showDeleteModal" v-on:close="showDeleteModal = false">
<DeleteDatabaseModal
:database="database"
v-on:close="showDeleteModal = false"
v-if="showDeleteModal"
/>
</modal>
</div>
`,
})

View file

@ -0,0 +1,73 @@
<template>
<div class="content-box mb-6 hover:border-neutral-200">
<div class="flex items-center text-neutral-800">
<Icon name="database" class="flex-none text-green-500"></icon>
<div class="flex-1 px-4">
<p class="uppercase text-xs text-neutral-500 pb-1 select-none">Database Name</p>
<p>{{database.name}}</p>
</div>
<div class="flex-1 px-4">
<p class="uppercase text-xs text-neutral-500 pb-1 select-none">Username</p>
<p>{{database.username}}</p>
</div>
<div class="flex-1 px-4">
<p class="uppercase text-xs text-neutral-500 pb-1 select-none">Password</p>
<p>
<code class="text-sm cursor-pointer" v-on:click="revealPassword">
<span class="select-none" v-if="!database.showPassword">
<Icon name="lock" class="h-3"/> &bull;&bull;&bull;&bull;&bull;&bull;
</span>
<span v-else>{{database.password}}</span>
</code>
</p>
</div>
<div class="flex-1 px-4">
<p class="uppercase text-xs text-neutral-500 pb-1 select-none">Server</p>
<p><code class="text-sm">{{database.host.address}}:{{database.host.port}}</code></p>
</div>
<div class="flex-none px-4">
<button class="btn btn-xs btn-secondary btn-red" v-on:click="showDeleteModal = true">
<Icon name="trash-2" class="w-3 h-3 mx-1"/>
</button>
</div>
</div>
<Modal :show="showDeleteModal" v-on:close="showDeleteModal = false">
<DeleteDatabaseModal
:database="database"
v-on:close="showDeleteModal = false"
v-if="showDeleteModal"
/>
</modal>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import Icon from "@/components/core/Icon.vue";
import Modal from "@/components/core/Modal.vue";
import {ServerDatabase} from "@/api/server/types";
import DeleteDatabaseModal from "@/components/server/components/database/DeleteDatabaseModal.vue";
export default Vue.extend({
name: 'DatabaseRow',
components: {DeleteDatabaseModal, Modal, Icon},
props: {
database: {
type: Object as () => ServerDatabase,
required: true,
}
},
data: function () {
return {
showDeleteModal: false,
};
},
methods: {
revealPassword: function () {
this.database.showPassword = !this.database.showPassword;
},
},
})
</script>

View file

@ -1,84 +0,0 @@
import Vue from 'vue';
import {ServerDatabase} from "@/api/server/types";
export default Vue.component('DeleteDatabaseModal', {
props: {
database: {
type: Object as () => ServerDatabase,
required: true
},
},
data: function () {
return {
showSpinner: false,
nameConfirmation: '',
};
},
computed: {
/**
* Determine if the 'Delete' button should be enabled or not. This requires the user
* to enter the database name before actually deleting the DB.
*/
disabled: function () {
const splits: Array<string> = this.database.name.split('_');
return (
this.nameConfirmation !== this.database.name && this.nameConfirmation !== splits.slice(1).join('_')
);
}
},
methods: {
/**
* Handle deleting the database for the server instance.
*/
deleteDatabase: function () {
this.nameConfirmation = '';
this.showSpinner = true;
window.axios.delete(this.route('api.client.servers.databases.delete', {
server: this.$route.params.id,
database: this.database.id,
}))
.then(() => {
window.events.$emit('server:deleted-database', this.database.id);
})
.catch(err => {
this.$flash.clear();
console.error({ err });
const response = err.response;
if (response.data && typeof response.data.errors === 'object') {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
}
})
.then(() => {
this.$emit('close');
})
},
},
template: `
<div>
<h2 class="font-medium text-neutral-900 mb-6">Delete this database?</h2>
<p class="text-neutral-900 text-sm">This action <strong>cannot</strong> be undone. This will permanetly delete the <strong>{{database.name}}</strong> database and remove all associated data.</p>
<div class="mt-6">
<label class="input-label">Confirm database name</label>
<input type="text" class="input" v-model="nameConfirmation"/>
</div>
<div class="mt-6 text-right">
<button class="btn btn-sm btn-secondary mr-2" v-on:click="$emit('close')">Cancel</button>
<button class="btn btn-sm btn-red" :disabled="disabled" v-on:click="deleteDatabase">
<span class="spinner white" v-bind:class="{ hidden: !showSpinner }">&nbsp;</span>
<span :class="{ hidden: showSpinner }">
Confirm Deletion
</span>
</button>
</div>
</div>
`,
});

View file

@ -0,0 +1,89 @@
<template>
<div>
<h2 class="font-medium text-neutral-900 mb-6">Delete this database?</h2>
<p class="text-neutral-900 text-sm">This action
<strong>cannot</strong> be undone. This will permanetly delete the
<strong>{{database.name}}</strong> database and remove all associated data.</p>
<div class="mt-6">
<label class="input-label">Confirm database name</label>
<input type="text" class="input" v-model="nameConfirmation"/>
</div>
<div class="mt-6 text-right">
<button class="btn btn-sm btn-secondary mr-2" v-on:click="$emit('close')">Cancel</button>
<button class="btn btn-sm btn-red" :disabled="disabled" v-on:click="deleteDatabase">
<span class="spinner white" v-bind:class="{ hidden: !showSpinner }">&nbsp;</span>
<span :class="{ hidden: showSpinner }">
Confirm Deletion
</span>
</button>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import {ServerDatabase} from "@/api/server/types";
export default Vue.extend({
name: 'DeleteDatabaseModal',
props: {
database: {
type: Object as () => ServerDatabase,
required: true
},
},
data: function () {
return {
showSpinner: false,
nameConfirmation: '',
};
},
computed: {
/**
* Determine if the 'Delete' button should be enabled or not. This requires the user
* to enter the database name before actually deleting the DB.
*/
disabled: function () {
const splits: Array<string> = this.database.name.split('_');
return (
this.nameConfirmation !== this.database.name && this.nameConfirmation !== splits.slice(1).join('_')
);
}
},
methods: {
/**
* Handle deleting the database for the server instance.
*/
deleteDatabase: function () {
this.nameConfirmation = '';
this.showSpinner = true;
window.axios.delete(this.route('api.client.servers.databases.delete', {
server: this.$route.params.id,
database: this.database.id,
}))
.then(() => {
window.events.$emit('server:deleted-database', this.database.id);
})
.catch(err => {
this.$flash.clear();
console.error({err});
const response = err.response;
if (response.data && typeof response.data.errors === 'object') {
response.data.errors.forEach((error: any) => {
this.$flash.error(error.detail);
});
}
})
.then(() => {
this.$emit('close');
})
},
},
});
</script>

View file

@ -1,59 +0,0 @@
import Vue from 'vue';
import Icon from "../../../core/Icon";
export default Vue.component('file-context-menu', {
components: { Icon },
template: `
<div class="context-menu">
<div>
<div class="context-row">
<div class="icon">
<icon name="edit-3"/>
</div>
<div class="action"><span>Rename</span></div>
</div>
<div class="context-row">
<div class="icon">
<icon name="corner-up-left" class="h-4"/>
</div>
<div class="action"><span class="text-left">Move</span></div>
</div>
<div class="context-row">
<div class="icon">
<icon name="copy" class="h-4"/>
</div>
<div class="action">Copy</div>
</div>
<div class="context-row">
<div class="icon">
<icon name="download" class="h-4"/>
</div>
<div class="action">Download</div>
</div>
</div>
<div>
<div class="context-row">
<div class="icon">
<icon name="file-plus" class="h-4"/>
</div>
<div class="action">New File</div>
</div>
<div class="context-row">
<div class="icon">
<icon name="folder-plus" class="h-4"/>
</div>
<div class="action">New Folder</div>
</div>
</div>
<div>
<div class="context-row danger">
<div class="icon">
<icon name="delete" class="h-4"/>
</div>
<div class="action">Delete</div>
</div>
</div>
</div>
`,
})

View file

@ -0,0 +1,62 @@
<template>
<div class="context-menu">
<div>
<div class="context-row">
<div class="icon">
<Icon name="edit-3"/>
</div>
<div class="action"><span>Rename</span></div>
</div>
<div class="context-row">
<div class="icon">
<Icon name="corner-up-left" class="h-4"/>
</div>
<div class="action"><span class="text-left">Move</span></div>
</div>
<div class="context-row">
<div class="icon">
<Icon name="copy" class="h-4"/>
</div>
<div class="action">Copy</div>
</div>
<div class="context-row">
<div class="icon">
<Icon name="download" class="h-4"/>
</div>
<div class="action">Download</div>
</div>
</div>
<div>
<div class="context-row">
<div class="icon">
<Icon name="file-plus" class="h-4"/>
</div>
<div class="action">New File</div>
</div>
<div class="context-row">
<div class="icon">
<Icon name="folder-plus" class="h-4"/>
</div>
<div class="action">New Folder</div>
</div>
</div>
<div>
<div class="context-row danger">
<div class="icon">
<Icon name="delete" class="h-4"/>
</div>
<div class="action">Delete</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import Icon from "../../../core/Icon.vue";
export default Vue.extend({
name: 'FileContextMenu',
components: { Icon },
});
</script>

View file

@ -1,99 +0,0 @@
import Vue from 'vue';
import Icon from "../../../core/Icon";
import {Vue as VueType} from "vue/types/vue";
import { readableSize, formatDate } from '../../../../helpers'
import FileContextMenu from "./FileContextMenu";
export default Vue.component('file-row', {
components: {
Icon,
FileContextMenu,
},
props: {
file: {type: Object, required: true},
editable: {type: Array, required: true}
},
data: function () {
return {
contextMenuVisible: false,
};
},
mounted: function () {
document.addEventListener('click', this._clickListener);
// If the parent component emits the collapse menu event check if the unique ID of the component
// is this one. If not, collapse the menu (we right clicked into another element).
this.$parent.$on('collapse-menus', (uid: string) => {
// @ts-ignore
if (this._uid !== uid) {
this.contextMenuVisible = false;
}
})
},
beforeDestroy: function () {
document.removeEventListener('click', this._clickListener, false);
},
methods: {
/**
* Handle a right-click action on a file manager row.
*/
showContextMenu: function (e: MouseEvent) {
e.preventDefault();
// @ts-ignore
this.$parent.$emit('collapse-menus', this._uid);
this.contextMenuVisible = true;
const menuWidth = (this.$refs.contextMenu as VueType).$el.clientWidth;
const positionElement = e.clientX - Math.round(menuWidth / 2);
(this.$refs.contextMenu as VueType).$el.setAttribute('style', `left: ${positionElement}; top: ${e.clientY}`);
},
/**
* Determine if a file can be edited on the Panel.
*/
canEdit: function (file: any): boolean {
return this.editable.indexOf(file.mime) >= 0;
},
/**
* Handle a click anywhere in the document and hide the context menu if that click is not
* a right click and isn't occurring somewhere in the currently visible context menu.
*
* @private
*/
_clickListener: function (e: MouseEvent) {
if (e.button !== 2 && this.contextMenuVisible) {
if (e.target !== (this.$refs.contextMenu as VueType).$el && !(this.$refs.contextMenu as VueType).$el.contains(e.target as Node)) {
this.contextMenuVisible = false;
}
}
},
readableSize: readableSize,
formatDate: formatDate,
},
template: `
<div>
<div class="row" :class="{ clickable: canEdit(file), 'active-selection': contextMenuVisible }" v-on:contextmenu="showContextMenu">
<div class="flex-none icon">
<icon name="file-text" v-if="!file.symlink"/>
<icon name="link2" v-else/>
</div>
<div class="flex-1">{{file.name}}</div>
<div class="flex-1 text-right text-neutral-600">{{readableSize(file.size)}}</div>
<div class="flex-1 text-right text-neutral-600">{{formatDate(file.modified)}}</div>
<div class="flex-none w-1/6"></div>
</div>
<file-context-menu class="context-menu" v-show="contextMenuVisible" ref="contextMenu"/>
</div>
`
});

View file

@ -0,0 +1,102 @@
<template>
<div>
<div class="row" :class="{ clickable: canEdit(file), 'active-selection': contextMenuVisible }" v-on:contextmenu="showContextMenu">
<div class="flex-none icon">
<Icon name="file-text" v-if="!file.symlink"/>
<Icon name="link2" v-else/>
</div>
<div class="flex-1">{{file.name}}</div>
<div class="flex-1 text-right text-neutral-600">{{readableSize(file.size)}}</div>
<div class="flex-1 text-right text-neutral-600">{{formatDate(file.modified)}}</div>
<div class="flex-none w-1/6"></div>
</div>
<FileContextMenu class="context-menu" v-show="contextMenuVisible" ref="contextMenu"/>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import Icon from "../../../core/Icon.vue";
import {Vue as VueType} from "vue/types/vue";
import {formatDate, readableSize} from '../../../../helpers'
import FileContextMenu from "./FileContextMenu.vue";
export default Vue.extend({
name: 'FileRow',
components: {
Icon,
FileContextMenu,
},
props: {
file: {type: Object, required: true},
editable: {type: Array, required: true}
},
data: function () {
return {
contextMenuVisible: false,
};
},
mounted: function () {
document.addEventListener('click', this._clickListener);
// If the parent component emits the collapse menu event check if the unique ID of the component
// is this one. If not, collapse the menu (we right clicked into another element).
this.$parent.$on('collapse-menus', (uid: string) => {
// @ts-ignore
if (this._uid !== uid) {
this.contextMenuVisible = false;
}
})
},
beforeDestroy: function () {
document.removeEventListener('click', this._clickListener, false);
},
methods: {
/**
* Handle a right-click action on a file manager row.
*/
showContextMenu: function (e: MouseEvent) {
e.preventDefault();
// @ts-ignore
this.$parent.$emit('collapse-menus', this._uid);
this.contextMenuVisible = true;
const menuWidth = (this.$refs.contextMenu as VueType).$el.clientWidth;
const positionElement = e.clientX - Math.round(menuWidth / 2);
(this.$refs.contextMenu as VueType).$el.setAttribute('style', `left: ${positionElement}; top: ${e.clientY}`);
},
/**
* Determine if a file can be edited on the Panel.
*/
canEdit: function (file: any): boolean {
return this.editable.indexOf(file.mime) >= 0;
},
/**
* Handle a click anywhere in the document and hide the context menu if that click is not
* a right click and isn't occurring somewhere in the currently visible context menu.
*
* @private
*/
_clickListener: function (e: MouseEvent) {
if (e.button !== 2 && this.contextMenuVisible) {
if (e.target !== (this.$refs.contextMenu as VueType).$el && !(this.$refs.contextMenu as VueType).$el.contains(e.target as Node)) {
this.contextMenuVisible = false;
}
}
},
readableSize: readableSize,
formatDate: formatDate,
},
});
</script>

View file

@ -1,44 +0,0 @@
import Vue from 'vue';
import { formatDate } from "@/helpers";
import Icon from "@/components/core/Icon";
export default Vue.component('folder-row', {
components: { Icon },
props: {
directory: {type: Object, required: true},
},
data: function () {
return {
currentDirectory: this.$route.params.path || '/',
};
},
methods: {
/**
* Return a formatted directory path that is used to switch to a nested directory.
*/
getClickablePath (directory: string): string {
return `${this.currentDirectory.replace(/\/$/, '')}/${directory}`;
},
formatDate: formatDate,
},
template: `
<div>
<router-link class="row clickable"
:to="{ name: 'server-files', params: { path: getClickablePath(directory.name).replace(/^\\//, '') }}"
>
<div class="flex-none icon text-primary-700">
<icon name="folder"/>
</div>
<div class="flex-1">{{directory.name}}</div>
<div class="flex-1 text-right text-neutral-600"></div>
<div class="flex-1 text-right text-neutral-600">{{formatDate(directory.modified)}}</div>
<div class="flex-none w-1/6"></div>
</router-link>
</div>
`
});

View file

@ -0,0 +1,47 @@
<template>
<div>
<router-link class="row clickable"
:to="{ name: 'server-files', params: { path: getClickablePath(directory.name) }}"
>
<div class="flex-none icon text-primary-700">
<Icon name="folder"/>
</div>
<div class="flex-1">{{directory.name}}</div>
<div class="flex-1 text-right text-neutral-600"></div>
<div class="flex-1 text-right text-neutral-600">{{formatDate(directory.modified)}}</div>
<div class="flex-none w-1/6"></div>
</router-link>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import { formatDate } from "@/helpers";
import Icon from "@/components/core/Icon.vue";
export default Vue.extend({
name: 'FolderRow',
components: { Icon },
props: {
directory: {type: Object, required: true},
},
data: function () {
return {
currentDirectory: this.$route.params.path || '/',
};
},
methods: {
/**
* Return a formatted directory path that is used to switch to a nested directory.
*/
getClickablePath (directory: string): string {
return `${this.currentDirectory.replace(/\/$/, '')}/${directory}`;
},
formatDate: formatDate,
},
});
</script>

View file

@ -1,4 +0,0 @@
export {default as Server} from './Server';
export {default as ConsolePage} from './subpages/Console';
export {default as DatabasesPage} from './subpages/Databases';
export {default as FileManagerPage} from './subpages/FileManager';

View file

@ -1,186 +0,0 @@
import Vue from 'vue';
import {mapState} from "vuex";
import {Terminal} from 'xterm';
import * as TerminalFit from 'xterm/lib/addons/fit/fit';
import {Socketio} from "@/mixins/socketio";
type DataStructure = {
terminal: Terminal | null,
command: string,
commandHistory: Array<string>,
commandHistoryIndex: number,
}
export default Vue.component('server-console', {
mixins: [Socketio],
computed: {
...mapState('socket', ['connected']),
},
watch: {
/**
* Watch the connected variable and when it becomes true request the server logs.
*/
connected: function (state: boolean) {
if (state) {
this.$nextTick(() => {
this.mountTerminal();
});
} else {
this.terminal && this.terminal.clear();
}
},
},
/**
* Listen for specific socket.io emits from the server.
*/
sockets: {
'server log': function (data: string) {
data.split(/\n/g).forEach((line: string): void => {
if (this.terminal) {
this.terminal.writeln(line + '\u001b[0m');
}
});
},
'console': function (data: { line: string }) {
data.line.split(/\n/g).forEach((line: string): void => {
if (this.terminal) {
this.terminal.writeln(line + '\u001b[0m');
}
});
},
},
/**
* Mount the component and setup all of the terminal actions. Also fetches the initial
* logs from the server to populate into the terminal if the socket is connected. If the
* socket is not connected this will occur automatically when it connects.
*/
mounted: function () {
if (this.connected) {
this.mountTerminal();
}
},
data: function (): DataStructure {
return {
terminal: null,
command: '',
commandHistory: [],
commandHistoryIndex: -1,
};
},
methods: {
/**
* Mount the terminal and grab the most recent server logs.
*/
mountTerminal: function () {
// Get a new instance of the terminal setup.
this.terminal = this._terminalInstance();
this.terminal.open((this.$refs.terminal as HTMLElement));
// @ts-ignore
this.terminal.fit();
this.terminal.clear();
this.$socket().instance().emit('send server log');
},
/**
* Send a command to the server using the configured websocket.
*/
sendCommand: function () {
this.commandHistoryIndex = -1;
this.commandHistory.unshift(this.command);
this.$socket().instance().emit('send command', this.command);
this.command = '';
},
/**
* Handle a user pressing up/down arrows when in the command field to scroll through thier
* command history for this server.
*/
handleArrowKey: function (e: KeyboardEvent) {
if (['ArrowUp', 'ArrowDown'].indexOf(e.key) < 0 || e.key === 'ArrowDown' && this.commandHistoryIndex < 0) {
return;
}
e.preventDefault();
e.stopPropagation();
if (e.key === 'ArrowUp' && (this.commandHistoryIndex + 1 > (this.commandHistory.length - 1))) {
return;
}
this.commandHistoryIndex += (e.key === 'ArrowUp') ? 1 : -1;
this.command = this.commandHistoryIndex < 0 ? '' : this.commandHistory[this.commandHistoryIndex];
},
/**
* Returns a new instance of the terminal to be used.
*
* @private
*/
_terminalInstance() {
Terminal.applyAddon(TerminalFit);
return new Terminal({
disableStdin: true,
cursorStyle: 'underline',
allowTransparency: true,
fontSize: 12,
fontFamily: 'Menlo, Monaco, Consolas, monospace',
rows: 30,
theme: {
background: 'transparent',
cursor: 'transparent',
black: '#000000',
red: '#E54B4B',
green: '#9ECE58',
yellow: '#FAED70',
blue: '#396FE2',
magenta: '#BB80B3',
cyan: '#2DDAFD',
white: '#d0d0d0',
brightBlack: 'rgba(255, 255, 255, 0.2)',
brightRed: '#FF5370',
brightGreen: '#C3E88D',
brightYellow: '#FFCB6B',
brightBlue: '#82AAFF',
brightMagenta: '#C792EA',
brightCyan: '#89DDFF',
brightWhite: '#ffffff',
},
});
}
},
template: `
<div class="animate fadein shadow-md">
<div class="text-xs font-mono">
<div class="rounded-t p-2 bg-black overflow-scroll w-full" style="min-height: 16rem;max-height:64rem;">
<div class="mb-2 text-neutral-400" ref="terminal" v-if="connected"></div>
<div v-else>
<div class="spinner spinner-xl mt-24"></div>
</div>
</div>
<div class="rounded-b bg-neutral-900 text-white flex">
<div class="flex-no-shrink p-2">
<span class="font-bold">$</span>
</div>
<div class="w-full">
<input type="text" aria-label="Send console command" class="bg-transparent text-white p-2 pl-0 w-full" placeholder="enter command and press enter to send"
ref="command"
v-model="command"
v-on:keyup.enter="sendCommand"
v-on:keydown="handleArrowKey"
>
</div>
</div>
</div>
</div>
`,
});

View file

@ -0,0 +1,189 @@
<template>
<div class="animate fadein shadow-md">
<div class="text-xs font-mono">
<div class="rounded-t p-2 bg-black overflow-scroll w-full" style="min-height: 16rem;max-height:64rem;">
<div class="mb-2 text-neutral-400" ref="terminal" v-if="connected"></div>
<div v-else>
<div class="spinner spinner-xl mt-24"></div>
</div>
</div>
<div class="rounded-b bg-neutral-900 text-white flex">
<div class="flex-no-shrink p-2">
<span class="font-bold">$</span>
</div>
<div class="w-full">
<input type="text" aria-label="Send console command" class="bg-transparent text-white p-2 pl-0 w-full" placeholder="enter command and press enter to send"
ref="command"
v-model="command"
v-on:keyup.enter="sendCommand"
v-on:keydown="handleArrowKey"
>
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import {mapState} from "vuex";
import {Terminal} from 'xterm';
import * as TerminalFit from 'xterm/lib/addons/fit/fit';
import {Socketio} from "@/mixins/socketio";
type DataStructure = {
terminal: Terminal | null,
command: string,
commandHistory: Array<string>,
commandHistoryIndex: number,
}
export default Vue.extend({
name: 'ServerConsole',
mixins: [Socketio],
computed: {
...mapState('socket', ['connected']),
},
watch: {
/**
* Watch the connected variable and when it becomes true request the server logs.
*/
connected: function (state: boolean) {
if (state) {
this.$nextTick(() => {
this.mountTerminal();
});
} else {
this.terminal && this.terminal.clear();
}
},
},
/**
* Listen for specific socket.io emits from the server.
*/
sockets: {
'server log': function (data: string) {
data.split(/\n/g).forEach((line: string): void => {
if (this.terminal) {
this.terminal.writeln(line + '\u001b[0m');
}
});
},
'console': function (data: { line: string }) {
data.line.split(/\n/g).forEach((line: string): void => {
if (this.terminal) {
this.terminal.writeln(line + '\u001b[0m');
}
});
},
},
/**
* Mount the component and setup all of the terminal actions. Also fetches the initial
* logs from the server to populate into the terminal if the socket is connected. If the
* socket is not connected this will occur automatically when it connects.
*/
mounted: function () {
if (this.connected) {
this.mountTerminal();
}
},
data: function (): DataStructure {
return {
terminal: null,
command: '',
commandHistory: [],
commandHistoryIndex: -1,
};
},
methods: {
/**
* Mount the terminal and grab the most recent server logs.
*/
mountTerminal: function () {
// Get a new instance of the terminal setup.
this.terminal = this._terminalInstance();
this.terminal.open((this.$refs.terminal as HTMLElement));
// @ts-ignore
this.terminal.fit();
this.terminal.clear();
this.$socket().instance().emit('send server log');
},
/**
* Send a command to the server using the configured websocket.
*/
sendCommand: function () {
this.commandHistoryIndex = -1;
this.commandHistory.unshift(this.command);
this.$socket().instance().emit('send command', this.command);
this.command = '';
},
/**
* Handle a user pressing up/down arrows when in the command field to scroll through thier
* command history for this server.
*/
handleArrowKey: function (e: KeyboardEvent) {
if (['ArrowUp', 'ArrowDown'].indexOf(e.key) < 0 || e.key === 'ArrowDown' && this.commandHistoryIndex < 0) {
return;
}
e.preventDefault();
e.stopPropagation();
if (e.key === 'ArrowUp' && (this.commandHistoryIndex + 1 > (this.commandHistory.length - 1))) {
return;
}
this.commandHistoryIndex += (e.key === 'ArrowUp') ? 1 : -1;
this.command = this.commandHistoryIndex < 0 ? '' : this.commandHistory[this.commandHistoryIndex];
},
/**
* Returns a new instance of the terminal to be used.
*
* @private
*/
_terminalInstance() {
Terminal.applyAddon(TerminalFit);
return new Terminal({
disableStdin: true,
cursorStyle: 'underline',
allowTransparency: true,
fontSize: 12,
fontFamily: 'Menlo, Monaco, Consolas, monospace',
rows: 30,
theme: {
background: 'transparent',
cursor: 'transparent',
black: '#000000',
red: '#E54B4B',
green: '#9ECE58',
yellow: '#FAED70',
blue: '#396FE2',
magenta: '#BB80B3',
cyan: '#2DDAFD',
white: '#d0d0d0',
brightBlack: 'rgba(255, 255, 255, 0.2)',
brightRed: '#FF5370',
brightGreen: '#C3E88D',
brightYellow: '#FFCB6B',
brightBlue: '#82AAFF',
brightMagenta: '#C792EA',
brightCyan: '#89DDFF',
brightWhite: '#ffffff',
},
});
}
},
});
</script>

View file

@ -1,112 +0,0 @@
import Vue from 'vue';
import { map, filter } from 'lodash';
import Modal from '@/components/core/Modal';
import CreateDatabaseModal from './../components/database/CreateDatabaseModal';
import Icon from "@/components/core/Icon";
import {ServerDatabase} from "@/api/server/types";
import DatabaseRow from "@/components/server/components/database/DatabaseRow";
type DataStructure = {
loading: boolean,
showCreateModal: boolean,
databases: Array<ServerDatabase>,
}
export default Vue.component('server-databases', {
components: {DatabaseRow, CreateDatabaseModal, Modal, Icon },
data: function (): DataStructure {
return {
databases: [],
loading: true,
showCreateModal: false,
};
},
mounted: function () {
this.getDatabases();
window.events.$on('server:deleted-database', this.removeDatabase);
},
methods: {
/**
* Get all of the databases that exist for this server.
*/
getDatabases: function () {
this.$flash.clear();
this.loading = true;
window.axios.get(this.route('api.client.servers.databases', {
server: this.$route.params.id,
include: 'password'
}))
.then(response => {
this.databases = map(response.data.data, (object) => {
const data = object.attributes;
data.password = data.relationships.password.attributes.password;
data.showPassword = false;
delete data.relationships;
return data;
});
})
.catch(err => {
this.$flash.error('There was an error encountered while attempting to fetch databases for this server.');
console.error(err);
})
.then(() => {
this.loading = false;
});
},
/**
* Add the database to the list of existing databases automatically when the modal
* is closed with a successful callback.
*/
handleModalCallback: function (data: ServerDatabase) {
this.databases.push(data);
},
/**
* Handle event that is removing a database.
*/
removeDatabase: function (databaseId: string) {
this.databases = filter(this.databases, (database) => {
return database.id !== databaseId;
});
}
},
template: `
<div>
<div v-if="loading">
<div class="spinner spinner-xl blue"></div>
</div>
<div class="animate fadein" v-else>
<div class="content-box mb-6" v-if="!databases.length">
<div class="flex items-center">
<icon name="database" class="flex-none text-neutral-800"></icon>
<div class="flex-1 px-4 text-neutral-800">
<p>You have no databases.</p>
</div>
</div>
</div>
<div v-else>
<DatabaseRow v-for="database in databases" :database="database" :key="database.name"/>
</div>
<div>
<button class="btn btn-primary btn-lg" v-on:click="showCreateModal = true">Create new database</button>
</div>
<modal :show="showCreateModal" v-on:close="showCreateModal = false">
<CreateDatabaseModal
v-on:close="showCreateModal = false"
v-on:database="handleModalCallback"
v-if="showCreateModal"
/>
</modal>
</div>
</div>
`,
});

View file

@ -0,0 +1,115 @@
<template>
<div>
<div v-if="loading">
<div class="spinner spinner-xl blue"></div>
</div>
<div class="animate fadein" v-else>
<div class="content-box mb-6" v-if="!databases.length">
<div class="flex items-center">
<Icon name="database" class="flex-none text-neutral-800"></icon>
<div class="flex-1 px-4 text-neutral-800">
<p>You have no databases.</p>
</div>
</div>
</div>
<div v-else>
<DatabaseRow v-for="database in databases" :database="database" :key="database.name"/>
</div>
<div>
<button class="btn btn-primary btn-lg" v-on:click="showCreateModal = true">Create new database</button>
</div>
<Modal :show="showCreateModal" v-on:close="showCreateModal = false">
<CreateDatabaseModal
v-on:close="showCreateModal = false"
v-on:database="handleModalCallback"
v-if="showCreateModal"
/>
</modal>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import {filter, map} from 'lodash';
import Modal from '@/components/core/Modal.vue';
import CreateDatabaseModal from './../components/database/CreateDatabaseModal.vue';
import Icon from "@/components/core/Icon.vue";
import {ServerDatabase} from "@/api/server/types";
import DatabaseRow from "@/components/server/components/database/DatabaseRow.vue";
type DataStructure = {
loading: boolean,
showCreateModal: boolean,
databases: Array<ServerDatabase>,
}
export default Vue.extend({
name: 'ServerDatabases',
components: {DatabaseRow, CreateDatabaseModal, Modal, Icon},
data: function (): DataStructure {
return {
databases: [],
loading: true,
showCreateModal: false,
};
},
mounted: function () {
this.getDatabases();
window.events.$on('server:deleted-database', this.removeDatabase);
},
methods: {
/**
* Get all of the databases that exist for this server.
*/
getDatabases: function () {
this.$flash.clear();
this.loading = true;
window.axios.get(this.route('api.client.servers.databases', {
server: this.$route.params.id,
include: 'password'
}))
.then(response => {
this.databases = map(response.data.data, (object) => {
const data = object.attributes;
data.password = data.relationships.password.attributes.password;
data.showPassword = false;
delete data.relationships;
return data;
});
})
.catch(err => {
this.$flash.error('There was an error encountered while attempting to fetch databases for this server.');
console.error(err);
})
.then(() => {
this.loading = false;
});
},
/**
* Add the database to the list of existing databases automatically when the modal
* is closed with a successful callback.
*/
handleModalCallback: function (data: ServerDatabase) {
this.databases.push(data);
},
/**
* Handle event that is removing a database.
*/
removeDatabase: function (databaseId: string) {
this.databases = filter(this.databases, (database) => {
return database.id !== databaseId;
});
}
},
});
</script>

View file

@ -1,9 +1,62 @@
<template>
<div class="animated-fade-in">
<div class="filemanager-breadcrumbs">
/<span class="px-1">home</span><!--
-->/<router-link :to="{ name: 'server-files' }" class="px-1">container</router-link><!--
--><span v-for="crumb in breadcrumbs" class="inline-block">
<span v-if="crumb.path">
/<router-link :to="{ name: 'server-files', params: { path: crumb.path } }" class="px-1">{{crumb.directoryName}}</router-link>
</span>
<span v-else>
/<span class="px-1 text-neutral-600 font-medium">{{crumb.directoryName}}</span>
</span>
</span>
</div>
<div class="content-box">
<div v-if="loading">
<div class="spinner spinner-xl blue"></div>
</div>
<div v-else-if="!loading && errorMessage">
<div class="alert error" v-text="errorMessage"></div>
</div>
<div v-else-if="!directories.length && !files.length">
<p class="text-neutral-500 text-sm text-center p-6 pb-4">This directory is empty.</p>
</div>
<div class="filemanager animated-fade-in" v-else>
<div class="header">
<div class="flex-none w-8"></div>
<div class="flex-1">Name</div>
<div class="flex-1 text-right">Size</div>
<div class="flex-1 text-right">Modified</div>
<div class="flex-none w-1/6">Actions</div>
</div>
<div v-for="directory in directories">
<FolderRow :directory="directory"/>
</div>
<div v-for="file in files">
<FileRow :file="file" :editable="editableFiles" />
</div>
</div>
</div>
<div class="flex mt-6" v-if="!loading && !errorMessage">
<div class="flex-1"></div>
<div class="mr-4">
<a href="#" class="block btn btn-secondary btn-sm">New Folder</a>
</div>
<div>
<a href="#" class="block btn btn-primary btn-sm">New File</a>
</div>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import {mapState} from "vuex";
import { map } from 'lodash';
import getDirectoryContents from "@/api/server/getDirectoryContents";
import FileRow from "@/components/server/components/filemanager/FileRow";
import FolderRow from "@/components/server/components/filemanager/FolderRow";
import FileRow from "@/components/server/components/filemanager/FileRow.vue";
import FolderRow from "@/components/server/components/filemanager/FolderRow.vue";
type DataStructure = {
loading: boolean,
@ -14,7 +67,8 @@ type DataStructure = {
editableFiles: Array<string>,
}
export default Vue.component('file-manager', {
export default Vue.extend({
name: 'FileManager',
components: { FileRow, FolderRow },
computed: {
...mapState('server', ['server', 'credentials']),
@ -113,56 +167,5 @@ export default Vue.component('file-manager', {
});
},
},
template: `
<div class="animated-fade-in">
<div class="filemanager-breadcrumbs">
/<span class="px-1">home</span><!--
-->/<router-link :to="{ name: 'server-files' }" class="px-1">container</router-link><!--
--><span v-for="crumb in breadcrumbs" class="inline-block">
<span v-if="crumb.path">
/<router-link :to="{ name: 'server-files', params: { path: crumb.path } }" class="px-1">{{crumb.directoryName}}</router-link>
</span>
<span v-else>
/<span class="px-1 text-neutral-600 font-medium">{{crumb.directoryName}}</span>
</span>
</span>
</div>
<div class="content-box">
<div v-if="loading">
<div class="spinner spinner-xl blue"></div>
</div>
<div v-else-if="!loading && errorMessage">
<div class="alert error" v-text="errorMessage"></div>
</div>
<div v-else-if="!directories.length && !files.length">
<p class="text-neutral-500 text-sm text-center p-6 pb-4">This directory is empty.</p>
</div>
<div class="filemanager animated-fade-in" v-else>
<div class="header">
<div class="flex-none w-8"></div>
<div class="flex-1">Name</div>
<div class="flex-1 text-right">Size</div>
<div class="flex-1 text-right">Modified</div>
<div class="flex-none w-1/6">Actions</div>
</div>
<div v-for="directory in directories">
<folder-row :directory="directory"/>
</div>
<div v-for="file in files">
<file-row :file="file" :editable="editableFiles" />
</div>
</div>
</div>
<div class="flex mt-6" v-if="!loading && !errorMessage">
<div class="flex-1"></div>
<div class="mr-4">
<a href="#" class="block btn btn-secondary btn-sm">New Folder</a>
</div>
<div>
<a href="#" class="block btn btn-primary btn-sm">New File</a>
</div>
</div>
</div>
`,
});
</script>

View file

@ -1,25 +1,32 @@
import VueRouter, {Route} from 'vue-router';
import store from './store/index';
import User from './models/user';
const route = require('./../../../vendor/tightenco/ziggy/src/js/route').default;
// Base Vuejs Templates
import Login from './components/auth/Login';
import Dashboard from './components/dashboard/Dashboard';
import Account from './components/dashboard/Account';
import ResetPassword from './components/auth/ResetPassword';
import User from './models/user';
import {
Server,
ConsolePage,
FileManagerPage,
DatabasesPage,
} from './components/server';
import Login from './components/auth/Login.vue';
import Dashboard from './components/dashboard/Dashboard.vue';
import Account from './components/dashboard/Account.vue';
import ResetPassword from './components/auth/ResetPassword.vue';
import LoginForm from "@/components/auth/LoginForm.vue";
import ForgotPassword from "@/components/auth/ForgotPassword.vue";
import TwoFactorForm from "@/components/auth/TwoFactorForm.vue";
import Server from "@/components/server/Server.vue";
import ConsolePage from "@/components/server/subpages/Console.vue";
import FileManagerPage from "@/components/server/subpages/FileManager.vue";
import DatabasesPage from "@/components/server/subpages/Databases.vue";
const routes = [
{name: 'login', path: '/auth/login', component: Login},
{name: 'forgot-password', path: '/auth/password', component: Login},
{name: 'checkpoint', path: '/auth/checkpoint', component: Login},
{
path: '/auth', component: Login,
children: [
{ name: 'login', path: 'login', component: LoginForm },
{ name: 'forgot-password', path: 'password', component: ForgotPassword },
{ name: 'checkpoint', path: 'checkpoint', component: TwoFactorForm },
]
},
{
name: 'reset-password',
path: '/auth/password/reset/:token',