You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.3 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. import Cookie from 'js-cookie'
  2. import ApiService from '@/services/api.service'
  3. import AuthService from '@/services/auth.service'
  4. export const state = () => ({
  5. token: null
  6. })
  7. export const mutations = {
  8. setToken(state, token) {
  9. state.token = token
  10. },
  11. clearToken(state) {
  12. state.token = null
  13. }
  14. }
  15. export const getters = {
  16. isAuthenticated(state) {
  17. return state.token != null
  18. }
  19. }
  20. export const actions = {
  21. authenticateUser({ commit }, authData) {
  22. return AuthService.postCredential(authData)
  23. .then((result) => {
  24. commit('setToken', result.data.token)
  25. localStorage.setItem('token', result.data.token)
  26. Cookie.set('jwt', result.data.token)
  27. ApiService.setHeader(result.data.token)
  28. })
  29. },
  30. initAuth({ commit, dispatch }, req) {
  31. let token
  32. if (req) {
  33. if (!req.headers.cookie) {
  34. return
  35. }
  36. const jwtCookie = req.headers.cookie
  37. .split(';')
  38. .find(c => c.trim().startsWith('jwt='))
  39. if (!jwtCookie) {
  40. return
  41. }
  42. token = jwtCookie.split('=')[1]
  43. } else {
  44. token = localStorage.getItem('token')
  45. }
  46. commit('setToken', token)
  47. ApiService.setHeader(token)
  48. },
  49. logout({ commit }) {
  50. commit('clearToken')
  51. Cookie.remove('jwt')
  52. if (process.client) {
  53. localStorage.removeItem('token')
  54. }
  55. }
  56. }