blob: 88456e95a2c6be1abb6e82f58f90f12d7399d211 [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: {
Derick Montaguefded0d12019-12-11 06:16:40 -06007 status: '',
8 cookie: Cookies.get('XSRF-TOKEN')
Derick Montaguee080a1a2019-12-04 16:30:08 -06009 },
10 getters: {
11 authStatus: state => state.status,
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080012 isLoggedIn: state => !!state.cookie
Derick Montaguee080a1a2019-12-04 16:30:08 -060013 },
14 mutations: {
15 authRequest(state) {
Derick Montaguefded0d12019-12-11 06:16:40 -060016 state.status = 'loading';
Derick Montaguee080a1a2019-12-04 16:30:08 -060017 },
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080018 authSuccess(state) {
Derick Montaguefded0d12019-12-11 06:16:40 -060019 state.status = 'authenticated';
20 state.cookie = Cookies.get('XSRF-TOKEN');
Derick Montaguee080a1a2019-12-04 16:30:08 -060021 },
22 authError(state) {
Derick Montaguefded0d12019-12-11 06:16:40 -060023 state.status = 'error';
Derick Montaguee080a1a2019-12-04 16:30:08 -060024 },
25 logout(state) {
Derick Montaguefded0d12019-12-11 06:16:40 -060026 state.status = '';
27 Cookies.remove('XSRF-TOKEN');
Derick Montaguee080a1a2019-12-04 16:30:08 -060028 }
29 },
30 actions: {
31 login({ commit }, auth) {
Derick Montaguefded0d12019-12-11 06:16:40 -060032 commit('authRequest');
Derick Montaguee080a1a2019-12-04 16:30:08 -060033 return api
Derick Montaguefded0d12019-12-11 06:16:40 -060034 .post('/login', { data: auth })
35 .then(() => commit('authSuccess'))
Derick Montaguee080a1a2019-12-04 16:30:08 -060036 .catch(error => {
Derick Montaguefded0d12019-12-11 06:16:40 -060037 commit('authError');
Derick Montaguee080a1a2019-12-04 16:30:08 -060038 throw new Error(error);
39 });
40 },
41 logout({ commit }) {
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080042 api
Derick Montaguefded0d12019-12-11 06:16:40 -060043 .post('/logout', { data: [] })
44 .then(() => commit('logout'))
Yoshie Muranaka6ce1a072019-12-06 14:13:59 -080045 .catch(error => console.log(error));
Derick Montaguee080a1a2019-12-04 16:30:08 -060046 }
47 }
48};
49
50export default AuthenticationStore;