Skip to content

Instantly share code, notes, and snippets.

@HyunGyu-Lee
Created November 29, 2019 01:29
Show Gist options
  • Save HyunGyu-Lee/ab9dc97c5d97b7150d7ba2510b12d434 to your computer and use it in GitHub Desktop.
Save HyunGyu-Lee/ab9dc97c5d97b7150d7ba2510b12d434 to your computer and use it in GitHub Desktop.
Vue 토큰 저장
import axios from 'axios'
import store from '@/plugins/store'
axios.interceptors.request.use((config) => {
let accessToken = store.getters.accessToken;
if (accessToken) {
config.headers.Authorization = `Bearer ${accessToken}`;
}
return config;
});
export default {
login(loginId, loginPassword) {
return axios.post('/api/auth/signin', {loginId, loginPassword})
}
}
import Vue from 'vue'
import Vuex from 'vuex'
import Auth from '@/api/auth'
import Const from '@/common/constants'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)
export default new Vuex.Store({
plugins: [createPersistedState()],
state: {
user: {},
accessToken: '',
authenticated: false
},
mutations: {
[Const.MUTATIONS.USER_LOGIN] : (state, signinInfo) => {
state.user = signinInfo.user;
state.accessToken = signinInfo.authorizedToken;
state.authenticated = true;
},
[Const.MUTATIONS.USER_LOGOUT] : (state) => {
state.user = {};
state.accessToken = '';
state.authenticated = false;
}
},
actions: {
LOGIN({ commit }, { id, password }) {
return new Promise(function (resolve, reject) {
Auth.login(id, password).then(response => {
commit(Const.MUTATIONS.USER_LOGIN, response.data.body);
resolve();
}).catch(e => {
reject(e);
});
});
},
LOGOUT({ commit }) {
commit(Const.MUTATIONS.USER_LOGOUT)
}
},
getters: {
accessToken(state) {
return state.accessToken;
},
isAuthorized(state) {
return state.authenticated;
},
loginUser(state) {
return state.user;
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment