从节点API端点解析表达式(布尔) [英] Resolve Expression from Node API Endpoint (Boolean)
问题描述
我正在尝试验证API密钥以运行API端点功能。
I am trying to validate an API key to run an API endpoint function.
server.js
server.js
let db = require("./sql/rest_functions") // Custom modules
let session = require("./sql/session_management")
app.get("/node/api/mssql/test", function(req, res) {
if(session.validateKey(req)) {
db.mssqlQuery(req, res)
}
})
session.js
session.js
exports.validateKey = function(req) {
return sql.connect(config.properties)
.then(pool => {
return pool.request()
.query("SELECT CASE WHEN EXISTS (SELECT * FROM Login WHERE (username = '" + req.header("username") + "' AND apiKey = '" + req.header("apiKey") + "')) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END")
.then(response => {
console.log(typeof response[0]['']) // returns boolean
return response[0][''] // return nested value to get true / false response
})
})
}
validateKey
函数是返回true和false(我认为是纯文本),并且我希望它解析为可以传递给API测试函数的布尔值。
The validateKey
function is returning true and false (I think as plain text), and I would like it to resolve to a boolean that can be passed into the API test function.
我已经尝试过此 JSON.parse
方法和 session.validateKey(req) =='true'
设计模式,但两种情况都无法解决预期的行为。
I have tried this JSON.parse
method and the session.validateKey(req) == 'true'
design pattern, but neither case resolves to an expected behavior.
如何解析返回值以验证用户的
How can I resolve the returned value to verify the user's credentials?
推荐答案
我建议简单地从数据库返回行数并验证是否存在 1
项(或多个,取决于数据的结构)。
I would suggest simply returning the count of rows from the database and validating that there exists 1
entry (or more than one, depending on how your data are structured).
请注意,为了缓解SQL注入,您必须使用参数绑定,如下所示;库不会自动防止注入,根据文档您不使用参数绑定。将 VarChar(100)
更改为这些字段的列类型。
Note that to mitigate against SQL Injection, you must use parameter binding, illustrated below; the library does not "automatically" protect against injection, as per the documentation if you do not use parameter binding. Change VarChar(100)
to whatever the column type is for those fields.
exports.validateKey = async function(req) {
return await sql.connect(config.properties)
.then(pool => pool.request()
.input('user', sql.VarChar(100), req.header("username"))
.input('key', sql.VarChar(100), req.header("apiKey"))
.query('SELECT COUNT(*) AS valid FROM Login WHERE username = @user AND apiKey = @key')
.then(response => result.recordset[0].valid === 1)
)
}
请注意, validateKey
将返回布尔值 Promise ,因此我们添加了 async
/ await
来保存对路由控制器的修改。
Note that validateKey
will return a Boolean Promise, so we've added async
/await
to save modifying the route controller.
请注意,我已经从大多数粗箭头功能中删除了花括号:它们是一条语句,使它们冗余。
Note that I've removed the braces from most of the fat arrow functions: they're all one statement so they're redundant.
Caveat :我实际上不能尝试这样做,这是从阅读文档中得出的有根据的猜测。希望对您有所帮助。
Caveat: I can't actually try this, it's an educated guess from reading the documentation. I hope it helps.
这篇关于从节点API端点解析表达式(布尔)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!