blob: 8d8898efdad2955d6406db2a90be5606087fe521 [file] [log] [blame]
Derick Montaguefded0d12019-12-11 06:16:40 -06001import api from '../../api';
2import Cookies from 'js-cookie';
Derick Montaguee080a1a2019-12-04 16:30:08 -06003
4const AuthenticationStore = {
5 namespaced: true,
6 state: {
Yoshie Muranaka4b0fc1d2020-01-06 07:36:16 -08007 authError: false,
Derick Montaguefded0d12019-12-11 06:16:40 -06008 cookie: Cookies.get('XSRF-TOKEN')
Derick Montaguee080a1a2019-12-04 16:30:08 -06009 },
10 getters: {
Yoshie Muranaka4b0fc1d2020-01-06 07:36:16 -080011 authError: state => state.authError,
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080012 isLoggedIn: state => !!state.cookie
Derick Montaguee080a1a2019-12-04 16:30:08 -060013 },
14 mutations: {
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080015 authSuccess(state) {
Yoshie Muranaka4b0fc1d2020-01-06 07:36:16 -080016 state.authError = false;
Derick Montaguefded0d12019-12-11 06:16:40 -060017 state.cookie = Cookies.get('XSRF-TOKEN');
Derick Montaguee080a1a2019-12-04 16:30:08 -060018 },
19 authError(state) {
Yoshie Muranaka4b0fc1d2020-01-06 07:36:16 -080020 state.authError = true;
Derick Montague676f2fc2019-12-23 20:53:49 -060021 },
Derick Montaguee080a1a2019-12-04 16:30:08 -060022 logout(state) {
Yoshie Muranaka4b0fc1d2020-01-06 07:36:16 -080023 state.authError = false;
Derick Montaguefded0d12019-12-11 06:16:40 -060024 Cookies.remove('XSRF-TOKEN');
Derick Montaguee080a1a2019-12-04 16:30:08 -060025 }
26 },
27 actions: {
28 login({ commit }, auth) {
Derick Montaguee080a1a2019-12-04 16:30:08 -060029 return api
Derick Montaguefded0d12019-12-11 06:16:40 -060030 .post('/login', { data: auth })
31 .then(() => commit('authSuccess'))
Derick Montaguee080a1a2019-12-04 16:30:08 -060032 .catch(error => {
Derick Montaguefded0d12019-12-11 06:16:40 -060033 commit('authError');
Derick Montaguee080a1a2019-12-04 16:30:08 -060034 throw new Error(error);
35 });
36 },
37 logout({ commit }) {
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080038 api
Derick Montaguefded0d12019-12-11 06:16:40 -060039 .post('/logout', { data: [] })
40 .then(() => commit('logout'))
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080041 .catch(error => console.log(error));
Derick Montaguee080a1a2019-12-04 16:30:08 -060042 }
43 }
44};
45
46export default AuthenticationStore;