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.

74 lines
1.7 KiB

5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 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. getUsername: () => () => {
  27. return localStorage.getItem('username')
  28. }
  29. }
  30. export const actions = {
  31. authenticateUser({ commit }, authData) {
  32. return AuthService.postCredential(authData)
  33. .then((result) => {
  34. commit('setToken', result.data.token)
  35. commit('setUsername', authData.username)
  36. localStorage.setItem('token', result.data.token)
  37. localStorage.setItem('username', authData.username)
  38. Cookie.set('jwt', result.data.token)
  39. ApiService.setHeader(result.data.token)
  40. })
  41. },
  42. initAuth({ commit, dispatch }, req) {
  43. let token
  44. if (req) {
  45. if (!req.headers.cookie) {
  46. return
  47. }
  48. const jwtCookie = req.headers.cookie
  49. .split(';')
  50. .find(c => c.trim().startsWith('jwt='))
  51. if (!jwtCookie) {
  52. return
  53. }
  54. token = jwtCookie.split('=')[1]
  55. } else {
  56. token = localStorage.getItem('token')
  57. }
  58. commit('setToken', token)
  59. ApiService.setHeader(token)
  60. },
  61. logout({ commit }) {
  62. commit('clearToken')
  63. commit('clearUsername')
  64. Cookie.remove('jwt')
  65. if (process.client) {
  66. localStorage.removeItem('token')
  67. localStorage.removeItem('username')
  68. }
  69. }
  70. }