Merge branch 'feature/vuejs' into feature/vue-serverview

This commit is contained in:
Dane Everitt 2018-07-15 16:50:11 -07:00
commit f2d2725ca0
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
130 changed files with 2275 additions and 1363 deletions

View file

@ -2,37 +2,31 @@ import Vue from 'vue';
import Vuex from 'vuex';
import vuexI18n from 'vuex-i18n';
import VueRouter from 'vue-router';
import VeeValidate from 'vee-validate';
Vue.config.productionTip = false;
require('./bootstrap');
// Helpers
import { Ziggy } from './helpers/ziggy';
import Locales from './../../../resources/lang/locales';
import { flash } from './mixins/flash';
import { routes } from './routes';
import createStore from './store';
import store from './store/index.js';
import router from './router';
window.events = new Vue;
window.Ziggy = Ziggy;
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history', routes
});
Vue.use(Vuex);
const store = createStore(router);
Vue.config.productionTip = false;
Vue.use(VueRouter);
Vue.use(vuexI18n.plugin, store);
Vue.use(VeeValidate);
const route = require('./../../../vendor/tightenco/ziggy/src/js/route').default;
Vue.mixin({ methods: { route } });
Vue.mixin(flash);
Vue.use(vuexI18n.plugin, store);
Vue.i18n.add('en', Locales.en);
Vue.i18n.set('en');

View file

@ -1,11 +1,11 @@
<template>
<div>
<form class="bg-white shadow-lg rounded-lg pt-10 px-8 pb-6 mb-4 animate fadein" method="post"
<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" id="grid-email" type="email" aria-labelledby="grid-email-label" required
<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"

View file

