stjdydayou 4 gadi atpakaļ
vecāks
revīzija
e7043b7b57

+ 0 - 1
package.json

@@ -17,7 +17,6 @@
     "axios": "0.18.1",
     "core-js": "3.6.5",
     "element-ui": "2.13.2",
-    "js-cookie": "2.2.0",
     "normalize.css": "7.0.0",
     "nprogress": "0.2.0",
     "path-to-regexp": "2.4.0",

+ 24 - 0
src/api/oauth.js

@@ -0,0 +1,24 @@
+import request from '@/utils/request'
+
+export function getCaptcha() {
+    return request({
+        url: '/oauth/getCaptcha',
+        method: 'post'
+    })
+}
+
+export function login(data) {
+    return request({
+        url: '/oauth/login',
+        method: 'post',
+        data
+    })
+}
+
+
+export function getOauthInfo() {
+    return request({
+        url: '/oauth/getOauthInfo',
+        method: 'post'
+    })
+}

+ 3 - 3
src/permission.js

@@ -3,7 +3,6 @@ import store from './store'
 import { Message } from 'element-ui'
 import NProgress from 'nprogress' // progress bar
 import 'nprogress/nprogress.css' // progress bar style
-import { getToken } from '@/utils/auth' // get token from cookie
 import getPageTitle from '@/utils/get-page-title'
 
 NProgress.configure({ showSpinner: false }) // NProgress Configuration
