@/utils/auth#setToken JavaScript Examples

The following examples show how to use @/utils/auth#setToken. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: auth.js    From react-antd-admin-template with MIT License 6 votes vote down vote up
login = (username, password) => (dispatch) => {
  return new Promise((resolve, reject) => {
    reqLogin({ username: username.trim(), password: password })
      .then((response) => {
        const { data } = response;
        if (data.status === 0) {
          const token = data.token;
          dispatch(setUserToken(token));
          setToken(token);
          resolve(data);
        } else {
          const msg = data.message;
          reject(msg);
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
}
Example #2
Source File: user.js    From vue3-element-admin with MIT License 6 votes vote down vote up
mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
    setRoles(roles)
  },
  SET_NAME: (state, name) => {
    state.name = name
    setName(name)
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
    setAvatar(avatar)
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  }
}
Example #3
Source File: user.js    From react-admin-template with MIT License 6 votes vote down vote up
A_login = (reqData) => (dispatch) => {
  return new Promise((resolve, reject) => {
    loginReq({ username: reqData.username.trim(), password: reqData.password })
      .then((res) => {
        const { jwtToken, msg } = res?.data
        if (res.code === 20000) {
          dispatch(A_USER_TOKEN(jwtToken))
          setToken(jwtToken)
          resolve(res?.data)
        } else {
          reject(msg)
        }
      })
      .catch((error) => {
        reject(error)
      })
  })
}
Example #4
Source File: user.js    From SystemManagement with MIT License 5 votes vote down vote up
actions = {
  // user login
  login({ dispatch, commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: username.trim(), password: password }).then(data => {
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(data => {
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        const { name, profile, permissions,roles } = data
        commit('SET_NAME', name)
        commit('SET_AVATAR', profile.avatar)
        commit('SET_PROFILE', profile)
        commit('SET_ROLES', roles)
        commit('SET_PERMISSIONS', permissions)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_NAME', '')
        commit('SET_AVATAR', '')
        commit('SET_PROFILE',{})
        commit('SET_ROLES',[])
        commit('SET_PERMISSIONS',[])
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },
  updateToken({commit},{token}){
    console.log('newToken',token)
    commit('SET_TOKEN', token)
    setToken(token)
  }
}
Example #5
Source File: user.js    From report with Apache License 2.0 5 votes vote down vote up
user = {
  state: {
    token: '', // 登录后的token
    accessUser: {} // 登录后的用户对象
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      setToken(token)
    },
    SET_ACCESSUSER: (state, accessUser) => {
      state.accessUser = accessUser
      setAccessUser(accessUser)
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const userName = userInfo.userName.trim()
      const password = userInfo.password.trim()
      const captchaVerification = userInfo.captchaVerification.trim()
      let data ={
        userName, password,captchaVerification
      }
      return new Promise((resolve, reject) => {
        login(data).then(response => {
          const repCode = response.repCode
          const repData = response.repData
          if (repCode === '0000') {
            commit('SET_TOKEN', repData.token)
            commit('SET_ACCESSUSER', repData.accessUser)
            resolve(response)
          } else {
            reject(response.repMsg)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ACCESSUSER', {})
          delToken()
          delShareToken()
          delAccessUser()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ACCESSUSER', {})
        delToken()
        delShareToken()
        delAccessUser()
        resolve()
      })
    }
  }
}
Example #6
Source File: user.js    From yshop-gin-vue with Apache License 2.0 5 votes vote down vote up
user = {
  state: {
    token: getToken(),
    user: {},
    roles: [],
    // 第一次加载菜单时用到
    loadMenus: false
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_LOAD_MENUS: (state, loadMenus) => {
      state.loadMenus = loadMenus
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const rememberMe = userInfo.rememberMe
      return new Promise((resolve, reject) => {
        login(userInfo.username, userInfo.password, userInfo.code, userInfo.uuid).then(res => {
          setToken(res.data.token, rememberMe)
          commit('SET_TOKEN', res.data.token)
          setUserInfo(res.data.user, commit)
          // 第一次加载菜单时用到, 具体见 src 目录下的 permission.js
          commit('SET_LOAD_MENUS', true)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          setUserInfo(res.data, commit)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout().then(res => {
          logOut(commit)
          resolve()
        }).catch(error => {
          logOut(commit)
          reject(error)
        })
      })
    },

    updateLoadMenus({ commit }) {
      return new Promise((resolve, reject) => {
        commit('SET_LOAD_MENUS', false)
      })
    }
  }
}
Example #7
Source File: manager.js    From EduAdmin with MIT License 5 votes vote down vote up
actions = {
  // user login
  login({ commit,dispatch }, userInfo) {
    const { tel, password } = userInfo
    return new Promise((resolve, reject) => {
      login('', '', { tel: tel.trim(), password: password }).then(response => {
        commit('SET_MANAGER', response.data)
        commit('SET_TOKEN', response.title)
        setToken(response.title) 
        resolve()
      }).catch(error => {
        console.log(error)
      })
    })
  },

  // // get user info
  getInfo({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      getInfo("", "", "").then(response => {
        commit('SET_MANAGER', response.data)
        commit('SET_TOKEN', response.title)
        setToken(response.title)
        dispatch('app/getPlatformList', null, { root: true })
        dispatch('app/getCollegeWithCourseKind', null, { root: true })
        // dispatch('app/getAllCourseKind', null, { root: true })
  
        resolve()
      }).catch(error => {
        console.log(error)
      })
    })
  },

  // user logout
  logout({ commit, dispatch }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      commit('SET_MANAGER', {})
      removeToken()
      resetRouter()
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_MANAGER', {})
      removeToken()
      resolve()
    })
  }
}
Example #8
Source File: user.js    From iota-payment-module with MIT License 5 votes vote down vote up
actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        commit('SET_TOKEN', response.token)
        setToken(response.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        if (!response) {
          reject('Verification failed, please Login again.')
        }

        const { id, avatar } = response.user

        commit('SET_NAME', id)
        commit('SET_AVATAR', avatar)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}
Example #9
Source File: axiosReq.js    From react-admin-template with MIT License 5 votes vote down vote up
// 响应拦截
service.interceptors.response.use(
  (res) => {
    if (reqConfig.afHLoading && loadingE) {
      loadingE.close()
    }
    // 如果是下载文件直接返回
    if (reqConfig.isDownLoadFile) {
      return res.data
    }
    const { msg, code, isNeedUpdateToken, updateToken } = res.data
    //更新token保持登录状态
    if (isNeedUpdateToken) {
      setToken(updateToken)
    }
    const successCode = '0,200,20000'
    if (successCode.indexOf(code) !== -1) {
      return res.data
    } else {
      //token失效或者有问题
      if (code === 403) {
        if (location.href.indexOf('/login') === -1) {
          Modal.confirm({
            title: 'token失效,请重新登录',
            content: '',
            okText: '是',
            okType: 'danger',
            cancelText: '否',
            onOk: () => {
              removeToken()
              location.reload()
            }
          })
        }
        return res.data
      }
      if (reqConfig.isAlertErrorMsg) {
        message.error(msg)
      }
      //返回错误信息
      //如果未catch 走unhandledrejection进行收集
      return Promise.reject(res.data)
    }
  },
  (err) => {
    if (loadingE) loadingE.close()
    message.error(err)
    //如果是跨域
    //Network Error,cross origin
    let errObj = {
      msg: err.toString(),
      reqUrl: reqConfig.baseURL + reqConfig.url,
      params: reqConfig.isParams ? reqConfig.params : reqConfig.data
    }
    return Promise.reject(JSON.stringify(errObj))
  }
)
Example #10
Source File: user.js    From fund_management-eastmoney with Apache License 2.0 4 votes vote down vote up
actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}
Example #11
Source File: user.js    From NCF with Apache License 2.0 4 votes vote down vote up
actions = {
  // user login
  login({commit}, userInfo) {
    const {username, password} = userInfo
    return new Promise((resolve, reject) => {
      login({username: username.trim(), password: password}).then(response => {
        if (response.success) {
          const {data} = response
          const {token} = data
          commit('SET_TOKEN', token)
          setToken(token)
          resolve(data)
        } else {
          Message({
            message: response.errorMessage || '登录失败!',
            type: 'error',
            duration: 5 * 1000
          })
          reject(response)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const {data} = response
        if (!data) {
          reject("验证失败,请重新登录。")
        }
        const {roleCodes, userName, menuTree, permissionCodes} = data
        // roles must be a non-empty array
        if (!roleCodes || roleCodes.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        const avatar = ''
        const introduction = 'i am admin'

        commit('SET_ROLES', roleCodes)
        setRole(roleCodes)
        commit('SET_NAME', userName)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        commit('SET_MENUTREE', menuTree)
        commit('SET_PERMISSIONCODES', permissionCodes)

        resolve(data)

      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({commit, state, dispatch}) {
    return new Promise((resolve, reject) => {
      console.log('退出登录--必须移除token和roles')
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken() // must remove  token  first
      removeRole()
      resetRouter()

      // 刷新页面
      // location.reload()

      dispatch('tagsView/delAllViews', null, {root: true})
      resolve()

      // 框架原本的逻辑
      // logout(state.token).then(() => {
      //   commit('SET_TOKEN', '')
      //   commit('SET_ROLES', [])
      //   removeToken()
      //   resetRouter()
      //
      //   // reset visited views and cached views
      //   // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      //   dispatch('tagsView/delAllViews', null, { root: true })
      //
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({commit, dispatch}, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roleCodes, menuTree } = await dispatch('getInfo')

    resetRouter()

    // 根据后端路由表生成可访问的路由
    const accessRoutes = await store.dispatch('permission/generateRoutes', {roleCodes, menuTree})

    // 动态添加可访问的路由
    console.log('动态添加可访问的路由',accessRoutes)
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, {root: true})
  }
}
Example #12
Source File: user.js    From ferry_web with GNU Lesser General Public License v3.0 4 votes vote down vote up
actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const { token } = response
        commit('SET_TOKEN', token)
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        if (!response || !response.data) {
          commit('SET_TOKEN', '')
          removeToken()
          resolve()
        }

        const { userId, roles, name, avatar, introduction, permissions } = response.data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_PERMISSIONS', permissions)
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_USERID', userId)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(response)
      }).catch(() => {
        commit('SET_TOKEN', '')
        setToken('')
        router.push({ path: '/' })
      })
    })
  },
  // 退出系统
  LogOut({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        removeToken()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 刷新token
  refreshToken({ commit, state }) {
    return new Promise((resolve, reject) => {
      refreshtoken({ token: state.token }).then(response => {
        const { token } = response
        commit('SET_TOKEN', token)
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }
}