修复权限验证问题

This commit is contained in:
HelloWorld 2020-03-25 10:55:36 +08:00
parent 78b7dd36c2
commit 39f5cfc1c7
2 changed files with 204 additions and 206 deletions

View File

@ -1,117 +1,117 @@
const fileCache = require('think-cache-file'); const fileCache = require('think-cache-file');
const nunjucks = require('think-view-nunjucks'); const nunjucks = require('think-view-nunjucks');
const JWTSession = require('think-session-jwt'); const JWTSession = require('think-session-jwt');
const mysql = require('think-model-mysql'); const mysql = require('think-model-mysql');
const {Console, File, DateFile} = require('think-logger3'); const {Console, File, DateFile} = require('think-logger3');
const path = require('path'); const path = require('path');
const isDev = think.env === 'development'; const isDev = think.env === 'development';
/** /**
* cache adapter config * cache adapter config
* @type {Object} * @type {Object}
*/ */
exports.cache = { exports.cache = {
type: 'file', type: 'file',
common: { common: {
timeout: 24 * 60 * 60 * 1000 // millisecond timeout: 24 * 60 * 60 * 1000 // millisecond
}, },
file: { file: {
handle: fileCache, handle: fileCache,
cachePath: path.join(think.ROOT_PATH, 'runtime/cache'), // absoulte path is necessarily required cachePath: path.join(think.ROOT_PATH, 'runtime/cache'), // absoulte path is necessarily required
pathDepth: 1, pathDepth: 1,
gcInterval: 24 * 60 * 60 * 1000 // gc interval gcInterval: 24 * 60 * 60 * 1000 // gc interval
} }
}; };
/** /**
* model adapter config * model adapter config
* @type {Object} * @type {Object}
*/ */
exports.model = { exports.model = {
type: 'mysql', type: 'mysql',
common: { common: {
logConnect: isDev, logConnect: isDev,
logSql: isDev, logSql: isDev,
logger: msg => think.logger.info(msg) logger: msg => think.logger.info(msg)
}, },
mysql: { mysql: {
handle: mysql, handle: mysql,
database: 'mybookmarks', database: 'mybookmarks',
prefix: '', prefix: '',
encoding: 'utf8', encoding: 'utf8',
host: '127.0.0.1', host: '127.0.0.1',
port: '3306', port: '3306',
user: 'test', user: 'test',
password: '123456', password: '123456',
dateStrings: true dateStrings: true
} }
}; };
/** /**
* session adapter config * session adapter config
* @type {Object} * @type {Object}
*/ */
exports.session = { exports.session = {
type: 'jwt', type: 'jwt',
common: { common: {
cookie: { cookie: {
name: 'thinkjs', name: 'thinkjs',
} }
}, },
jwt: { jwt: {
handle: JWTSession, handle: JWTSession,
secret: 'secret', // secret is reqired secret: 'secret', // secret is reqired
tokenType: 'header', // ['query', 'body', 'header', 'cookie'], 'cookie' is default tokenType: 'header', // ['query', 'body', 'header', 'cookie'], 'cookie' is default
tokenName: 'authorization', // if tokenType not 'cookie', this will be token name, 'jwt' is default 后端字母要小写 tokenName: 'authorization', // if tokenType not 'cookie', this will be token name, 'jwt' is default 后端字母要小写
sign: { sign: {
// sign options is not required // sign options is not required
expiresIn: '604800s' // 7天过期 expiresIn: '604800s' // 7天过期
}, },
verify: { verify: {
// verify options is not required // verify options is not required
}, },
verifyCallback: (error) => { throw new Error("token verify error"); }, // default verify fail callback verifyCallback: any => any, // default verify fail callback
} }
} }
/** /**
* view adapter config * view adapter config
* @type {Object} * @type {Object}
*/ */
exports.view = { exports.view = {
type: 'nunjucks', type: 'nunjucks',
common: { common: {
viewPath: path.join(think.ROOT_PATH, 'view'), viewPath: path.join(think.ROOT_PATH, 'view'),
sep: '_', sep: '_',
extname: '.html' extname: '.html'
}, },
nunjucks: { nunjucks: {
handle: nunjucks handle: nunjucks
} }
}; };
/** /**
* logger adapter config * logger adapter config
* @type {Object} * @type {Object}
*/ */
exports.logger = { exports.logger = {
type: isDev ? 'console' : 'dateFile', type: isDev ? 'console' : 'dateFile',
console: { console: {
handle: Console handle: Console
}, },
file: { file: {
handle: File, handle: File,
backups: 10, // max chunk number backups: 10, // max chunk number
absolute: true, absolute: true,
maxLogSize: 50 * 1024, // 50M maxLogSize: 50 * 1024, // 50M
filename: path.join(think.ROOT_PATH, 'logs/app.log') filename: path.join(think.ROOT_PATH, 'logs/app.log')
}, },
dateFile: { dateFile: {
handle: DateFile, handle: DateFile,
level: 'ALL', level: 'ALL',
absolute: true, absolute: true,
pattern: '-yyyy-MM-dd', pattern: '-yyyy-MM-dd',
alwaysIncludePattern: true, alwaysIncludePattern: true,
filename: path.join(think.ROOT_PATH, 'logs/app.log') filename: path.join(think.ROOT_PATH, 'logs/app.log')
} }
}; };

