Skip to content

Commit

Permalink
fix 修改登录用户保存方式
Browse files Browse the repository at this point in the history
  • Loading branch information
tumobi committed Aug 1, 2018
1 parent cac2eda commit 9abce37
Show file tree
Hide file tree
Showing 12 changed files with 51 additions and 81 deletions.
6 changes: 3 additions & 3 deletions src/admin/controller/base.js
Original file line number Diff line number Diff line change
@@ -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, '请先登录');
}
}
Expand Down
29 changes: 7 additions & 22 deletions src/admin/service/token.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,52 +5,37 @@ 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;
}

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;
}
}
return null;
}

async verify() {
const result = await this.parse();
async verify(token) {
const result = await this.parse(token);
if (think.isEmpty(result)) {
return false;
}
Expand Down
10 changes: 5 additions & 5 deletions src/api/controller/address.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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
});
}
Expand All @@ -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('删除成功');
}
Expand Down
8 changes: 4 additions & 4 deletions src/api/controller/base.js
Original file line number Diff line number Diff line change
@@ -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, '请先登录');
}
}
Expand All @@ -29,6 +29,6 @@ module.exports = class extends think.Controller {
* @returns {*}
*/
getLoginUserId() {
return think.userId;
return this.ctx.state.userId;
}
};
8 changes: 4 additions & 4 deletions src/api/controller/cart.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(';'),
Expand Down Expand Up @@ -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)) {
Expand Down
6 changes: 3 additions & 3 deletions src/api/controller/collect.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand All @@ -21,15 +21,15 @@ 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)) {
// 添加收藏
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 {
Expand Down
6 changes: 3 additions & 3 deletions src/api/controller/goods.js
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down Expand Up @@ -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)
});
}
Expand Down
10 changes: 5 additions & 5 deletions src/api/controller/order.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
// 订单的商品
Expand All @@ -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('订单不存在');
Expand Down Expand Up @@ -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('请选择商品');
}
Expand All @@ -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,
Expand Down Expand Up @@ -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 });
}
Expand Down
4 changes: 2 additions & 2 deletions src/api/controller/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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();
}
};
4 changes: 2 additions & 2 deletions src/api/controller/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand All @@ -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();
Expand Down
12 changes: 6 additions & 6 deletions src/api/model/cart.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,26 @@ 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;
}

/**
* 获取购物车的选中的商品
* @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;
}

/**
* 清空已购买的商品
* @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;
}
};
29 changes: 7 additions & 22 deletions src/api/service/token.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,52 +5,37 @@ 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;
}

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;
}
}
return null;
}

async verify() {
const result = await this.parse();
async verify(token) {
const result = await this.parse(token);
if (think.isEmpty(result)) {
return false;
}
Expand Down

0 comments on commit 9abce37

Please sign in to comment.