Преглед изворни кода

fix router auth and add filter username

Starink пре 6 година
родитељ
комит
6e400549ab

+ 17 - 0
components/ColumnCard.vue

@@ -44,6 +44,23 @@
     },
     methods: {
       checkColumnDetail(){
+        this.$api.$post('/user/getInfo', {
+          uid: this.$store.state.user.id
+        }).then((res) =>
+          {
+            if(res.code === 0){
+              let data = res.data;
+            }else{
+              this.$message({
+                showClose: true,
+                message: res.message,
+                type: 'error'
+              });
+            }
+          }
+        ).catch((e)=>{
+          console.log("e", e);
+        });
         this.$message({
           showClose: true,
           message: '即将上线,敬请期待'

+ 4 - 2
components/Navi.vue

@@ -84,9 +84,11 @@
       logout(){
         this.$store.commit("saveToken", null);
         this.$store.commit("saveUser", {});
-        localStorage.removeItem('token');
-        localStorage.removeItem('user');
+        this.$cookies.remove('token', {maxAge: 24*60*60});
+        this.$cookies.remove('user', {maxAge: 24*60*60});
+        this.$cookies.removeAll();
         this.refresh();
+        this.$router.push("/");
       },
       refresh(){
         this.isLogin = !!this.$store.state.token;

+ 20 - 4
layouts/person.vue

@@ -3,8 +3,9 @@
     <navi></navi>
     <div class="person-container">
       <el-menu
-        default-active="1"
-        class="el-menu-vertical-demo side-bar">
+        :default-active="activeIndex"
+        class="el-menu-vertical-demo side-bar"
+        @select="handleSelect">
         <el-menu-item index="1">
           <i class="el-icon-user"></i>
           <span slot="title">基本信息</span>
@@ -13,7 +14,7 @@
           <i class="el-icon-document"></i>
           <span slot="title">身份认证</span>
         </el-menu-item>
-        <el-menu-item index="3">
+        <el-menu-item index="3" disabled>
           <i class="el-icon-data-line"></i>
           <span slot="title">学习数据</span>
         </el-menu-item>
@@ -35,7 +36,22 @@
   import Foot from "~/components/Foot";
 
   export default{
-    components: {Navi, Foot}
+    components: {Navi, Foot},
+    data(){
+      return{
+        activeIndex: "1"
+      }
+    },
+    methods: {
+      handleSelect(index){
+        const routes=['/person/info', '/person/identification', '/person/analysis', '/person/orders'];
+        this.$router.push(routes[index-1]);
+      }
+    },
+    mounted(){
+      const routes=['/person/info', '/person/identification', '/person/analysis', '/person/orders'];
+      this.activeIndex = (1 + routes.indexOf(this.$router.app._route.path)) + "";
+    }
   }
 </script>
 

+ 1 - 1
middleware/auth.js

@@ -41,7 +41,7 @@ export default function (context) {
     }
   }
 
-  else if (!token && mainPath !== "/" && mainPath !=="/login" && mainPath !== "/register" && mainPath !=="/error" && mainPath !== "/api/receiveIDToken") {
+  else if (!token && mainPath !== "/" && mainPath !=="/login" && mainPath !== "/register" && mainPath !=="/error" && mainPath !=="/unauthorized" && mainPath !== "/api/receiveIDToken") {
 
     // console.log("session:", req.session);
     app.$cookies.set('origin_path', path);

+ 3 - 0
pages/error.vue

@@ -1,5 +1,8 @@
 <template>
+  <div class="container">
     <h1>请求非法</h1>
+    <nuxt-link to="/">首 页</nuxt-link>
+  </div>
 </template>
 
 <script>

+ 2 - 1
pages/person/identification.vue

@@ -4,7 +4,8 @@
 
 <script>
   export default {
-    name: "identification"
+    name: "identification",
+    layout: 'person',
   };
 </script>
 

+ 62 - 9
pages/person/info.vue

@@ -7,23 +7,36 @@
       <div class="main-card__info-item">
         <div class="main-card__info-item__head">
           <p class="main-card__info-item__name">昵称</p>
-          <a class="main-card__info-item__modify">修改</a>
+          <a class="main-card__info-item__modify" @click="nameDialogVisible = true">修改</a>
         </div>
         <div class="main-card__info-item__value">{{name}}</div>
+
+        <el-dialog
+          title="修改昵称"
+          :visible.sync="nameDialogVisible"
+          width="30%">
+          <el-input ref="name" v-model="newName" placeholder="请输入昵称, 长度为1-10个字符" maxlength="10" class="login-card__item" oninput="value=value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5\ ]/g,'')" autofocus></el-input>
+          <span slot="footer" class="dialog-footer">
+            <el-button @click="nameDialogVisible = false">取 消</el-button>
+            <el-button type="primary" @click="saveName">确 定</el-button>
+          </span>
+        </el-dialog>
+
       </div>
       <div class="main-card__info-item">
         <div class="main-card__info-item__head">
           <p class="main-card__info-item__name">邮箱</p>
-          <a class="main-card__info-item__modify">修改</a>
+          <a class="main-card__info-item__modify" @click="emailDialogVisible = true">修改</a>
         </div>
         <div class="main-card__info-item__value">{{email}}</div>
-      </div><div class="main-card__info-item">
-      <div class="main-card__info-item__head">
-        <p class="main-card__info-item__name">个性签名</p>
-        <a class="main-card__info-item__modify">修改</a>
       </div>
-      <div class="main-card__info-item__value">{{signature}}</div>
-    </div>
+      <div class="main-card__info-item">
+        <div class="main-card__info-item__head">
+          <p class="main-card__info-item__name">个性签名</p>
+          <a class="main-card__info-item__modify" @click="signatueDialogVisible = true">修改</a>
+        </div>
+        <div class="main-card__info-item__value">{{signature}}</div>
+      </div>
     </div>
   </div>
 </template>
@@ -35,8 +48,14 @@
     data(){
       return {
         name: '',
+        email: '',
         signature: '',
-        email: ''
+        newName: '',
+        newEmail: '',
+        newSignature: '',
+        nameDialogVisible: false,
+        emailDialogVisible: false,
+        signatureDialogVisible: false
       }
     },
     mounted(){
@@ -64,6 +83,40 @@
         ).catch((e)=>{
           console.log(e);
         });
+      },
+      saveName(){
+        this.$api.$post('/user/saveName', {
+          name: this.newName
+        }).then((res) =>
+          {
+            if(res.code === 0){
+              let user = this.$store.state.user;
+              user.name = this.newName;
+              this.$store.commit("saveUser", user);
+              this.name = this.newName;
+              this.nameDialogVisible = false;
+              this.$message({
+                showClose: true,
+                message: "修改成功",
+                type: 'success'
+              });
+            }else{
+              this.$message({
+                showClose: true,
+                message: res.message,
+                type: 'error'
+              });
+            }
+          }
+        ).catch((e)=>{
+          console.log(e);
+        });
+      },
+      saveEmail(){
+
+      },
+      saveSignature(){
+
       }
     }
     // asyncData ({ app, params, error, store }) {

+ 1 - 1
pages/register.vue

@@ -2,7 +2,7 @@
   <div class="page-container login-container">
     <el-card class="login-card">
       <h2 class="login-card__title login-card__item">注 册</h2>
-      <el-input ref="name" v-model="name" placeholder="请输入昵称, 长度为1-10个字符" maxlength="10" class="login-card__item" autofocus></el-input>
+      <el-input ref="name" v-model="name" placeholder="请输入昵称, 长度为1-10个字符" maxlength="10" class="login-card__item" oninput="value=value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5\ ]/g,'')" autofocus></el-input>
       <el-input ref="password" v-model="password" type="password" placeholder="请输入密码, 长度为6-20个字符" maxlength="20" class="login-card__item"></el-input>
       <el-input ref="passwordConfirm" v-model="passwordConfirm" type="password" placeholder="请再次输入密码" maxlength="20" class="login-card__item"></el-input>
       <el-input ref="email" v-model="email" placeholder="请输入邮箱" maxlength="320" class="login-card__item" autofocus></el-input>

+ 13 - 0
pages/unauthorized.vue

@@ -0,0 +1,13 @@
+<template>
+  <div class="container">
+    <h1>未授权,请先登录</h1>
+    <nuxt-link to="/">首 页</nuxt-link>
+  </div>
+</template>
+
+<script>
+  export default {
+    name: 'unauthorized',
+    layout: 'blank' // 你可以为错误页面指定自定义的布局
+  }
+</script>

+ 52 - 19
plugins/api.js

@@ -1,38 +1,71 @@
 
 export default function ({ $axios, redirect, app, store }, inject) {
-  $axios.onRequest(config => {
+  // $axios.onRequest(config => {
+  //   if(store.state.token){
+  //     config.headers['Authorization'] = 'Bearer ' + store.state.token;
+  //   }
+  //   return config;
+  // });
+  //
+  // $axios.setHeader('Content-Type', 'application/json');
+  //
+  // $axios.onResponse(response =>{
+  //   console.log("response", response);
+  //   if(response.status === 401){
+  //     app.$cookies.removeAll();
+  //     store.commit('saveToken', null);
+  //     store.commit('saveUser', {});
+  //     this.$message({
+  //       showClose: true,
+  //       message: '未授权,请先登录',
+  //       type: 'warning'
+  //     });
+  //   }
+  //
+  // });
+
+  // Create a custom axios instance
+  const api = $axios.create({
+    // headers: {
+    //   common: {
+    //     Accept: 'text/plain, */*'
+    //   }
+    // },
+    baseURL: '/api',
+    timeout: 10000,
+    withCredentials: true
+  });
+
+  api.onRequest(config => {
     if(store.state.token){
-      config.headers.common['Authorization'] = 'Bearer ' + store.state.token;
+      config.headers['authorization'] = 'Bearer ' + store.state.token;
+    }else{
+      delete config.headers['authorization'];
     }
+
     return config;
   });
 
-  $axios.setHeader('Content-Type', 'application/json');
+  api.setHeader('Content-Type', 'application/json');
 
-  $axios.onResponse(response =>{
+  api.onResponse(response =>{
     if(response.status === 401){
       app.$cookies.removeAll();
       store.commit('saveToken', null);
       store.commit('saveUser', {});
-      this.$message({
-        showClose: true,
-        message: '未授权,请先登录',
-        type: 'warning'
-      });
+      redirect('/unauthorized');
     }
 
   });
 
-  // Create a custom axios instance
-  const api = $axios.create({
-    // headers: {
-    //   common: {
-    //     Accept: 'text/plain, */*'
-    //   }
-    // },
-    baseURL: '/api',
-    timeout: 10000,
-    withCredentials: true
+  api.onError(error => {
+    if(error.response.status === 401) {
+      app.$cookies.removeAll();
+      store.commit('saveToken', null);
+      store.commit('saveUser', {});
+      console.log('here')
+      redirect('/unauthorized');
+    }
   });
 
   // Set baseURL to something different

+ 82 - 8
server/index.js

@@ -7,6 +7,7 @@ const bodyparser = require('koa-bodyparser');
 const logger = require('koa-logger');
 const cors = require('koa2-cors');
 const jwt = require('koa-jwt');
+const jsonwebtoken = require('jsonwebtoken')
 const helmet = require('koa-helmet');
 const mount = require('koa-mount');
 const set = require('lodash/set');
@@ -76,12 +77,6 @@ app.use(async (ctx, next) => {
     console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
 });
 
-// app.use(jwt({
-//     secret: secret.sign
-// }).unless({
-//     path: [/\/api\/user\/login/, /\/api\/user\/register/]
-// }));
-
 // Custom 401 handling if you don't want to expose koa-jwt errors to users
 app.use(function(ctx, next){
     return next().catch((err) => {
@@ -94,8 +89,6 @@ app.use(function(ctx, next){
     });
 });
 //
-// routes
-app.use(router().routes(), router().allowedMethods());
 
 // error-handling
 app.on('error', (err, ctx) => {
@@ -164,6 +157,17 @@ async function start () {
     await builder.build()
   }
 
+  app.use(jwt({ secret: 'seec-portal' }).unless({
+    // 设置login、register接口,可以不需要认证访问
+    path: [
+      /\/api\/user\/login/, /\/api\/user\/register/, /\/api\/interaction/, /\/api\/receiveIDToken/, /\/api\/authenticate/,
+      /^((?!\/api).)*$/   // 设置除了私有接口外的其它资源,可以不需要认证访问
+    ]
+  }));
+
+  // routes
+  app.use(router().routes(), router().allowedMethods());
+
   app.use((ctx) => {
     ctx.req.session = ctx.session;
     ctx.status = 200
@@ -172,6 +176,76 @@ async function start () {
     nuxt.render(ctx.req, ctx.res)
   })
 
+  // app.use((ctx, next) => {
+  //   console.log("ctx.url", ctx.url);
+  //   console.log("ctx.url.match(/^\\/api/)", ctx.url.match(/\/api/));
+  //   if (
+  //     ctx.url.match(/\/api\/user\/login/) ||
+  //     ctx.url.match(/\/api\/user\/register/)||
+  //     ctx.url.match(/\/api\/receiveIDToken/)||
+  //     ctx.url.match(/\/api\/interaction/)||
+  //     ctx.url.match(/\/api\/authenticate/)
+  //   ) {
+  //     return next();
+  //   }
+  //   if (ctx.url.substr(0, 4) === '/api') {
+  //     //路由判断是否以/api开头的url,是则进行鉴权,否则直接输入内容
+  //     let authorization = ctx.headers.authorization,
+  //       token;
+  //     console.log('authorization', authorization);
+  //     if (ctx.headers) {
+  //       if (!authorization) {
+  //         ctx.status = 401;
+  //         return (ctx.body = "Bad permissions");
+  //       }
+  //       token = authorization.split(" ")[1];
+  //       try {
+  //         jwt.verify(token, 'seec-portal', (err, authData) => {
+  //           if(err) {
+  //             console.log("err:", err);
+  //             ctx.status = 401;
+  //             return (ctx.body = "Bad permissions");
+  //           }
+  //         });
+  //         //   ,refresh;
+  //         // //这里写刷新令牌逻辑,refresh是判断是否到达刷新令牌时间结果
+  //         // if (refresh) {
+  //         //   //在刷新时间范围内请求则刷新令牌
+  //         //   try {
+  //         //     let newToken = jsonwebtoken.sign(
+  //         //       user,
+  //         //       SECRET,
+  //         //       {
+  //         //         expiresIn: "1h"
+  //         //       }
+  //         //     );
+  //         //     ctx.cookies.set(
+  //         //       "authUser",
+  //         //       JSON.stringify(newToken),
+  //         //       {
+  //         //         maxAge: 60000 * 60,
+  //         //         overwrite: true
+  //         //       }
+  //         //     );
+  //         //   } catch (err) {
+  //         //     console.log(err);
+  //         //   }
+  //         // }
+  //       } catch (err) {
+  //         ctx.status = 401;
+  //         return (ctx.body = "Bad permissions");
+  //       }
+  //     }
+  //     return next();
+  //   } else {
+  //     ctx.req.session = ctx.session;
+  //     ctx.status = 200
+  //     ctx.respond = false // Bypass Koa's built-in response handling
+  //     ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
+  //     nuxt.render(ctx.req, ctx.res);
+  //   }
+  // });
+
   app.listen(port, host)
   consola.ready({
     message: `Server listening on http://${host}:${port}`,

+ 14 - 0
server/util/tokenProcessor.js

@@ -0,0 +1,14 @@
+const jwt = require('jsonwebtoken');
+
+
+module.exports = function getTokenUser(ctx){
+  let token = ctx.header.authorization.replace("Bearer '", "")
+  jwt.verify(token, 'seec-portal', (err, authData) => {
+    if(err) {
+      return null;
+    }
+    else {
+      return authData;
+    }
+  });
+};