修复权限验证问题

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

View File

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