如何在Express应用程序中获得当前登录的用户?

时间:2019-11-14 19:18:21

标签: node.js express mean-stack scheduler syncfusion

我在MEAN-stack应用程序中使用Syncfusion Scheduler。这是处理获取/插入/编辑约会的代码:

MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("meanstacknew");
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});
app.post("/GetData", (req, res) => {
    var user = req.user;

    const token = req.get("authorization");
    dbo.collection('ScheduleData').find({}).toArray((err, cus) => {
        res.send(cus);
       console.log(token);
    });
});
app.post("/BatchData", (req, res) => {
    console.log(req.body);
    var eventData = [];
    if (req.body.action == "insert" || (req.body.action == "batch" && req.body.added.length > 0)) {
        (req.body.action == "insert") ? eventData.push(req.body.value) : eventData = req.body.added;
        for (var i = 0; i < eventData.length; i++) {
            var sdate = new Date(eventData[i].StartTime);
            var edate = new Date(eventData[i].EndTime);
            eventData[i].StartTime = (new Date(+sdate - (sdate.getTimezoneOffset() * 60000)));
            eventData[i].EndTime = (new Date(+edate - (edate.getTimezoneOffset() * 60000)));
            eventData[i].CreatedBy =  //here I want to send the email to the database
            dbo.collection('ScheduleData').insertOne(eventData[i]);
        }
    }
    if (req.body.action == "update" || (req.body.action == "batch" && req.body.changed.length > 0)) {
        (req.body.action == "update") ? eventData.push(req.body.value) : eventData = req.body.changed;
        for (var i = 0; i < eventData.length; i++) {
            delete eventData[i]._id;
            var sdate = new Date(eventData[i].StartTime);
            var edate = new Date(eventData[i].EndTime);
            eventData[i].StartTime = (new Date(+sdate - (sdate.getTimezoneOffset() * 60000)));
            eventData[i].EndTime = (new Date(+edate - (edate.getTimezoneOffset() * 60000)));
            dbo.collection('ScheduleData').updateOne({ "Id": eventData[i].Id }, { $set: eventData[i] });
        }
    }
    if (req.body.action == "remove" || (req.body.action == "batch" && req.body.deleted.length > 0)) {
        (req.body.action == "remove") ? eventData.push({ Id: req.body.key }) : eventData = req.body.deleted;
        for (var i = 0; i < eventData.length; i++) {
            dbo.collection('ScheduleData').deleteOne({ "Id": eventData[i].Id });
        }
    }
    res.send(req.body);
});

我在schedule.component.ts中呼叫这些端点:

 private dataManager: DataManager = new DataManager({
url: 'http://localhost:8000/GetData',
crudUrl: 'http://localhost:8000/BatchData',
adaptor: new UrlAdaptor,
crossDomain: true
  });

此刻我正在使用JWT令牌进行用户授权,例如,这是我的/ profile端点:

   router.get('/profile', authRequired, (req, res) => {
       User.findOne({_id: req.decoded.userId}).select('username email').exec((err, user) =>{
          if(err){
              res.json({success: false, message: err});
          } else {
              if(!user){
                  res.json({success: false, message: 'User not found'});
              } else {
                  res.json({success: true, user: user})
              }
          }
       });
    });

如何访问用户电子邮件以在约会中设置“ createdBy”字段? 如果以这种方式console.log令牌,我只会得到undefined

这是middleware.js文件中的authRequired函数:

function authRequired(req, res, next) {
const token = req.get("authorization");
if (!token) {
    res.json({ success: false, message: "No token provided" });
} else {
    jwt.verify(token, config.secret, (err, decoded) => {
        if (err) {
            res.json({ success: false, message: "Token is invalid" + err });
        } else {
            req.decoded = decoded;
            next();
        }
         });
}
}

module.exports = {
authRequired: authRequired
};

2 个答案:

答案 0 :(得分:0)

您没有在authRequired路由上运行POST /GetData中间件,因此不会提取令牌。确保您也在POST中发送令牌。

像在router.get('/profile', authRequired, (req, res) => {中一样更新路由,以便获得解码的令牌。

app.post("/GetData", authRequired, (req, res) => {
    var user = req.decoded; //decoded
    ...
});

答案 1 :(得分:0)

Dear customer,

Syncfusion Greetings

We have achieved your requirement by making use of actionBegin event of our scheduler and same can be available in below link.

Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/sample276535241

  onActionBegin(args: ActionEventArgs): void {
    if (args.requestType === "eventCreate") {
      args.data[0].CreateBy = this.email;
      args.data[0].UserName = this.userName;
    }
  }

Kindly try with the above sample and let us know, if you need any further assistance on this.

Regards,
M. Vinitha devi