瀏覽代碼

使用 token 进行用户认证, 不再使用 cookie

reghao 2 年之前
父節點
當前提交
e6c549731a

+ 1 - 1
src/api/video.js

@@ -129,7 +129,7 @@ export function cacheBiliVideo(bvId) {
   return post(videoApi.cacheBiliApi + '/' + bvId)
 }
 
-/***********************************************************************************************************************/
+// ********************************************************************************************************************
 // 获取推荐视频
 export function videoRecommend(nextId) {
   return get(videoApi.videoRecommendApi + '?nextId=' + nextId)

+ 31 - 83
src/assets/js/mixin.js

@@ -13,12 +13,11 @@ export const userMixin = {
       pubkeyR: '',
       captchaCode: '',
       userLogin: {
-        accountType: 1,
-        loginType: 1,
-        username: null,
-        password: null,
+        principal: null,
+        credential: null,
         captchaCode: null,
-        plat: 1
+        loginType: 1,
+        plat: 2
       },
       loginDialog: false,
       registerDialog: false,
@@ -41,14 +40,14 @@ export const userMixin = {
   },
   methods: {
     fetchPubkey() {
-      getPubkey().then(res => {
-        if (res.code === 0) {
-          this.pubkey = res.data.pubkey
-          this.pubkeyR = res.data.r
+      getPubkey().then(resp => {
+        if (resp.code === 0) {
+          this.pubkey = resp.data.pubkey
+          this.pubkeyR = resp.data.r
 
           this.getCaptcha()
         } else {
-          this.message = res.msg
+          this.message = resp.msg
           this.showMessage = true
         }
       }).catch(error => {
@@ -57,9 +56,9 @@ export const userMixin = {
       })
     },
     getCaptcha() {
-      getCaptchaCode().then(res => {
-        if (res.code === 0) {
-          this.captchaCode = res.data
+      getCaptchaCode().then(resp => {
+        if (resp.code === 0) {
+          this.captchaCode = resp.data
           this.dialogVisible = true
         } else {
           this.message = '获取图形验证码失败, 请重新刷新页面'
@@ -73,7 +72,7 @@ export const userMixin = {
       return encryptor.encrypt(pubkeyR + password)
     },
     fetchVerifyCode() {
-      if (this.userLogin.username === null || this.userLogin.username === '') {
+      if (this.userLogin.principal === null || this.userLogin.principal === '') {
         this.$message.success('请填写手机号')
         return
       }
@@ -92,13 +91,13 @@ export const userMixin = {
       }, 1000)
 
       const verifyCodeReq = {}
-      verifyCodeReq.receiver = this.userLogin.username
+      verifyCodeReq.receiver = this.userLogin.principal
       verifyCodeReq.notifyType = 2
-      getVerifyCode(verifyCodeReq).then(res => {
-        if (res.code === 0) {
+      getVerifyCode(verifyCodeReq).then(resp => {
+        if (resp.code === 0) {
           this.$message.success('验证码已发送, 请注意查收')
         } else {
-          this.$message.warning(res.msg)
+          this.$message.warning(resp.msg)
         }
       }).catch(error => {
         this.$message.error(error)
@@ -119,11 +118,11 @@ export const userMixin = {
     loginBtn() {
       // 显示加载效果
       this.isLoading = true
-      if (this.userLogin.username === '') {
+      if (this.userLogin.principal === '') {
         this.$message.warning('手机号不能为空')
         return
       }
-      if (this.userLogin.password === '' || this.userLogin.password === null) {
+      if (this.userLogin.credential === '' || this.userLogin.credential === null) {
         this.$message.warning('短信验证码不能为空')
         return
       }
@@ -132,12 +131,12 @@ export const userMixin = {
         return
       }
 
-      this.userLogin.password = this.encryptPassword(this.userLogin.password, this.pubkey, this.pubkeyR)
-      login(this.userLogin).then(res => {
-        if (res.code === 0) {
-          const resData = res.data
-          const userInfo = resData.userInfo
-          const userToken = resData.userToken
+      this.userLogin.credential = this.encryptPassword(this.userLogin.credential, this.pubkey, this.pubkeyR)
+      login(this.userLogin).then(resp => {
+        if (resp.code === 0) {
+          const respData = resp.data
+          const userInfo = respData.accountInfo
+          const userToken = respData.accountToken
           // 保存授权信息到本地缓存
           setUserToken(userToken)
           this.$store.commit('UPDATE_USER_INFO', userInfo)
@@ -147,7 +146,7 @@ export const userMixin = {
           this.$router.go(0)
         } else {
           // 登录失败
-          this.$message.warning(res.msg)
+          this.$message.warning(resp.msg)
         }
       }).catch(error => {
         // 登录请求错误
@@ -156,8 +155,8 @@ export const userMixin = {
         this.userLogin = {
           accountType: 1,
           loginType: 1,
-          username: null,
-          password: null,
+          principal: null,
+          credential: null,
           captchaCode: null,
           plat: 1
         }
@@ -169,15 +168,15 @@ export const userMixin = {
         cancelButtonText: '取消',
         type: 'warning'
       }).then(() => {
-        logout().then(res => {
-          if (res.code === 0) {
+        logout().then(resp => {
+          if (resp.code === 0) {
             Vue.$cookies.remove('token')
             this.$store.commit('USER_LOGOUT')
             removeAll()
           } else {
             this.$notify.error({
               title: '提示',
-              message: res.msg
+              message: resp.msg
             })
           }
         }).catch((e) => {
@@ -197,57 +196,6 @@ export const userMixin = {
           message: '已取消'
         })
       })
-    },
-    // 点击注册
-    register() {
-      if (this.password !== this.repassword) {
-        this.$message.warning('密码输入不一致')
-        return
-      }
-      // 先判断验证码是否正确
-      /* checkCode(this.rcode).then(res => {
-        if (res === 1) {
-          // 验证码正确,提交头像,在成功的回调中注册用户
-          this.$refs.uploadImg.submit()
-        } else if (res === -1) {
-          this.$message.warning('验证码已失效,请重新获取!')
-        } else {
-          this.$message.warning('验证码错误!')
-        }
-      })*/
-    },
-    // 选择图片时
-    imgChange(file) {
-      this.imageUrl = URL.createObjectURL(file.raw)
-    },
-    // 上传成功时
-    handleAvatarSuccess(res, file) {
-      this.avatarurl = res
-      // console.log(res);// 服务器返回的文件名称
-      // 注册
-      /* register(this.phone, this.password, this.nickname, this.avatarurl, this.phone).then(res => {
-        // console.log(res);
-        if (res === 1) {
-          this.$message.success('注册成功!')
-          this.dialogVisible2 = false
-          this.password = ''
-        } else if (res === -1) {
-          this.$message.warning('该手机号码已经被注册!如有疑问,请联系管理员!')
-        }
-      })*/
-    },
-    // 上传之前
-    beforeAvatarUpload(file) {
-      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
-      const isLt2M = file.size / 1024 / 1024 < 2
-
-      if (!isJPG) {
-        this.$message.error('上传头像图片格式错误!')
-      }
-      if (!isLt2M) {
-        this.$message.error('上传头像图片大小不能超过 2MB!')
-      }
-      return isJPG && isLt2M
     }
   }
 }

+ 3 - 3
src/components/VideoPlayer.vue

@@ -8,7 +8,7 @@ import SocketInstance from '@/utils/ws/socket-instance'
 
 import flvjs from 'flv.js'
 import DPlayer from 'dplayer'
-import Vue from "vue";
+import { getAccessToken } from '@/utils/auth'
 
 export default {
   name: 'VideoPlayer',
@@ -41,8 +41,8 @@ export default {
     getVideoUrl(videoId) {
       videoUrl(videoId).then(res => {
         if (res.code === 0) {
-          const userdata = Vue.$cookies.get('USERDATA')
-          if (userdata != null) {
+          const token = getAccessToken()
+          if (token != null) {
             SocketInstance.connect()
           }
 

+ 11 - 5
src/components/card/UserAvatarCard.vue

@@ -19,6 +19,9 @@
               <span v-html="'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'" />
               <span>粉丝 {{ userAvatar.follower }}</span>
             </el-row>
+            <el-row v-if="userAvatar.signature !== null">
+              <span>{{ userAvatar.signature }}</span>
+            </el-row>
           </el-col>
         </el-row>
       </div>
@@ -87,15 +90,15 @@ export default {
   methods: {
     followUser(userId) {
       if (this.followButton.text === '关注') {
-        followUser(userId).then(res => {
-          if (res.code === 0) {
+        followUser(userId).then(resp => {
+          if (resp.code === 0) {
             this.followButton.text = '已关注'
             this.followButton.icon = 'el-icon-check'
           }
         })
       } else {
-        unfollowUser(userId).then(res => {
-          if (res.code === 0) {
+        unfollowUser(userId).then(resp => {
+          if (resp.code === 0) {
             this.followButton.text = '关注'
             this.followButton.icon = 'el-icon-plus'
           }
@@ -103,7 +106,10 @@ export default {
       }
     },
     sendMessage(userId) {
-      console.log('发送消息给 ' + userId)
+      this.$notify.info({
+        message: '未实现',
+        duration: 3000
+      })
     }
   }
 }

+ 0 - 187
src/components/card/UserCard.vue

@@ -1,187 +0,0 @@
-<template>
-  <el-row style="padding-right: 5px; padding-left: 5px; padding-bottom: 5px">
-    <el-card>
-      <el-col>
-        <router-link target="_blank" :to="`/user/` + user.userId">
-          <el-avatar>
-            <el-image :src="user.avatarUrl" />
-          </el-avatar>
-        </router-link>
-      </el-col>
-      <el-col>
-        <el-row>
-          <span>{{ user.screenName }}</span>
-        </el-row>
-        <el-row>
-          <span>关注 22</span>
-          <span v-html="'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'" />
-          <span>粉丝 33</span>
-        </el-row>
-        <el-row>
-          <span v-if="user.signature !== undefined">{{ user.signature }}</span>
-          <span v-if="user.signature === undefined">无签名</span>
-        </el-row>
-        <el-row>
-          <el-button
-            type="danger"
-            size="mini"
-            :icon="followButton.icon"
-            @click="followUser(user.userId)"
-          >
-            <span>{{ followButton.text }}</span>
-          </el-button>
-        </el-row>
-      </el-col>
-    </el-card>
-  </el-row>
-</template>
-
-<script>
-import { getUserInfo, getUserFollowing, getUserFollower, checkRelation, followUser, unfollowUser } from '@/api/user'
-
-export default {
-  name: 'UserCard',
-  filters: {
-    ellipsis(value) {
-      if (!value) return ''
-      const max = 20
-      if (value.length > max) {
-        return value.slice(0, max) + '...'
-      }
-      return value
-    }
-  },
-  props: {
-    user: {
-      type: Object,
-      default: null
-    },
-    // 时间前的描述
-    dateTit: {
-      type: String,
-      default: ''
-    }
-  },
-  data() {
-    return {
-      followButton: {
-        icon: 'el-icon-plus',
-        text: '关注'
-      }
-    }
-  },
-  methods: {
-    followUser(userId) {
-      if (this.followButton.text === '关注') {
-        followUser(userId).then(res => {
-          if (res.code === 0) {
-            this.followButton.text = '已关注'
-            this.followButton.icon = 'el-icon-check'
-          }
-        })
-      } else {
-        unfollowUser(userId).then(res => {
-          if (res.code === 0) {
-            this.followButton.text = '关注'
-            this.followButton.icon = 'el-icon-plus'
-          }
-        })
-      }
-    },
-    sendMessage(userId) {
-      console.log('发送消息')
-    }
-  }
-}
-</script>
-
-<style scoped>
-.time {
-  font-size: 15px;
-  color: #999;
-}
-
-.bottom {
-  margin-top: 13px;
-  line-height: 12px;
-}
-
-.tit {
-  font-weight: 700;
-  font-size: 18px;
-
-  height: 50px;
-  overflow: hidden;
-  text-overflow: ellipsis;
-  display: -webkit-box;
-  -webkit-line-clamp: 2; /*行数*/
-  -webkit-box-orient: vertical;
-}
-
-.num {
-  position: relative;
-  font-size: 15px;
-  padding-top: 9px;
-}
-
-/*处于手机屏幕时*/
-@media screen and (max-width: 768px) {
-  .tit {
-    font-weight: 600;
-    font-size: 12px;
-    height: 32px;
-  }
-  .time {
-    font-size: 10px;
-    color: #999;
-  }
-  .num {
-    font-size: 9px;
-    padding-top: 3px;
-  }
-  .bottom {
-    margin-top: 2px;
-    line-height: 7px;
-  }
-  .coverImg {
-    height: 120px !important;
-  }
-}
-
-.coverImg {
-  width: 100%;
-  height: 100%;
-  display: block;
-}
-
-.clearfix:before,
-.clearfix:after {
-  display: table;
-  content: "";
-}
-
-.clearfix:after {
-  clear: both;
-}
-
-.card {
-  margin-bottom: 20px;
-  transition: all 0.6s; /*所有属性变化在0.6秒内执行动画*/
-}
-
-/*.card:hover {
-  !*鼠标放上之后元素变成1.06倍大小*!
-  transform: scale(1.06);
-}*/
-.imgs {
-  position: relative;
-}
-.play-icon {
-  position: absolute;
-  /*top: -15px;*/
-  right: 2%;
-  bottom: 5px;
-  z-index: 7;
-  width: 40px;
-}
-</style>

+ 8 - 9
src/components/layout/NavBar.vue

@@ -138,7 +138,7 @@
       <el-form ref="form" :model="userLogin">
         <el-form-item label="帐号">
           <el-input
-            v-model="userLogin.username"
+            v-model="userLogin.principal"
             placeholder="请输入手机号或邮箱"
             style="width: 70%; padding-right: 2px"
             clearable
@@ -146,7 +146,7 @@
         </el-form-item>
         <el-form-item label="密码">
           <el-input
-            v-model="userLogin.password"
+            v-model="userLogin.credential"
             placeholder="请输入验证码"
             style="width: 45%; padding-right: 2px"
           />
@@ -178,6 +178,7 @@ import Vue from 'vue'
 import { userMixin } from 'assets/js/mixin'
 import { getMyInfo } from '@/api/user'
 import { keywordSuggest } from '@/api/search'
+import {getUserInfo} from "@/utils/auth";
 
 export default {
   name: 'NavBar',
@@ -194,13 +195,11 @@ export default {
     }
   },
   created() {
-    const userdata = Vue.$cookies.get('USERDATA')
-    if (userdata !== null) {
-      getMyInfo().then(res => {
-        if (res.code === 0) {
-          this.user = res.data
-        }
-      })
+    /* const userdata = Vue.$cookies.get('USERDATA')
+    const userId = userdata.split(':')[0]*/
+    const userInfo = getUserInfo()
+    if (userInfo !== null) {
+      this.user = userInfo
     }
   },
   methods: {

+ 0 - 3
src/main.js

@@ -51,9 +51,6 @@ Vue.use(VueClipboards)
 
 Vue.config.productionTip = false // 阻止控制台打印生产模式下的消息
 Vue.prototype.baseURL = '//api.reghao.cn'
-// this.$user 引用登录的用户
-// Vue.prototype.$user = Vue.$cookies.get('user')
-
 new Vue({
   render: h => h(App),
   router,

+ 31 - 11
src/utils/request.js

@@ -1,8 +1,7 @@
 import axios from 'axios'
 import store from '@/store'
-import router from '@/router'
 import Vue from 'vue'
-import {removeAll} from '@/utils/auth'
+import {getAccessToken, removeAll} from '@/utils/auth'
 
 const instance = axios.create({
   // 域名
@@ -23,8 +22,9 @@ const loading = null
 
 // 请求拦截器
 instance.interceptors.request.use(config => {
-  const token1 = store.getters.token
-  if (token1) {
+  // const token = store.getters.token
+  const token = getAccessToken()
+  if (token) {
     // 在请求的 Authorization 首部添加 token
     config.headers.Authorization = 'Bearer ' + token
   }
@@ -47,7 +47,7 @@ instance.interceptors.response.use(
       return Promise.reject(response)
     }
   },
-    error => {
+  error => {
     if (loading) {
       loading.close()
     }
@@ -56,25 +56,45 @@ instance.interceptors.response.use(
       switch (error.response.status) {
         case 401:
           // 返回 401 清除token信息并跳转到登陆页面
-          console.log('401 错误...')
+          this.$notify.error({
+            message: '401 错误',
+            type: 'error',
+            duration: 3000
+          })
+
           Vue.$cookies.remove('token')
           store.commit('USER_LOGOUT')
           store.commit('delToken')
           removeAll()
           break
         case 404:
-          console.error('网络请求不存在')
+          this.$notify.error({
+            message: '网络请求不存在',
+            type: 'error',
+            duration: 3000
+          })
           break
         default:
-          console.error(error.response.data.message)
+          this.$notify.error({
+            message: error.response.data.message,
+            type: 'error',
+            duration: 3000
+          })
       }
     } else {
       // 请求超时或者网络有问题
       if (error.message.includes('timeout')) {
-        console.error('请求超时!请检查网络是否正常')
+        this.$notify.error({
+          message: '请求超时!请检查网络是否正常',
+          type: 'error',
+          duration: 3000
+        })
       } else {
-        console.error(error.message)
-        console.error('请求失败,请检查服务器是否已启动')
+        this.$notify.error({
+          message: error.message,
+          type: 'error',
+          duration: 3000
+        })
       }
     }
     return Promise.reject(error)

+ 2 - 3
src/utils/ws/socket-instance.js

@@ -1,6 +1,6 @@
 import WsSocket from '@/utils/ws/ws-socket'
 import { Notification } from 'element-ui'
-import Vue from 'vue'
+import { getAccessToken } from '@/utils/auth'
 
 /**
  * SocketInstance 连接实例
@@ -19,8 +19,7 @@ class SocketInstance {
   constructor() {
     this.socket = new WsSocket(
       () => {
-        const userdata = Vue.$cookies.get('USERDATA')
-        const token = userdata.split(':')[0]
+        const token = getAccessToken()
         var url = 'wss://api.reghao.cn/ws/progress?token=' + token
         return url
       },

+ 15 - 15
src/views/home/AudioPage.vue

@@ -12,31 +12,31 @@
             <el-row>
               <audio-player
                 ref="audioPlayer"
-                :isLoop="false"
+                :is-loop="false"
                 :show-prev-button="false"
                 :show-next-button="false"
                 :show-playback-rate="false"
                 :audio-list="audioList.map(elm => elm.url)"
                 :before-play="handleBeforePlay"
+                theme-color="#87CEFA"
                 @playing="onPlaying"
                 @on-progress-move="onProgressMove"
                 @ended="onEnd"
-                theme-color="#87CEFA"
               />
             </el-row>
-            <el-divider v-if="audioInfo.description !== undefined && audioInfo.description !== null"/>
+            <el-divider v-if="audioInfo.description !== undefined && audioInfo.description !== null" />
             <el-row>
               <span v-html="audioInfo.description" />
             </el-row>
-            <el-divider/>
+            <el-divider />
             <el-row>
               发布于 <span v-html="audioInfo.publishAt" />
             </el-row>
-            <el-divider/>
+            <el-divider />
             <el-row>
               <span>
                 <span>
-                  <i :class=collectedIcon @click="collectItem"/>
+                  <i :class="collectedIcon" @click="collectItem" />
                 </span>
               </span>
             </el-row>
@@ -45,17 +45,17 @@
       </el-row>
     </el-col>
     <el-col :md="6">
-      <user-avatar-card :userAvatar="user" />
+      <user-avatar-card :user-avatar="user" />
     </el-col>
   </el-row>
 </template>
 
 <script>
 import UserAvatarCard from '@/components/card/UserAvatarCard'
-import { getAudioInfo} from "@/api/audio";
-import {getUserInfo} from "@/api/user";
-import SocketInstance from "@/utils/ws/socket-instance";
-import Vue from "vue";
+import { getAudioInfo } from '@/api/audio'
+import { getUserInfo } from '@/api/user'
+import SocketInstance from '@/utils/ws/socket-instance'
+import { getAccessToken } from '@/utils/auth'
 
 export default {
   name: 'AudioPage',
@@ -89,8 +89,8 @@ export default {
           { name: this.audioInfo.title, url: this.audioInfo.audioUrl }
         ]
 
-        const userdata = Vue.$cookies.get('USERDATA')
-        if (userdata != null) {
+        const token = getAccessToken()
+        if (token != null) {
           SocketInstance.connect()
         }
         document.title = '音频 - ' + this.audioInfo.title
@@ -108,7 +108,7 @@ export default {
     // 播放前做的事
     handleBeforePlay(next) {
       // 这里可以做一些事情...
-      //this.audioList[this.$refs.audioPlayer.currentPlayIndex].name
+      // this.audioList[this.$refs.audioPlayer.currentPlayIndex].name
       this.$refs.audioPlayer.$refs.audio.currentTime = this.audioInfo.currentTime
       // 开始播放
       next()
@@ -119,7 +119,7 @@ export default {
         this.$refs.audioPlayer.play()
         this.title = this.audioList[
           this.$refs.audioPlayer.currentPlayIndex
-          ].name
+        ].name
       })
     },
     onPlaying() {

+ 5 - 15
src/views/home/Timeline.vue

@@ -65,23 +65,13 @@ export default {
     }
   },
   created() {
-    const userdata = Vue.$cookies.get('USERDATA')
-    if (userdata == null) {
+    const userInfo = getUserInfo()
+    if (userInfo === null) {
       return null
     }
-    const userId = userdata.split(':')[0]
-    getUserInfo(userId).then(resp => {
-      if (resp.code === 0) {
-        this.userInfo = resp.data
-        document.title = this.userInfo.screenName + '的时间线'
-      }
-    })
-    /* getMyInfo().then(resp => {
-      if (resp.code === 0) {
-        this.userInfo = resp.data
-        document.title = this.userInfo.screenName + '的时间线'
-      }
-    })*/
+
+    this.userInfo = userInfo
+    document.title = userInfo.screenName + '的时间线'
     this.videoTimelineWrapper(this.nextId)
   },
   mounted() {

+ 3 - 3
src/views/home/VideoList.vue

@@ -235,7 +235,7 @@ import { videoUrl, similarVideo, videoInfo, videoErrorReport, downloadVideo, cac
 import { collectItem } from '@/api/collect'
 import { getUserInfo } from '@/api/user'
 import { submitAccessCode } from '@/api/content'
-import Vue from "vue";
+import { getAccessToken } from '@/utils/auth'
 
 export default {
   name: 'VideoList',
@@ -508,8 +508,8 @@ export default {
     getVideoUrl(videoId) {
       videoUrl(videoId).then(res => {
         if (res.code === 0) {
-          const userdata = Vue.$cookies.get('USERDATA')
-          if (userdata != null) {
+          const token = getAccessToken()
+          if (token != null) {
             SocketInstance.connect()
           }
 

+ 4 - 9
src/views/user/Home.vue

@@ -1,8 +1,8 @@
 <template>
   <div>
     <el-row class="movie-list">
-      <el-col :md="24">
-        <el-card :if="!user" :body-style="{ padding: '0px' }" class="card">
+      <el-col v-if="user" :md="24">
+        <el-card :body-style="{ padding: '0px' }" class="card">
           <div slot="header" class="clearfix">
             <el-row>
               <el-col :md="1">
@@ -130,7 +130,6 @@
 </template>
 
 <script>
-import UserCard from '@/components/card/UserCard'
 import StatusCard from '@/components/card/StatusCard'
 import VideoCard from '@/components/card/VideoCard'
 import AudioCard from '@/components/card/AudioCard'
@@ -146,7 +145,7 @@ import { userStatus } from '@/api/status'
 
 export default {
   name: 'Home',
-  components: { UserCard, StatusCard, VideoCard, ImageAlbumCard, AudioCard, ArticleCard },
+  components: { StatusCard, VideoCard, ImageAlbumCard, AudioCard, ArticleCard },
   data() {
     return {
       // 屏幕宽度, 为了控制分页条的大小
@@ -330,11 +329,7 @@ export default {
       userStatus(userId, pageNumber).then(resp => {
         if (resp.code === 0) {
           this.dataList = resp.data.list
-          if (this.dataList.length === 0) {
-            this.showEmpty = true
-          } else {
-            this.showEmpty = false
-          }
+          this.showEmpty = this.dataList.length === 0
         }
       })
     }