blob: 7a0c5ba3a58ef52466412531f9f7f31290f180fe [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 Muranaka23f227d2020-05-01 14:19:43 -070013 isLoggedIn: state => !!state.cookie,
14 token: state => state.cookie
Derick Montaguee080a1a2019-12-04 16:30:08 -060015 },
16 mutations: {
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080017 authSuccess(state) {
Yoshie Muranaka4b0fc1d2020-01-06 07:36:16 -080018 state.authError = false;
Derick Montaguefded0d12019-12-11 06:16:40 -060019 state.cookie = Cookies.get('XSRF-TOKEN');
Derick Montaguee080a1a2019-12-04 16:30:08 -060020 },
Derick Montaguea06fe462020-03-11 13:48:42 -050021 authError(state, authError = true) {
22 state.authError = authError;
Derick Montague676f2fc2019-12-23 20:53:49 -060023 },
Derick Montaguec031b692020-02-12 15:55:42 -060024 logout() {
Derick Montaguefded0d12019-12-11 06:16:40 -060025 Cookies.remove('XSRF-TOKEN');
Derick Montaguee080a1a2019-12-04 16:30:08 -060026 }
27 },
28 actions: {
29 login({ commit }, auth) {
Derick Montaguea06fe462020-03-11 13:48:42 -050030 commit('authError', false);
Derick Montaguee080a1a2019-12-04 16:30:08 -060031 return api
Derick Montaguefded0d12019-12-11 06:16:40 -060032 .post('/login', { data: auth })
33 .then(() => commit('authSuccess'))
Derick Montaguee080a1a2019-12-04 16:30:08 -060034 .catch(error => {
Derick Montaguefded0d12019-12-11 06:16:40 -060035 commit('authError');
Derick Montaguee080a1a2019-12-04 16:30:08 -060036 throw new Error(error);
37 });
38 },
39 logout({ commit }) {
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080040 api
Derick Montaguefded0d12019-12-11 06:16:40 -060041 .post('/logout', { data: [] })
42 .then(() => commit('logout'))
Derick Montaguec031b692020-02-12 15:55:42 -060043 .then(() => router.go('/login'))
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080044 .catch(error => console.log(error));
Derick Montaguee080a1a2019-12-04 16:30:08 -060045 }
46 }
47};
48
49export default AuthenticationStore;