完成控制器的重构

v1
宇天 2020-09-27 19:33:30 +08:00
parent 8cc03c337e
commit 20d03cd84c
2 changed files with 21 additions and 24 deletions

View File

@ -14,7 +14,7 @@ export default class Controller {
this.request = req this.request = req
this.response = res this.response = res
this.smarty = ctx.$$smarty this.views = ctx.$$views
} }
// 定义一个模板变量 // 定义一个模板变量
@ -24,15 +24,14 @@ export default class Controller {
} }
key += '' key += ''
if (key && this.smarty) { if (key) {
this.smarty.assign(key, val) this.views.assign(key, val)
} }
} }
// 模板渲染, 参数是模板名, 可不带后缀, 默认是 // 模板渲染, 参数是模板名, 可不带后缀, 默认是
render(file, noParse = false) { render(file, noParse = false) {
if (this.smarty) { this.views
this.smarty
.render(file, noParse) .render(file, noParse)
.then(html => { .then(html => {
this.response.render(html) this.response.render(html)
@ -41,24 +40,22 @@ export default class Controller {
this.response.error(err) this.response.error(err)
}) })
} }
}
get jwt() { // jwt 生成token及校验token
jwt(data) {
var { enabled, ttl } = this.context.get('jwt') var { enabled, ttl } = this.context.get('jwt')
var { mixKey } = this.request var { mixKey } = this.request
var auth = this.request.header('authorization')
if (enabled) { if (enabled) {
var tmp = Object.create(null) if (data) {
return this.context.$$jwt.sign(data, mixKey, ttl)
tmp.sign = data => this.context.$$jwt.sign(data, mixKey, ttl) } else {
if (auth) {
tmp.check = _ => { this.jwt.result = this.context.$$jwt.verify(auth, mixKey)
var str = this.request.header('authorization') return this.jwt.result
if (str) {
return this.context.$$jwt.verify(str, mixKey)
} }
} }
return tmp
} else { } else {
throw Error('Jwt was disabled.') throw Error('Jwt was disabled.')
} }

View File

@ -4,7 +4,7 @@
"type": "module", "type": "module",
"description": "控制器基类。", "description": "控制器基类。",
"main": "index.js", "main": "index.js",
"author": "yutent", "author": "yutent <yutent.io@gmail.com>",
"dependencies": { "dependencies": {
"crypto.js": "^2.0.2" "crypto.js": "^2.0.2"
}, },