Parcourir la source

fix 修改登录用户保存方式

tumobi il y a 6 ans
Parent
commit
9abce37ee7

+ 3 - 3
src/admin/controller/base.js

@@ -1,13 +1,13 @@
 module.exports = class extends think.Controller {
   async __before() {
     // 根据token值获取用户id
-    think.token = this.ctx.header['x-nideshop-token'] || '';
+    this.ctx.state.token = this.ctx.header['x-nideshop-token'] || '';
     const tokenSerivce = think.service('token', 'admin');
-    think.userId = await tokenSerivce.getUserId();
+    this.ctx.state.userId = await tokenSerivce.getUserId(this.ctx.state.token);
 
     // 只允许登录操作
     if (this.ctx.controller !== 'auth') {
-      if (think.userId <= 0) {
+      if (this.ctx.state.userId <= 0) {
         return this.fail(401, '请先登录');
       }
     }

+ 7 - 22
src/admin/service/token.js

@@ -5,13 +5,12 @@ module.exports = class extends think.Service {
   /**
    * 根据header中的X-Nideshop-Token值获取用户id
    */
-  async getUserId() {
-    const token = think.token;
+  async getUserId(token) {
     if (!token) {
       return 0;
     }
 
-    const result = await this.parse();
+    const result = await this.parse(token);
     if (think.isEmpty(result) || result.user_id <= 0) {
       return 0;
     }
@@ -19,29 +18,15 @@ module.exports = class extends think.Service {
     return result.user_id;
   }
 
-  /**
-   * 根据值获取用户信息
-   */
-  async getUserInfo() {
-    const userId = await this.getUserId();
-    if (userId <= 0) {
-      return null;
-    }
-
-    const userInfo = await this.model('admin').where({ id: userId }).find();
-
-    return think.isEmpty(userInfo) ? null : userInfo;
-  }
-
   async create(userInfo) {
     const token = jwt.sign(userInfo, secret);
     return token;
   }
 
-  async parse() {
-    if (think.token) {
+  async parse(token) {
+    if (token) {
       try {
-        return jwt.verify(think.token, secret);
+        return jwt.verify(token, secret);
       } catch (err) {
         return null;
       }
@@ -49,8 +34,8 @@ module.exports = class extends think.Service {
     return null;
   }
 
-  async verify() {
-    const result = await this.parse();
+  async verify(token) {
+    const result = await this.parse(token);
     if (think.isEmpty(result)) {
       return false;
     }

+ 5 - 5
src/api/controller/address.js

@@ -6,7 +6,7 @@ module.exports = class extends Base {
    * @return {Promise} []
    */
   async listAction() {
-    const addressList = await this.model('address').where({user_id: think.userId}).select();
+    const addressList = await this.model('address').where({user_id: this.getLoginUserId()}).select();
     let itemKey = 0;
     for (const addressItem of addressList) {
       addressList[itemKey].province_name = await this.model('region').getRegionName(addressItem.province_id);
@@ -26,7 +26,7 @@ module.exports = class extends Base {
   async detailAction() {
     const addressId = this.get('id');
 
-    const addressInfo = await this.model('address').where({user_id: think.userId, id: addressId}).find();
+    const addressInfo = await this.model('address').where({user_id: this.getLoginUserId(), id: addressId}).find();
     if (!think.isEmpty(addressInfo)) {
       addressInfo.province_name = await this.model('region').getRegionName(addressInfo.province_id);
       addressInfo.city_name = await this.model('region').getRegionName(addressInfo.city_id);
@@ -58,12 +58,12 @@ module.exports = class extends Base {
     if (think.isEmpty(addressId)) {
       addressId = await this.model('address').add(addressData);
     } else {
-      await this.model('address').where({id: addressId, user_id: think.userId}).update(addressData);
+      await this.model('address').where({id: addressId, user_id: this.getLoginUserId()}).update(addressData);
     }
 
     // 如果设置为默认,则取消其它的默认
     if (this.post('is_default') === true) {
-      await this.model('address').where({id: ['<>', addressId], user_id: think.userId}).update({
+      await this.model('address').where({id: ['<>', addressId], user_id: this.getLoginUserId()}).update({
         is_default: 0
       });
     }
@@ -79,7 +79,7 @@ module.exports = class extends Base {
   async deleteAction() {
     const addressId = this.post('id');
 
-    await this.model('address').where({id: addressId, user_id: think.userId}).delete();
+    await this.model('address').where({id: addressId, user_id: this.getLoginUserId()}).delete();
 
     return this.success('删除成功');
   }

+ 4 - 4
src/api/controller/base.js

@@ -1,16 +1,16 @@
 module.exports = class extends think.Controller {
   async __before() {
     // 根据token值获取用户id
-    think.token = this.ctx.header['x-nideshop-token'] || '';
+    this.ctx.state.token = this.ctx.header['x-nideshop-token'] || '';
     const tokenSerivce = think.service('token', 'api');
-    think.userId = await tokenSerivce.getUserId();
+    this.ctx.state.userId = await tokenSerivce.getUserId(this.ctx.state.token);
 
     const publicController = this.config('publicController');
     const publicAction = this.config('publicAction');
     // 如果为非公开,则验证用户是否登录
     const controllerAction = this.ctx.controller + '/' + this.ctx.action;
     if (!publicController.includes(this.ctx.controller) && !publicAction.includes(controllerAction)) {
-      if (think.userId <= 0) {
+      if (this.ctx.state.userId <= 0) {
         return this.fail(401, '请先登录');
       }
     }
@@ -29,6 +29,6 @@ module.exports = class extends think.Controller {
    * @returns {*}
    */
   getLoginUserId() {
-    return think.userId;
+    return this.ctx.state.userId;
   }
 };

+ 4 - 4
src/api/controller/cart.js

@@ -6,7 +6,7 @@ module.exports = class extends Base {
    * @returns {Promise.<{cartList: *, cartTotal: {goodsCount: number, goodsAmount: number, checkedGoodsCount: number, checkedGoodsAmount: number}}>}
    */
   async getCart() {
-    const cartList = await this.model('cart').where({user_id: think.userId, session_id: 1}).select();
+    const cartList = await this.model('cart').where({user_id: this.getLoginUserId(), session_id: 1}).select();
     // 获取购物车统计信息
     let goodsCount = 0;
     let goodsAmount = 0.00;
@@ -87,7 +87,7 @@ module.exports = class extends Base {
         list_pic_url: goodsInfo.list_pic_url,
         number: number,
         session_id: 1,
-        user_id: think.userId,
+        user_id: this.getLoginUserId(),
         retail_price: productInfo.retail_price,
         market_price: productInfo.retail_price,
         goods_specifition_name_value: goodsSepcifitionValue.join(';'),
@@ -235,9 +235,9 @@ module.exports = class extends Base {
     // 选择的收货地址
     let checkedAddress = null;
     if (addressId) {
-      checkedAddress = await this.model('address').where({is_default: 1, user_id: think.userId}).find();
+      checkedAddress = await this.model('address').where({is_default: 1, user_id: this.getLoginUserId()}).find();
     } else {
-      checkedAddress = await this.model('address').where({id: addressId, user_id: think.userId}).find();
+      checkedAddress = await this.model('address').where({id: addressId, user_id: this.getLoginUserId()}).find();
     }
 
     if (!think.isEmpty(checkedAddress)) {

+ 3 - 3
src/api/controller/collect.js

@@ -12,7 +12,7 @@ module.exports = class extends Base {
         join: 'left',
         as: 'g',
         on: ['c.value_id', 'g.id']
-      }).where({user_id: think.userId, type_id: parseInt(typeId)}).countSelect();
+      }).where({user_id: this.getLoginUserId(), type_id: parseInt(typeId)}).countSelect();
 
     return this.success(list);
   }
@@ -21,7 +21,7 @@ module.exports = class extends Base {
     const typeId = this.post('typeId');
     const valueId = this.post('valueId');
 
-    const collect = await this.model('collect').where({type_id: typeId, value_id: valueId, user_id: think.userId}).find();
+    const collect = await this.model('collect').where({type_id: typeId, value_id: valueId, user_id: this.getLoginUserId()}).find();
     let collectRes = null;
     let handleType = 'add';
     if (think.isEmpty(collect)) {
@@ -29,7 +29,7 @@ module.exports = class extends Base {
       collectRes = await this.model('collect').add({
         type_id: typeId,
         value_id: valueId,
-        user_id: think.userId,
+        user_id: this.getLoginUserId(),
         add_time: parseInt(new Date().getTime() / 1000)
       });
     } else {

+ 3 - 3
src/api/controller/goods.js

@@ -55,10 +55,10 @@ module.exports = class extends Base {
     };
 
     // 当前用户是否收藏
-    const userHasCollect = await this.model('collect').isUserHasCollect(think.userId, 0, goodsId);
+    const userHasCollect = await this.model('collect').isUserHasCollect(this.getLoginUserId(), 0, goodsId);
 
     // 记录用户的足迹 TODO
-    await await this.model('footprint').addFootprint(think.userId, goodsId);
+    await await this.model('footprint').addFootprint(this.getLoginUserId(), goodsId);
 
     // return this.json(jsonData);
     return this.success({
@@ -122,7 +122,7 @@ module.exports = class extends Base {
       // 添加到搜索历史
       await this.model('search_history').add({
         keyword: keyword,
-        user_id: think.userId,
+        user_id: this.getLoginUserId(),
         add_time: parseInt(new Date().getTime() / 1000)
       });
     }

+ 5 - 5
src/api/controller/order.js

@@ -7,7 +7,7 @@ module.exports = class extends Base {
    * @return {Promise} []
    */
   async listAction() {
-    const orderList = await this.model('order').where({ user_id: think.userId }).page(1, 10).countSelect();
+    const orderList = await this.model('order').where({ user_id: this.getLoginUserId() }).page(1, 10).countSelect();
     const newOrderList = [];
     for (const item of orderList.data) {
       // 订单的商品
@@ -32,7 +32,7 @@ module.exports = class extends Base {
 
   async detailAction() {
     const orderId = this.get('orderId');
-    const orderInfo = await this.model('order').where({ user_id: 1, id: orderId }).find();
+    const orderInfo = await this.model('order').where({ user_id: this.getLoginUserId(), id: orderId }).find();
 
     if (think.isEmpty(orderInfo)) {
       return this.fail('订单不存在');
@@ -85,7 +85,7 @@ module.exports = class extends Base {
     const freightPrice = 0.00;
 
     // 获取要购买的商品
-    const checkedGoodsList = await this.model('cart').where({ user_id: think.userId, session_id: 1, checked: 1 }).select();
+    const checkedGoodsList = await this.model('cart').where({ user_id: this.getLoginUserId(), session_id: 1, checked: 1 }).select();
     if (think.isEmpty(checkedGoodsList)) {
       return this.fail('请选择商品');
     }
@@ -110,7 +110,7 @@ module.exports = class extends Base {
 
     const orderInfo = {
       order_sn: this.model('order').generateOrderNumber(),
-      user_id: think.userId,
+      user_id: this.getLoginUserId(),
 
       // 收货地址和运费
       consignee: checkedAddress.name,
@@ -160,7 +160,7 @@ module.exports = class extends Base {
     }
 
     await this.model('order_goods').addMany(orderGoodsData);
-    await this.model('cart').clearBuyGoods();
+    await this.model('cart').clearBuyGoods(this.getLoginUserId());
 
     return this.success({ orderInfo: orderInfo });
   }

+ 2 - 2
src/api/controller/search.js

@@ -6,7 +6,7 @@ module.exports = class extends Base {
     const defaultKeyword = await this.model('keywords').where({ is_default: 1 }).limit(1).find();
     // 取出热闹关键词
     const hotKeywordList = await this.model('keywords').distinct('keyword').field(['keyword', 'is_hot']).limit(10).select();
-    const historyKeywordList = await this.model('search_history').distinct('keyword').where({ user_id: think.userId }).limit(10).getField('keyword');
+    const historyKeywordList = await this.model('search_history').distinct('keyword').where({ user_id: this.getLoginUserId() }).limit(10).getField('keyword');
 
     return this.success({
       defaultKeyword: defaultKeyword,
@@ -22,7 +22,7 @@ module.exports = class extends Base {
   }
 
   async clearhistoryAction() {
-    await this.model('search_history').where({ user_id: think.userId }).delete();
+    await this.model('search_history').where({ user_id: this.getLoginUserId() }).delete();
     return this.success();
   }
 };

+ 2 - 2
src/api/controller/user.js

@@ -4,7 +4,7 @@ const _ = require('lodash');
 
 module.exports = class extends Base {
   async infoAction() {
-    const userInfo = await this.model('user').where({mobile: '15989389319'}).find();
+    const userInfo = await this.model('user').where({id: this.getLoginUserId()}).find();
     delete userInfo.password;
     return this.json(userInfo);
   }
@@ -19,7 +19,7 @@ module.exports = class extends Base {
       return this.fail('保存失败');
     }
 
-    const avatarPath = think.RESOURCE_PATH + '/static/user/avatar/1.' + _.last(_.split(avatar.path, '.'));
+    const avatarPath = think.RESOURCE_PATH + `/static/user/avatar/${this.getLoginUserId()}.` + _.last(_.split(avatar.path, '.'));
 
     fs.rename(avatar.path, avatarPath, function(res) {
       return this.success();

+ 6 - 6
src/api/model/cart.js

@@ -3,8 +3,8 @@ module.exports = class extends think.Model {
    * 获取购物车的商品
    * @returns {Promise.<*>}
    */
-  async getGoodsList() {
-    const goodsList = await this.model('cart').where({user_id: think.userId, session_id: 1}).select();
+  async getGoodsList(userId) {
+    const goodsList = await this.model('cart').where({user_id: userId, session_id: 1}).select();
     return goodsList;
   }
 
@@ -12,8 +12,8 @@ module.exports = class extends think.Model {
    * 获取购物车的选中的商品
    * @returns {Promise.<*>}
    */
-  async getCheckedGoodsList() {
-    const goodsList = await this.model('cart').where({user_id: think.userId, session_id: 1, checked: 1}).select();
+  async getCheckedGoodsList(userId) {
+    const goodsList = await this.model('cart').where({user_id: userId, session_id: 1, checked: 1}).select();
     return goodsList;
   }
 
@@ -21,8 +21,8 @@ module.exports = class extends think.Model {
    * 清空已购买的商品
    * @returns {Promise.<*>}
    */
-  async clearBuyGoods() {
-    const $res = await this.model('cart').where({user_id: think.userId, session_id: 1, checked: 1}).delete();
+  async clearBuyGoods(userId) {
+    const $res = await this.model('cart').where({user_id: userId, session_id: 1, checked: 1}).delete();
     return $res;
   }
 };

+ 7 - 22
src/api/service/token.js

@@ -5,13 +5,12 @@ module.exports = class extends think.Service {
   /**
    * 根据header中的X-Nideshop-Token值获取用户id
    */
-  async getUserId() {
-    const token = think.token;
+  async getUserId(token) {
     if (!token) {
       return 0;
     }
 
-    const result = await this.parse();
+    const result = await this.parse(token);
     if (think.isEmpty(result) || result.user_id <= 0) {
       return 0;
     }
@@ -19,29 +18,15 @@ module.exports = class extends think.Service {
     return result.user_id;
   }
 
-  /**
-   * 根据值获取用户信息
-   */
-  async getUserInfo() {
-    const userId = await this.getUserId();
-    if (userId <= 0) {
-      return null;
-    }
-
-    const userInfo = await this.model('user').field(['id', 'username', 'nickname', 'gender', 'avatar', 'birthday']).where({ id: userId }).find();
-
-    return think.isEmpty(userInfo) ? null : userInfo;
-  }
-
   async create(userInfo) {
     const token = jwt.sign(userInfo, secret);
     return token;
   }
 
-  async parse() {
-    if (think.token) {
+  async parse(token) {
+    if (token) {
       try {
-        return jwt.verify(think.token, secret);
+        return jwt.verify(token, secret);
       } catch (err) {
         return null;
       }
@@ -49,8 +34,8 @@ module.exports = class extends think.Service {
     return null;
   }
 
-  async verify() {
-    const result = await this.parse();
+  async verify(token) {
+    const result = await this.parse(token);
     if (think.isEmpty(result)) {
       return false;
     }