@@ -18,9 +17,10 @@ router.beforeEach(async(to, from, next) => {
   document.title = getPageTitle(to.meta.title)
 
   // determine whether the user has logged in
-  const hasToken = getToken()
+  // const hasToken = getToken()
+  const accessToken = localStorage.getItem('x-access-token') || '';
 
-  if (hasToken) {
+  if (accessToken) {
     if (to.path === '/login') {
       // if is logged in, redirect to the home page
       next({ path: '/' })

+ 4 - 6
src/store/modules/app.js

@@ -1,8 +1,6 @@
-import Cookies from 'js-cookie'
-
 const state = {
   sidebar: {
-    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
+    opened: localStorage.getItem('sidebarStatus') ? !!+localStorage.getItem('sidebarStatus') : true,
     withoutAnimation: false
   },
   device: 'desktop'
@@ -13,13 +11,13 @@ const mutations = {
     state.sidebar.opened = !state.sidebar.opened
     state.sidebar.withoutAnimation = false
     if (state.sidebar.opened) {
-      Cookies.set('sidebarStatus', 1)
+      localStorage.setItem('sidebarStatus', 1)
     } else {
-      Cookies.set('sidebarStatus', 0)
+      localStorage.setItem('sidebarStatus', 0)
     }
   },
   CLOSE_SIDEBAR: (state, withoutAnimation) => {
-    Cookies.set('sidebarStatus', 0)
+    localStorage.setItem('sidebarStatus', 0)
     state.sidebar.opened = false
     state.sidebar.withoutAnimation = withoutAnimation
   },

+ 21 - 32
src/store/modules/user.js

@@ -1,12 +1,11 @@
-import { login, logout, getInfo } from '@/api/user'
-import { getToken, setToken, removeToken } from '@/utils/auth'
+import { login, getOauthInfo, loginOut } from '@/api/oauth'
 import { resetRouter } from '@/router'
 
 const getDefaultState = () => {
   return {
-    token: getToken(),
-    name: '',
-    avatar: ''
+    // name: '',
+    // avatar: '',
+    oauthInfo: undefined,
   }
 }
 
@@ -16,26 +15,22 @@ const mutations = {
   RESET_STATE: (state) => {
     Object.assign(state, getDefaultState())
   },
-  SET_TOKEN: (state, token) => {
-    state.token = token
-  },
-  SET_NAME: (state, name) => {
-    state.name = name
+
+  SET_OAUTH_INFO: (state, oauthInfo) => {
+    state.oauthInfo = oauthInfo
   },
-  SET_AVATAR: (state, avatar) => {
-    state.avatar = avatar
-  }
 }
 
 const actions = {
   // user login
-  login({ commit }, userInfo) {
-    const { username, password } = userInfo
+  login({ commit }, params) {
+    console.log(params)
+    const { captcha, username, password, token } = params
     return new Promise((resolve, reject) => {
-      login({ username: username.trim(), password: password }).then(response => {
-        const { data } = response
-        commit('SET_TOKEN', data.token)
-        setToken(data.token)
+      login({ loginAccount: username.trim(), loginPassword: password, captcha, token }).then(data => {
+        console.log(data);
+        commit('SET_OAUTH_INFO', data)
+        localStorage.setItem("x-access-token", data.accessToken || '');
         resolve()
       }).catch(error => {
         reject(error)
@@ -46,17 +41,12 @@ const actions = {
   // get user info
   getInfo({ commit, state }) {
     return new Promise((resolve, reject) => {
-      getInfo(state.token).then(response => {
-        const { data } = response
-
+      getOauthInfo().then(data => {
         if (!data) {
-          reject('Verification failed, please Login again.')
+          reject('获取用户信息失败,请重新登录')
         }
-
-        const { name, avatar } = data
-
-        commit('SET_NAME', name)
-        commit('SET_AVATAR', avatar)
+        commit('SET_OAUTH_INFO', data)
+        localStorage.setItem("x-access-token", data.accessToken || '');
         resolve(data)
       }).catch(error => {
         reject(error)
@@ -67,8 +57,8 @@ const actions = {
   // user logout
   logout({ commit, state }) {
     return new Promise((resolve, reject) => {
-      logout(state.token).then(() => {
-        removeToken() // must remove  token  first
+      loginOut().then(() => {
+        localStorage.removeItem("x-access-token");
         resetRouter()
         commit('RESET_STATE')
         resolve()
@@ -81,8 +71,7 @@ const actions = {
   // remove token
   resetToken({ commit }) {
     return new Promise(resolve => {
-      removeToken() // must remove  token  first
-      commit('RESET_STATE')
+      localStorage.removeItem("x-access-token");
       resolve()
     })
   }

+ 0 - 15
src/utils/auth.js

@@ -1,15 +0,0 @@
-import Cookies from 'js-cookie'
-
-const TokenKey = 'vue_admin_template_token'
-
-export function getToken() {
-  return Cookies.get(TokenKey)
-}
-
-export function setToken(token) {
-  return Cookies.set(TokenKey, token)
-}
-
-export function removeToken() {
-  return Cookies.remove(TokenKey)
-}

+ 24 - 44
src/utils/request.js

@@ -1,74 +1,54 @@
 import axios from 'axios'
-import { MessageBox, Message } from 'element-ui'
-import store from '@/store'
-import { getToken } from '@/utils/auth'
+import { Message } from 'element-ui'
 
 // create an axios instance
 const service = axios.create({
-  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
-  // withCredentials: true, // send cookies when cross-domain requests
-  timeout: 5000 // request timeout
+  baseURL: process.env.VUE_APP_BASE_API,
+  withCredentials: true,
+  timeout: 15000
 })
 
-// request interceptor
 service.interceptors.request.use(
   config => {
-    // do something before request is sent
-
-    if (store.getters.token) {
-      // let each request carry token
-      // ['X-Token'] is a custom headers key
-      // please modify it according to the actual situation
-      config.headers['X-Token'] = getToken()
+    const accessToken = localStorage.getItem('x-access-token') || '';
+    if (accessToken) {
+      config.headers['x-access-token'] = accessToken
     }
+    config.headers['Content-Type'] = 'application/json;charset=UTF-8';
+    config.headers['x-from-source'] = 'manager-admin-web';
     return config
   },
   error => {
-    // do something with request error
-    console.log(error) // for debug
+    console.log(error)
     return Promise.reject(error)
   }
 )
 
 // response interceptor
 service.interceptors.response.use(
-  /**
-   * If you want to get http information such as headers or status
-   * Please return  response => response
-  */
-
-  /**
-   * Determine the request status by custom code
-   * Here is just an example
-   * You can also judge the status by HTTP Status Code
-   */
   response => {
     const res = response.data
+    console.log(res);
 
     // if the custom code is not 20000, it is judged as an error.
-    if (res.code !== 20000) {
+    if (['SUCCESS', 'MESSAGE_SUCCESS'].indexOf(res.code) > -1) {
+      if (res.code === 'MESSAGE_SUCCESS') {
+        Message({
+          message: res.message,
+          type: 'success',
+          duration: 5 * 1000
+        })
+      }
+      return res.data || {};
+    } else if (res.code === 'NO_LOGIN') {
+      history.push('/oauth/login');
+    } else {
       Message({
-        message: res.message || 'Error',
+        message: res.message,
         type: 'error',
         duration: 5 * 1000
       })
-
-      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
-      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
-        // to re-login
-        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
-          confirmButtonText: 'Re-Login',
-          cancelButtonText: 'Cancel',
-          type: 'warning'
-        }).then(() => {
-          store.dispatch('user/resetToken').then(() => {
-            location.reload()
-          })
-        })
-      }
       return Promise.reject(new Error(res.message || 'Error'))
-    } else {
-      return res
     }
   },
   error => {

+ 1 - 10
src/utils/validate.js

@@ -8,13 +8,4 @@
  */
 export function isExternal(path) {
   return /^(https?:|mailto:|tel:)/.test(path)
-}
-
-/**
- * @param {string} str
- * @returns {Boolean}
- */
-export function validUsername(str) {
-  const valid_map = ['admin', 'editor']
-  return valid_map.indexOf(str.trim()) >= 0
-}
+}

+ 91 - 68
src/views/login/index.vue

@@ -1,130 +1,153 @@
 <template>
   <div class="login-container">
-    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
-
+    <el-form
+      ref="loginForm"
+      :model="loginForm"
+      class="login-form"
+      auto-complete="on"
+      label-position="left"
+    >
       <div class="title-container">
         <h3 class="title">湖南智企云开放平台</h3>
       </div>
 
       <el-form-item prop="username">
-        <span class="svg-container">
-          <svg-icon icon-class="user" />
-        </span>
+        <span class="svg-container el-icon-user-solid"></span>
+
         <el-input
           ref="username"
           v-model="loginForm.username"
-          placeholder="Username"
+          placeholder="请输入手机号/邮箱"
           name="username"
           type="text"
-          tabindex="1"
           auto-complete="on"
         />
       </el-form-item>
 
       <el-form-item prop="password">
-        <span class="svg-container">
-          <svg-icon icon-class="password" />
-        </span>
+        <span class="svg-container el-icon-lock"></span>
         <el-input
           :key="passwordType"
           ref="password"
           v-model="loginForm.password"
           :type="passwordType"
-          placeholder="Password"
+          placeholder="请输入登录密码"
           name="password"
-          tabindex="2"
           auto-complete="on"
           @keyup.enter.native="handleLogin"
         />
         <span class="show-pwd" @click="showPwd">
-          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
+          <svg-icon
+            :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
+          />
         </span>
       </el-form-item>
 
-      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">立即登录</el-button>
+      <el-form-item prop="password">
+        <span class="svg-container el-icon-warning"></span>
 
+        <el-input
+          ref="captcha"
+          v-model="loginForm.captcha"
+          placeholder="请输入验证码"
+          name="captcha"
+          type="text"
+        />
+        <img
+          :src="captcha"
+          class="show-pwd"
+          style="height: 38px"
+          @click="refreshCaptcha"
+        />
+      </el-form-item>
+
+      <el-button
+        :loading="loading"
+        type="primary"
+        style="width: 100%; margin-bottom: 30px"
+        @click.native.prevent="handleLogin"
+        >立即登录</el-button
+      >
     </el-form>
   </div>
 </template>
 
 <script>
-import { validUsername } from '@/utils/validate'
+import { getCaptcha } from "@/api/oauth";
 
 export default {
-  name: 'Login',
+  name: "Login",
   data() {
-    const validateUsername = (rule, value, callback) => {
-      if (!validUsername(value)) {
-        callback(new Error('Please enter the correct user name'))
-      } else {
-        callback()
-      }
-    }
-    const validatePassword = (rule, value, callback) => {
-      if (value.length < 6) {
-        callback(new Error('The password can not be less than 6 digits'))
-      } else {
-        callback()
-      }
-    }
     return {
       loginForm: {
-        username: 'admin',
-        password: '111111'
-      },
-      loginRules: {
-        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
-        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
+        username: "",
+        password: "",
+        captcha: "",
       },
       loading: false,
-      passwordType: 'password',
-      redirect: undefined
-    }
+      passwordType: "password",
+      redirect: undefined,
+      token: "",
+      captcha: "",
+    };
+  },
+  created() {
+    this.refreshCaptcha();
   },
   watch: {
     $route: {
-      handler: function(route) {
-        this.redirect = route.query && route.query.redirect
+      handler: function (route) {
+        this.redirect = route.query && route.query.redirect;
       },
-      immediate: true
-    }
+      immediate: true,
+    },
   },
   methods: {
+    refreshCaptcha() {
+      let _this = this;
+      getCaptcha().then((v) => {
+        console.log(v);
+        this.token = v.token;
+        this.captcha = v.captcha;
+      });
+    },
     showPwd() {
-      if (this.passwordType === 'password') {
-        this.passwordType = ''
+      if (this.passwordType === "password") {
+        this.passwordType = "";
       } else {
-        this.passwordType = 'password'
+        this.passwordType = "password";
       }
       this.$nextTick(() => {
-        this.$refs.password.focus()
-      })
+        this.$refs.password.focus();
+      });
     },
     handleLogin() {
-      this.$refs.loginForm.validate(valid => {
+      this.$refs.loginForm.validate((valid) => {
         if (valid) {
-          this.loading = true
-          this.$store.dispatch('user/login', this.loginForm).then(() => {
-            this.$router.push({ path: this.redirect || '/' })
-            this.loading = false
-          }).catch(() => {
-            this.loading = false
-          })
+          this.loading = true;
+          this.$store
+            .dispatch("user/login", { ...this.loginForm, token: this.token })
+            .then(() => {
+              this.$router.push({ path: this.redirect || "/" });
+              this.loading = false;
+            })
+            .catch(() => {
+              this.loading = false;
+            });
         } else {
-          console.log('error submit!!')
-          return false
+          console.log("error submit!!");
+          return false;
         }
-      })
-    }
-  }
-}
+      });
+    },
+  },
+};
 </script>
 
 <style lang="scss">
+$bg: #283443;
 
-$bg:#283443;
-
-$light_gray:#fff;
+$light_gray: #fff;
 $cursor: #fff;
 
 @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
@@ -167,9 +190,9 @@ $cursor: #fff;
 </style>
 
 <style lang="scss" scoped>
-$bg:#2d3a4b;
-$dark_gray:#889aa4;
-$light_gray:#eee;
+$bg: #2d3a4b;
+$dark_gray: #889aa4;
+$light_gray: #eee;
 
 .login-container {
   min-height: 100%;