blob: d64c7308a17f22af2b60668eeeb8202428588f4a [file] [log] [blame]
Derick Montaguefded0d12019-12-11 06:16:40 -06001import api from '../../api';
2import Cookies from 'js-cookie';
Derick Montaguec031b692020-02-12 15:55:42 -06003import router from '../../../router';
Derick Montaguee080a1a2019-12-04 16:30:08 -06004
5const AuthenticationStore = {
6 namespaced: true,
7 state: {
Yoshie Muranaka4b0fc1d2020-01-06 07:36:16 -08008 authError: false,
Derick Montaguefded0d12019-12-11 06:16:40 -06009 cookie: Cookies.get('XSRF-TOKEN')
Derick Montaguee080a1a2019-12-04 16:30:08 -060010 },
11 getters: {
Yoshie Muranaka4b0fc1d2020-01-06 07:36:16 -080012 authError: state => state.authError,
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080013 isLoggedIn: state => !!state.cookie
Derick Montaguee080a1a2019-12-04 16:30:08 -060014 },
15 mutations: {
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080016 authSuccess(state) {
Yoshie Muranaka4b0fc1d2020-01-06 07:36:16 -080017 state.authError = false;
Derick Montaguefded0d12019-12-11 06:16:40 -060018 state.cookie = Cookies.get('XSRF-TOKEN');
Derick Montaguee080a1a2019-12-04 16:30:08 -060019 },
Derick Montaguea06fe462020-03-11 13:48:42 -050020 authError(state, authError = true) {
21 state.authError = authError;
Derick Montague676f2fc2019-12-23 20:53:49 -060022 },
Derick Montaguec031b692020-02-12 15:55:42 -060023 logout() {
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 Montaguea06fe462020-03-11 13:48:42 -050029 commit('authError', false);
Derick Montaguee080a1a2019-12-04 16:30:08 -060030 return api
Derick Montaguefded0d12019-12-11 06:16:40 -060031 .post('/login', { data: auth })
32 .then(() => commit('authSuccess'))
Derick Montaguee080a1a2019-12-04 16:30:08 -060033 .catch(error => {
Derick Montaguefded0d12019-12-11 06:16:40 -060034 commit('authError');
Derick Montaguee080a1a2019-12-04 16:30:08 -060035 throw new Error(error);
36 });
37 },
38 logout({ commit }) {
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080039 api
Derick Montaguefded0d12019-12-11 06:16:40 -060040 .post('/logout', { data: [] })
41 .then(() => commit('logout'))
Derick Montaguec031b692020-02-12 15:55:42 -060042 .then(() => router.go('/login'))
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080043 .catch(error => console.log(error));
Derick Montaguee080a1a2019-12-04 16:30:08 -060044 }
45 }
46};
47
48export default AuthenticationStore;