misc_pterodactyl-panel/resources/assets/scripts/store/modules/auth.js

99 lines
3.4 KiB
JavaScript
Raw Normal View History

import User from './../../models/user';
const route = require('./../../../../../vendor/tightenco/ziggy/src/js/route').default;
export default {
namespaced: true,
state: {
user: User.fromToken(),
},
getters: {
/**
* Return the currently authenticated user.
*
* @param state
* @returns {User|null}
*/
2018-06-12 05:36:43 +00:00
getUser: function (state) {
return state.user;
2018-06-12 05:36:43 +00:00
},
},
setters: {},
actions: {
2018-06-12 05:36:43 +00:00
/**
* 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})
.then(response => {
commit('logout');
// 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)) {
return reject(new Error('An error was encountered while processing this request.'));
}
if (response.data.complete) {
commit('login', {jwt: response.data.jwt});
return resolve({
complete: true,
intended: response.data.intended,
});
}
return resolve({
complete: false,
token: response.data.login_token,
});
})
.catch(reject);
});
},
2018-06-12 05:36:43 +00:00
/**
* 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}) {
2018-06-12 05:36:43 +00:00
return new Promise((resolve, reject) => {
window.axios.put(route('api.client.account.update-email'), {email, password})
2018-06-12 05:36:43 +00:00
.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)) {
return reject(new Error('An error was encountered while processing this request.'));
}
commit('setEmail', response.data.email);
return resolve();
})
.catch(reject);
});
},
},
mutations: {
2018-06-12 05:36:43 +00:00
setEmail: function (state, email) {
state.user.email = email;
},
login: function (state, {jwt}) {
localStorage.setItem('token', jwt);
state.user = User.fromToken(jwt);
},
logout: function (state) {
localStorage.removeItem('token');
state.user = null;
},
},
};