gpt4 book ai didi

javascript - 将解码后的用户保存在数据库中

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:26 25 4
gpt4 key购买 nike

我有一个应用程序,用户可以拍摄一些照片并将其发送到数据库,就这么简单。

每次用户登录时,如果 token 一切正常,他都会获得一个 token (他不需要登录)。

我关注了this进行jwt身份验证的教程,现在我想检查除(/登录/注册)该 token 之外的每个请求并对其进行解码以获取用户信息(我只是保存用户名,它是唯一的,所以很好)。

想象一下我正在路由到/flower?flowerName (随机路由),所以在这条路由中我想创建一个寄存器并在我的数据库中保存一些数据,但在此之前正如我所说,我应该输入一个检查权限的中间件。

这是我的中间件:

var jwt = require('jsonwebtoken');
var jwtConfig = require('../config/jwt');

module.exports = function(req, res, next) {
console.log("entered");

// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
console.log(req.headers['x-access-token']);
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token,jwtConfig.secret, function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
console.log("HEREE");
// if everything is good, save to request for use in other routes
req.decoded = decoded;
console.log(req.decoded);
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}

}

我的问题是,如何获取中间件的用户ID,然后将其保存在下一个路由中?我可以通过下一个吗?就像下一个(用户ID)???那我该如何获取参数呢?

这是我保存寄存器的地方:

    var express = require('express');
var User = require('../models').User;
var Foto = require('../models').Foto;
var router = express.Router();
var jwt = require('jsonwebtoken');
var fs = require('fs');
var fsPath = require('fs-path');


module.exports = {
sendPicture: function (req, res,next) {
var bitmap = new Buffer(req.body.base64, 'base64');
var dummyDate = "25/04/14-15:54:23";
var lat = req.params.lat;
var lon = req.params.lon;
var alt = req.params.alt;
var path = __dirname + "/../public/images/" + req.params.flowerName + "/example3.png";
var fotoPath = ""
var userId = 1;
console.log(lat);
console.log(lon);
console.log(alt);
console.log(req.query.token);
fsPath.writeFile(path, bitmap, function (err) {
if (err) {
console.log(err.stack);
return err;
}
Foto.create({
image: path,
userId: userId
}).then(function () {
return res.status(200).json({ message: "foto created" });
}).catch(function(err){
console.log(err.stack);
})

});
}
}

最佳答案

您应该能够通过 res.locals 在整个链中传递任何状态变量,即

res.locals.decoded = decoded;
next();

您可以在 res.locals here 上找到详细信息

关于javascript - 将解码后的用户保存在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44117892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com