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.

90 lines
2.2 KiB

5 years ago
  1. import Cookie from 'js-cookie'
  2. export const state = () => ({
  3. token: null
  4. })
  5. export const mutations = {
  6. setToken(state, token) {
  7. state.token = token
  8. },
  9. clearToken(state) {
  10. state.token = null
  11. }
  12. }
  13. export const getters = {
  14. isAuthenticated(state) {
  15. return state.token != null
  16. }
  17. }
  18. export const actions = {
  19. authenticateUser({ commit }, authData) {
  20. let authUrl =
  21. 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=' +
  22. process.env.fbAPIKey
  23. if (!authData.isLogin) {
  24. authUrl =
  25. 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=' +
  26. process.env.fbAPIKey
  27. }
  28. return this.$axios
  29. .$post(authUrl, {
  30. email: authData.email,
  31. password: authData.password,
  32. returnSecureToken: true
  33. })
  34. .then((result) => {
  35. commit('setToken', result.idToken)
  36. localStorage.setItem('token', result.idToken)
  37. localStorage.setItem(
  38. 'tokenExpiration',
  39. new Date().getTime() + Number.parseInt(result.expiresIn) * 1000
  40. )
  41. Cookie.set('jwt', result.idToken)
  42. Cookie.set(
  43. 'expirationDate',
  44. new Date().getTime() + Number.parseInt(result.expiresIn) * 1000
  45. )
  46. })
  47. .catch(e => alert(e))
  48. },
  49. initAuth({ commit, dispatch }, req) {
  50. let token
  51. let expirationDate
  52. if (req) {
  53. if (!req.headers.cookie) {
  54. return
  55. }
  56. const jwtCookie = req.headers.cookie
  57. .split(';')
  58. .find(c => c.trim().startsWith('jwt='))
  59. if (!jwtCookie) {
  60. return
  61. }
  62. token = jwtCookie.split('=')[1]
  63. expirationDate = req.headers.cookie
  64. .split(';')
  65. .find(c => c.trim().startsWith('expirationDate='))
  66. .split('=')[1]
  67. } else {
  68. token = localStorage.getItem('token')
  69. expirationDate = localStorage.getItem('tokenExpiration')
  70. }
  71. if (new Date().getTime() > +expirationDate || !token) {
  72. dispatch('logout')
  73. return
  74. }
  75. commit('setToken', token)
  76. },
  77. logout({ commit }) {
  78. commit('clearToken')
  79. Cookie.remove('jwt')
  80. Cookie.remove('expirationDate')
  81. if (process.client) {
  82. localStorage.removeItem('token')
  83. localStorage.removeItem('tokenExpiration')
  84. }
  85. }
  86. }