login.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import Vue from 'vue';
  2. import Vuex from 'vuex';
  3. import _ from 'lodash';
  4. import { Notification } from 'element-ui';
  5. const jwt = require('jsonwebtoken');
  6. Vue.use(Vuex);
  7. const api = {
  8. interface: `/api/train/login`,
  9. user: id => `/api/train/user/update/${id}`,
  10. bind: `/api/train/user/bind`,
  11. userBind: `/api/train/user/userbind`,
  12. };
  13. const state = () => ({});
  14. const mutations = {};
  15. const actions = {
  16. async login({ commit }, { user, router, path = '/', needReturn = false, typeCheck = true }) {
  17. const res = await this.$axios.$post(`${api.interface}`, user);
  18. const setUser = (user, commit) => {
  19. localStorage.setItem('user', JSON.stringify(user));
  20. commit('setUser', user, { root: true });
  21. };
  22. if (res.errcode === 0) {
  23. let user = jwt.decode(res.data);
  24. if (!typeCheck) {
  25. setUser(user, commit);
  26. if (needReturn) return res;
  27. else router.push(path);
  28. }
  29. if (user.type == process.env.VUE_APP_USER_TYPE) {
  30. setUser(user, commit);
  31. Notification({
  32. title: '登录成功',
  33. message: `欢迎,${user.name}`,
  34. type: 'success',
  35. duration: 2000,
  36. });
  37. if (needReturn) return res;
  38. else router.push(path);
  39. } else {
  40. Notification({
  41. title: '请重新登陆',
  42. message: `原因:非当前端用户,需要重新登陆`,
  43. type: 'warning',
  44. });
  45. console.warn('非当前端用户,需要重新登陆');
  46. }
  47. } else {
  48. if (needReturn) return res;
  49. else {
  50. Notification({
  51. title: '登录失败',
  52. message: `失败原因:${res.errmsg}`,
  53. type: 'error',
  54. });
  55. }
  56. }
  57. },
  58. async update({ commit }, { id, ...info }) {
  59. let res = await this.$axios.$post(`${api.user(id)}`, info);
  60. return res;
  61. },
  62. async bind({ commit }, payload) {
  63. let res = await this.$axios.$post(`${api.bind}`, payload);
  64. return res;
  65. },
  66. async userBind({ commit }, payload) {
  67. let res = await this.$axios.$post(`${api.userBind}`, payload);
  68. return res;
  69. },
  70. };
  71. export default {
  72. namespaced: true,
  73. state,
  74. mutations,
  75. actions,
  76. };