auth.module.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { login, register } from "@/api/auth";
  2. import { LOGIN, LOGOUT, REGISTER } from "@/store/type/actions.type";
  3. import {
  4. SET_AUTH,
  5. SET_LOGIN_ERROR,
  6. REMOVE_AUTH,
  7. SET_REGISTER_ERROR,
  8. SET_PROFILE
  9. } from "@/store/type/mutations.type";
  10. import { getToken, destroyToken, saveToken } from "@/util/tokenStorage";
  11. const state = {
  12. isAuthenticated: !!getToken(),
  13. isLoginError: false,
  14. isRegisterError: false
  15. };
  16. const actions = {
  17. async [LOGIN](context, credentials) {
  18. try {
  19. const { token, user } = await login(credentials);
  20. context.commit(SET_PROFILE, user);
  21. context.commit(SET_AUTH, { token, profile: user });
  22. context.commit(SET_LOGIN_ERROR, false);
  23. } catch (e) {
  24. context.commit(SET_LOGIN_ERROR, true);
  25. }
  26. },
  27. [LOGOUT](context) {
  28. context.commit(REMOVE_AUTH);
  29. },
  30. async [REGISTER](context, credentials) {
  31. try {
  32. await register(credentials);
  33. } catch (e) {
  34. context.commit(SET_REGISTER_ERROR, true);
  35. }
  36. }
  37. };
  38. const mutations = {
  39. [SET_LOGIN_ERROR](state, error) {
  40. state.isLoginError = error;
  41. },
  42. [SET_REGISTER_ERROR](state, error) {
  43. state.isRegisterError = error;
  44. },
  45. [SET_AUTH](state, { token, profile }) {
  46. state.isAuthenticated = true;
  47. saveToken(token, profile);
  48. },
  49. [REMOVE_AUTH](state) {
  50. state.isAuthenticated = false;
  51. destroyToken();
  52. }
  53. };
  54. export default {
  55. state,
  56. actions,
  57. mutations
  58. };