@ -1,11 +1,11 @@
<template>
<div>
<form class="bg-white shadow-lg rounded-lg pt-10 px-8 pb-6 mb-4 animate fadein" method="post"
<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" id="grid-username" type="text" name="user" aria-labelledby="grid-username-label" required
<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"
@ -17,7 +17,7 @@
</div>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input" id="grid-password" type="password" name="password" aria-labelledby="grid-password-label" required
<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"
@ -62,7 +62,6 @@
},
data: function () {
return {
errors: [],
showSpinner: false,
}
},
@ -91,7 +90,7 @@
this.$props.user.password = '';
this.$data.showSpinner = false;
this.$refs.password.focus();
this.$store.dispatch('auth/logout');
this.$store.commit('auth/logout');
if (!err.response) {
return console.error(err);

View file

@ -5,7 +5,7 @@
>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input" id="grid-email" type="email" aria-labelledby="grid-email" required
<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"
@ -16,7 +16,7 @@
</div>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input" id="grid-password" type="password" aria-labelledby="grid-password" required
<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"
@ -28,7 +28,7 @@
</div>
<div class="flex flex-wrap -mx-3 mb-6">
<div class="input-open">
<input class="input" id="grid-password-confirmation" type="password" aria-labelledby="grid-password-confirmation" required
<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"
@ -97,6 +97,11 @@
throw new Error('An error was encountered while processing this login.');
}
if (response.data.send_to_login) {
self.success('Your password has been reset, please login to continue.');
return self.$router.push({ name: 'login' });
}
return window.location = response.data.redirect_to;
})
.catch(function (err) {

View file

@ -1,10 +1,10 @@
<template>
<form class="bg-white shadow-lg rounded-lg pt-10 px-8 pb-6 mb-4 animate fadein" method="post"
<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" id="grid-code" type="number" name="token" aria-labelledby="grid-username" required
<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"

View file

@ -0,0 +1,40 @@
<template>
<transition name="modal">
<div class="modal-mask" v-show="show" v-on:click="close">
<div class="modal-container" @click.stop>
<x-icon class="absolute pin-r pin-t m-2 text-grey cursor-pointer" aria-label="Close modal" role="button"
v-on:click="close"
/>
<slot/>
</div>
</div>
</transition>
</template>
<script>
import { XIcon } from 'vue-feather-icons';
export default {
name: 'modal',
components: { XIcon },
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

@ -9,22 +9,22 @@
<ul>
<li>
<router-link :to="{ name: 'dashboard' }">
<server-icon aria-label="Server dashboard"/>
<server-icon aria-label="Server dashboard" class="h-4"/>
</router-link>
</li>
<li>
<router-link :to="{ name: 'account' }">
<user-icon aria-label="Profile management"/>
<user-icon aria-label="Profile management" class="h-4"/>
</router-link>
</li>
<li>
<a :href="this.route('admin.index')">
<settings-icon aria-label="Administrative controls"/>
<settings-icon aria-label="Administrative controls" class="h-4"/>
</a>
</li>
<li>
<a :href="this.route('auth.logout')">
<log-out-icon aria-label="Sign out"/>
<a :href="this.route('auth.logout')" v-on:click.prevent="doLogout">
<log-out-icon aria-label="Sign out" class="h-4"/>
</a>
</li>
</ul>
@ -37,6 +37,12 @@
export default {
name: 'navigation',
components: { LogOutIcon, ServerIcon, SettingsIcon, UserIcon }
components: { LogOutIcon, ServerIcon, SettingsIcon, UserIcon },
methods: {
doLogout: function () {
this.$store.commit('auth/logout');
return window.location = this.route('auth.logout');
},
}
};
</script>

View file

@ -1,13 +1,51 @@
<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>
</template>
<script>
import Navigation from '../core/Navigation';
import Flash from '../Flash';
import UpdateEmail from './account/UpdateEmail';
import ChangePassword from './account/ChangePassword';
import Modal from '../core/Modal';
import TwoFactorAuthentication from './account/TwoFactorAuthentication';
export default {
name: 'account'
name: 'account',
components: {TwoFactorAuthentication, Modal, ChangePassword, UpdateEmail, Flash, Navigation},
data: function () {
return {
modalVisible: false,
};
},
methods: {
openModal: function () {
this.$data.modalVisible = true;
window.events.$emit('two_factor:open');
},
}
};
</script>
<style scoped>
</style>

View file

@ -11,16 +11,16 @@
ref="search"
/>
</div>
<div v-if="this.isServersLoading" class="my-4 animate fadein">
<div v-if="this.loading" class="my-4 animate fadein">
<div class="text-center h-16">
<span class="spinner spinner-xl"></span>
</div>
</div>
<transition-group class="w-full m-auto mt-4 animate fadein sm:flex flex-wrap content-start">
<transition-group class="w-full m-auto mt-4 animate fadein sm:flex flex-wrap content-start" v-else>
<server-box
v-for="(server, index) in this.serverList"
:key="index"
:server="server"
v-for="(server, index) in servers"
v-bind:key="index"
v-bind:server="server"
/>
</transition-group>
</div>
@ -28,38 +28,31 @@
</template>
<script>
import { DateTime } from 'luxon';
import Server from '../../models/server';
import _ from 'lodash';
import debounce from 'lodash/debounce';
import differenceInSeconds from 'date-fns/difference_in_seconds';
import Flash from '../Flash';
import ServerBox from './ServerBox';
import Navigation from '../core/Navigation';
import {mapGetters, mapState} from 'vuex'
export default {
name: 'dashboard',
components: { Navigation, ServerBox, Flash },
data: function () {
return {
backgroundedAt: DateTime.local(),
backgroundedAt: new Date(),
documentVisible: true,
loading: true,
search: '',
servers: [],
}
},
computed: {
...mapGetters([
'isServersLoading',
'serverList'
]),
...mapState({
servers: 'servers'
})
},
/**
* Start loading the servers before the DOM $.el is created.
*/
created: function () {
this.$store.dispatch('loadServers')
this.loadServers();
document.addEventListener('visibilitychange', () => {
this.documentVisible = document.visibilityState === 'visible';
@ -76,11 +69,50 @@
},
methods: {
/**
* Load the user's servers and render them onto the dashboard.
*
* @param {string} query
*/
loadServers: function (query = '') {
this.loading = true;
window.axios.get(this.route('api.client.index'), {
params: { query },
})
.finally(() => {
this.clearFlashes();
})
.then(response => {
this.servers = [];
response.data.data.forEach(obj => {
const s = new Server(obj.attributes);
this.servers.push(s);
this.getResourceUse(s);
});
if (this.servers.length === 0) {
this.info(this.$t('dashboard.index.no_matches'));
}
})
.catch(err => {
console.error(err);
const response = err.response;
if (response.data && _.isObject(response.data.errors)) {
response.data.errors.forEach(error => {
this.error(error.detail);
});
}
})
.finally(() => {
this.loading = false;
});
},
/**
* Handle a search for servers but only call the search function every 500ms
* at the fastest.
*/
onChange: _.debounce(function () {
onChange: debounce(function () {
this.loadServers(this.$data.search);
}, 500),
@ -124,14 +156,14 @@
*/
_handleDocumentVisibilityChange: function (isVisible) {
if (!isVisible) {
this.backgroundedAt = DateTime.local();
this.backgroundedAt = new Date();
return;
}
// If it has been more than 30 seconds since this window was put into the background
// lets go ahead and refresh all of the listed servers so that they have fresh stats.
const diff = DateTime.local().diff(this.backgroundedAt, 'seconds');
this._iterateServerResourceUse(diff.seconds > 30 ? 1 : 5000);
const diff = differenceInSeconds(new Date(), this.backgroundedAt);
this._iterateServerResourceUse(diff > 30 ? 1 : 5000);
},
}
};

View file

@ -0,0 +1,91 @@
<template>
<div id="change-password-container" :class>
<form method="post" v-on:submit.prevent="submitForm">
<div class="content-box">
<h2 class="mb-6 text-grey-darkest 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-blue btn-sm text-right" type="submit">{{ $t('strings.save') }}</button>
</div>
</div>
</form>
</div>
</template>
<script>
import isObject from 'lodash/isObject';
export default {
name: 'change-password',
data: function () {
return {
current: '',
newPassword: '',
confirmNew: '',
};
},
methods: {
submitForm: function () {
window.axios.put(this.route('api.client.account.update-password'), {
current_password: this.$data.current,
password: this.$data.newPassword,
password_confirmation: this.$data.confirmNew,
})
.finally(() => {
this.clearFlashes();
this.$validator.pause();
this.$data.current = '';
this.$refs.current.focus();
})
.then(() => {
this.$data.newPassword = '';
this.$data.confirmNew = '';
this.success(this.$t('dashboard.account.password.updated'));
})
.catch(err => {
if (!err.response) {
return console.error(err);
}
const response = err.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach(error => {
this.error(error.detail);
});
}
})
.finally(() => {
this.$validator.resume();
})
}
}
};
</script>

View file

@ -0,0 +1,191 @@
<template>
<div id="configure-two-factor">
<div class="h-16 text-center" v-show="spinner">
<span class="spinner spinner-xl text-blue"></span>
</div>
<div id="container-disable-two-factor" v-if="response.enabled" v-show="!spinner">
<h2 class="font-medium text-grey-darkest">{{ $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-grey-darkest">{{ $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-grey-darker 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-blue btn-jumbo" type="submit"
:disabled="submitDisabled"
v-on:click.prevent="enableTwoFactor"
>{{ $t('strings.enable') }}</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import Vue from 'vue';
import isObject from 'lodash/isObject';
export default {
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.$data.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.
Object.assign(this.$data, this.$options.data());
window.axios.get(this.route('account.two_factor'))
.finally(() => {
this.clearFlashes();
})
.then(response => {
this.$data.response = response.data;
this.$data.spinner = false;
Vue.nextTick().then(() => {
this.$refs.token.focus();
})
})
.catch(error => {
if (!error.response) {
this.error(error.message);
}
const response = error.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach(e => {
this.error(e.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.
*
* @param {String} route
* @param {String} langKey
* @private
*/
_callInternalApi: function (route, langKey) {
window.axios.post(this.route(route), {
token: this.$data.token,
})
.finally(() => {
this.clearFlashes();
})
.then(response => {
if (response.data.success) {
this.success(this.$t(`dashboard.account.two_factor.${langKey}`));
} else {
this.error(this.$t('dashboard.account.two_factor.invalid'));
}
})
.catch(error => {
if (!error.response) {
this.error(error.message);
}
const response = error.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach(e => {
this.error(e.detail);
});
}
})
.finally(() => {
this.$emit('close');
})
}
},
};
</script>

View file

@ -0,0 +1,81 @@
<template>
<div id="update-email-container" :class>
<form method="post" v-on:submit.prevent="submitForm">
<div class="content-box">
<h2 class="mb-6 text-grey-darkest 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-blue btn-sm text-right" type="submit">{{ $t('strings.save') }}</button>
</div>
</div>
</form>
</div>
</template>
<script>
import { isObject, get } from 'lodash';
import { mapState, mapActions } from 'vuex';
export default {
name: 'update-email',
data: function () {
return {
email: get(this.$store.state, 'auth.user.email', ''),
password: '',
};
},
computed: {
...mapState({
user: state => state.auth.user,
})
},
methods: {
/**
* Update a user's email address on the Panel.
*/
submitForm: function () {
this.clearFlashes();
this.updateEmail({
email: this.$data.email,
password: this.$data.password
})
.finally(() => {
this.$data.password = '';
})
.then(() => {
this.success(this.$t('dashboard.account.email.updated'));
})
.catch(error => {
if (!error.response) {
this.error(error.message);
}
const response = error.response;
if (response.data && isObject(response.data.errors)) {
response.data.errors.forEach(e => {
this.error(e.detail);
});
}
});
},
...mapActions('auth', [
'updateEmail',
])
}
};
</script>

View file

@ -1,5 +1,3 @@
import User from './../models/user';
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
@ -9,7 +7,6 @@ import User from './../models/user';
let axios = require('axios');
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.headers.common['Accept'] = 'application/json';
axios.defaults.headers.common['Authorization'] = `Bearer ${User.getToken()}`;
if (typeof phpdebugbar !== 'undefined') {
axios.interceptors.response.use(function (response) {

File diff suppressed because one or more lines are too long

View file

@ -1,39 +1,4 @@
import isString from 'lodash/isString';
import jwtDecode from 'jwt-decode';
export default class User {
/**
* Get a new user model from the JWT.
*
* @return {User | null}
*/
static fromToken(token) {
if (!isString(token)) {
token = localStorage.getItem('token');
}
if (!isString(token) || token.length < 1) {
return null;
}
const data = jwtDecode(token);
if (data.user) {
return new User(data.user);
}
return null;
}
/**
* Return the JWT for the authenticated user.
*
* @returns {string | null}
*/
static getToken()
{
return localStorage.getItem('token');
}
/**
* Create a new user model.
*
@ -45,14 +10,14 @@ export default class User {
* @param {String} language
*/
constructor({
admin,
root_admin,
username,
email,
first_name,
last_name,
language,
}) {
this.admin = admin;
this.admin = root_admin;
this.username = username;
this.email = email;
this.name = `${first_name} ${last_name}`;

View file

@ -0,0 +1,66 @@
import VueRouter from 'vue-router';
import store from './store/index';
import compareDate from 'date-fns/compare_asc'
import addHours from 'date-fns/add_hours'
import dateParse from 'date-fns/parse'
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';
const routes = [
{ name: 'login', path: '/auth/login', component: Login },
{ name: 'forgot-password', path: '/auth/password', component: Login },
{ name: 'checkpoint', path: '/auth/checkpoint', component: Login },
{
name: 'reset-password',
path: '/auth/password/reset/:token',
component: ResetPassword,
props: function (route) {
return { token: route.params.token, email: route.query.email || '' };
}
},
{ name : 'dashboard', path: '/', component: Dashboard },
{ name : 'account', path: '/account', component: Account },
{ name : 'account.api', path: '/account/api', component: Account },
{ name : 'account.security', path: '/account/security', component: Account },
{
name: 'server',
path: '/server/:id',
// component: Server,
// children: [
// { path: 'files', component: ServerFileManager }
// ],
}
];
const router = new VueRouter({
mode: 'history', routes
});
// Redirect the user to the login page if they try to access a protected route and
// have no JWT or the JWT is expired and wouldn't be accepted by the Panel.
router.beforeEach((to, from, next) => {
if (to.path === route('auth.logout')) {
return window.location = route('auth.logout');
}
const user = store.getters['auth/getUser'];
// Check that if we're accessing a non-auth route that a user exists on the page.
if (!to.path.startsWith('/auth') && !(user instanceof User)) {
store.commit('auth/logout');
return window.location = route('auth.logout');
}
// Continue on through the pipeline.
return next();
});
export default router;

View file

@ -1,20 +1,24 @@
import Vue from 'vue';
import Vuex from 'vuex';
import { sync } from 'vuex-router-sync';
import { serverModule } from "./modules/server";
import { userModule } from './modules/user';
import { authModule } from "./modules/auth";
const createStore = (router) => {
const store = new Vuex.Store({
strict: process.env.NODE_ENV !== 'production',
modules: {
userModule,
serverModule,
authModule,
},
});
sync(store, router);
return store;
};
Vue.use(Vuex);
export default createStore;
const store = new Vuex.Store({
strict: process.env.NODE_ENV !== 'production',
modules: { userModule, serverModule, authModule },
});
if (module.hot) {
module.hot.accept(['./modules/auth'], () => {
const newAuthModule = require('./modules/auth').default;
store.hotUpdate({
modules: { newAuthModule },
});
});
}
export default store;

View file

@ -1,10 +1,11 @@
import User from './../../models/user';
const route = require('./../../../../../vendor/tightenco/ziggy/src/js/route').default;
export const authModule = {
namespaced: true,
state: {
user: User.fromToken(),
user: typeof window.PterodactylUser === 'object' ? new User(window.PterodactylUser) : null,
},
getters: {
/**
@ -13,12 +14,20 @@ export const authModule = {
* @param state
* @returns {User|null}
*/
currentUser: function (state) {
getUser: function (state) {
return state.user;
}
},
},
setters: {},
actions: {
/**
* Log a user into the Panel.
*
* @param commit
* @param {String} user
* @param {String} password
* @returns {Promise<any>}
*/
login: ({commit}, {user, password}) => {
return new Promise((resolve, reject) => {
window.axios.post(route('auth.login'), {user, password})
@ -32,7 +41,7 @@ export const authModule = {
}
if (response.data.complete) {
commit('login', {jwt: response.data.jwt});
commit('login', response.data.user);
return resolve({
complete: true,
intended: response.data.intended,
@ -47,24 +56,40 @@ export const authModule = {
.catch(reject);
});
},
logout: function ({commit}) {
/**
* Update a user's email address on the Panel and store the updated result in Vuex.
*
* @param commit
* @param {String} email
* @param {String} password
* @return {Promise<any>}
*/
updateEmail: function ({commit}, {email, password}) {
return new Promise((resolve, reject) => {
window.axios.get(route('auth.logout'))
.then(() => {
commit('logout');
window.axios.put(route('api.client.account.update-email'), {email, password})
.then(response => {
// If there is a 302 redirect or some other odd behavior (basically, response that isnt
// in JSON format) throw an error and don't try to continue with the login.
if (!(response.data instanceof Object) && response.status !== 201) {
return reject(new Error('An error was encountered while processing this request.'));
}
commit('setEmail', email);
return resolve();
})
.catch(reject);
})
});
},
},
mutations: {
login: function (state, {jwt}) {
localStorage.setItem('token', jwt);
state.user = User.fromToken(jwt);
setEmail: function (state, email) {
state.user.email = email;
},
login: function (state, data) {
state.user = new User(data);
},
logout: function (state) {
localStorage.removeItem('token');
state.user = null;
},
},