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.

69 lines
1.5 KiB

5 years ago
5 years ago
5 years ago
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. username: null
  7. })
  8. export const mutations = {
  9. setToken(state, token) {
  10. state.token = token
  11. },
  12. clearToken(state) {
  13. state.token = null
  14. },
  15. setUsername(state, username) {
  16. state.username = username
  17. },
  18. clearUsername(state) {
  19. state.username = null
  20. }
  21. }
  22. export const getters = {
  23. isAuthenticated(state) {
  24. return state.token != null
  25. }
  26. }
  27. export const actions = {
  28. authenticateUser({ commit }, authData) {
  29. return AuthService.postCredential(authData)
  30. .then((result) => {
  31. commit('setToken', result.data.token)
  32. commit('setUsername', authData.username)
  33. localStorage.setItem('token', result.data.token)
  34. Cookie.set('jwt', result.data.token)
  35. ApiService.setHeader(result.data.token)
  36. })
  37. },
  38. initAuth({ commit, dispatch }, req) {
  39. let token
  40. if (req) {
  41. if (!req.headers.cookie) {
  42. return
  43. }
  44. const jwtCookie = req.headers.cookie
  45. .split(';')
  46. .find(c => c.trim().startsWith('jwt='))
  47. if (!jwtCookie) {
  48. return
  49. }
  50. token = jwtCookie.split('=')[1]
  51. } else {
  52. token = localStorage.getItem('token')
  53. }
  54. commit('setToken', token)
  55. ApiService.setHeader(token)
  56. },
  57. logout({ commit }) {
  58. commit('clearToken')
  59. commit('clearUsername')
  60. Cookie.remove('jwt')
  61. if (process.client) {
  62. localStorage.removeItem('token')
  63. }
  64. }
  65. }