View File

@ -1,89 +1,87 @@
const Base = require('./base.js'); const Base = require('./base.js');
const crypto = require('crypto'); const crypto = require('crypto');
function md5(str) { function md5(str) {
return crypto.createHash('md5').update(str).digest('hex'); return crypto.createHash('md5').update(str).digest('hex');
}; };
module.exports = class extends Base { module.exports = class extends Base {
async __before() { async __before() {
if (['register', 'login'].indexOf(this.ctx.action) >= 0) { if (['register', 'login'].indexOf(this.ctx.action) >= 0) {
return; return;
} }
try { try {
let user = await this.session('user'); let user = await this.session('user');
console.log(".......session user", this.ctx.action, Object.keys(user)); if (think.isEmpty(user.id)) {
if (think.isEmpty(user)) { return this.fail(401, '请先登录');
return this.fail(401, '请先登录'); }
} this.ctx.state.user = user;
this.ctx.state.user = user; } catch (error) {
} catch (error) { // 获取用户的 session 信息,如果为空,返回 false 阻止后续的行为继续执行
// 获取用户的 session 信息,如果为空,返回 false 阻止后续的行为继续执行 return this.fail(401, '请先登录:' + error.toString());
return this.fail(401, '请先登录:' + error.toString()); }
} }
}
indexAction() {
indexAction() { return this.display();
return this.display(); }
}
// 注册
// 注册 async registerAction() {
async registerAction() { try {
try { let post = this.post();
let post = this.post(); post.password = md5(post.password); // 进行密码加密
post.password = md5(post.password); // 进行密码加密
let res = await this.model("users").add(post);
let res = await this.model("users").add(post); this.json({ code: 0, data: res, msg: "注册成功" });
this.json({ code: 0, data: res, msg: "注册成功" }); } catch (error) {
} catch (error) { this.json({ code: 1, data: '', msg: error.toString() });
this.json({ code: 1, data: '', msg: error.toString() }); }
} }
}
// 登陆
// 登陆 async loginAction() {
async loginAction() { try {
try { let post = this.post();
let post = this.post(); post.password = md5(post.password); // 进行密码加密
post.password = md5(post.password); // 进行密码加密
let data = await this.model('users').where({ username: post.username, password: post.password }).find();
let data = await this.model('users').where({ username: post.username, password: post.password }).find(); if (think.isEmpty(data)) {
if (think.isEmpty(data)) { this.json({ code: 2, msg: "账号或者密码错误" });
this.json({ code: 2, msg: "账号或者密码错误" }); } else {
} else { delete data.password;
delete data.password; const token = await this.session('user', {
const token = await this.session('user', { id: data.id,
id: data.id, username: data.username
username: data.username });
}); data.token = token;
data.token = token; this.json({ code: 0, data, msg: "登陆成功" });
this.json({ code: 0, data, msg: "登陆成功" }); }
} catch (error) {
} this.json({ code: 1, data: '', msg: error.toString() });
} catch (error) { }
this.json({ code: 1, data: '', msg: error.toString() }); }
}
} // 通过session获取自己信息
async ownAction() {
// 通过session获取自己信息 let full = this.post().full;
async ownAction() { if (full) {
let full = this.post().full; let data = await this.model('users').where({ id: this.ctx.state.user.id }).find();
if (full) { delete data.password;
let data = await this.model('users').where({ id: this.ctx.state.user.id }).find(); this.json({ code: 0, data, msg: '' });
delete data.password; } else {
this.json({ code: 0, data, msg: '' }); this.json({ code: 0, data: this.ctx.state.user, msg: '' });
} else { }
this.json({ code: 0, data: this.ctx.state.user, msg: '' }); }
}
} async tagsAction() {
let tags = await this.model('tags').where({ user_id: this.ctx.state.user.id }).order('sort ASC, last_use DESC').select();
async tagsAction() { for (let tag of tags) {
let tags = await this.model('tags').where({ user_id: this.ctx.state.user.id }).order('sort ASC, last_use DESC').select(); let cnt = await this.model('tags_bookmarks').where({ tag_id: tag.id }).count();
for (let tag of tags) { let ncnt = await this.model('notes').where({ tag_id: tag.id }).count();
let cnt = await this.model('tags_bookmarks').where({ tag_id: tag.id }).count(); tag.cnt = cnt;
let ncnt = await this.model('notes').where({ tag_id: tag.id }).count(); tag.ncnt = ncnt;
tag.cnt = cnt; }
tag.ncnt = ncnt; this.json({ code: 0, data: tags, msg: '' });
} }
this.json({ code: 0, data: tags, msg: '' }); };
}
};