blob: 975f258bb910b930e28aa1256e589a44c063d4f2 [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 },
20 authError(state) {
Yoshie Muranaka4b0fc1d2020-01-06 07:36:16 -080021 state.authError = true;
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 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'))
Derick Montaguec031b692020-02-12 15:55:42 -060041 .then(() => router.go('/login'))
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080042 .catch(error => console.log(error));
Derick Montaguee080a1a2019-12-04 16:30:08 -060043 }
44 }
45};
46
47export default AuthenticationStore;