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,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>