简体   繁体   English

如何获取 userId 作为 ClientId?

[英]How to get userId as ClientId?

I am trying to get user id, that mongoose will create for user schema, as clientId in "/post" api so that i can have user Id as clientId on tickets我正在尝试获取用户 ID,该 mongoose 将为用户架构创建,作为“/post”api 中的 clientId,以便我可以将用户 ID 作为票证上的 clientId

User.schema.js用户架构.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    name: {
        type: String,
        maxlength: 50,
        required: true
    },
    company: {
        type: String,
        maxlength: 50,
        required: true
    },
    address: {
        type: String,
        maxlength: 100,
    },
    phone: {
        type: Number,
        maxlength: 11,
    },
    email: {
        type: String,
        maxlength: 50,
        required: true,
    },
    password: {
        type: String,
        minLength: 8,
        maxlength: 100,
        required: true
    },
    refreshJWT: {
        token: {
            type: String,
            maxLength: 500,
            default: "",
        },
        addedAt: {
            type: Date,
            required: true,
            default: Date.now(),
        },
    },
    isVerified: {
        type: Boolean,
        required: true,
        default: false
    },
});

module.exports = {
    UserSchema: mongoose.model("User", UserSchema),
};

Ticket.schema.js票证.schema.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const TicketSchema = new Schema({
    clientId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
    },
    subject: {
        type: String,
        maxLength: 100,
        required: true,
        default: ""
    },
    openAt: {
        type: Date,
        required: true,
        default: Date.now(),
    },
    status: {
        type: String,
        maxLength: 30,
        required: true,
        default: "Pending operator response",
    },
    conversations: [
        {
            sender: {
                type: String,
                maxLength: 50,
                required: true,
                default: "",
            },
            message: {
                type: String,
                maxLength: 1000,
                required: true,
                default: "",
            },
            msgAt: {
                type: Date,
                required: true,
                default: Date.now(),
            },
        },
    ],
});

module.exports = {
    TicketSchema: mongoose.model("Ticket", TicketSchema),
};

Ticket.js - This is the router I am using to create a ticket with client ID and other details on it. Ticket.js - 这是我用来创建带有客户端 ID 和其他详细信息的票证的路由器。

router.post(
  "/",
  createNewTicketValidation,
  userAuthorization,
  async (req, res) => {
    try {
      const { subject, sender, message } = req.body;

      const userId = req.User._id;

      const ticketObj = {
        clientId: userId,
        subject,
        conversations: [
          {
            sender,
            message,
          },
        ],
      };

      const result = await newTicket(ticketObj);

      if (result._id) {
        return res.json({
          status: "success",
          message: "New ticket has been created!",
        });
      }

      res.json({
        status: "error",
        message: "Unable to create the ticket , please try again later",
      });
    } catch (error) {
      res.json({ status: "error", message: error.message });
    }
  }
);

Basically, I am stuck with specifically this phase of code,as I am not able to figure out that how can i get user Id as client id in the above router.基本上,我特别坚持这个阶段的代码,因为我无法弄清楚如何在上述路由器中获取用户 ID 作为客户端 ID。

const userId = req.User._id;

      const ticketObj = {
        clientId: userId,
        subject,
        conversations: [
          {
            sender,
            message,
          },
        ],
      };

Any help and suggestions would be appreciated.任何帮助和建议将不胜感激。

authorization.js授权.js

const userAuthorization = async(req,res,next) => {
    const { authorization } = req.headers;

    const decoded = await verifyAccessJWT(authorization);

    if (decoded.email){

        const userId = await getJWT(authorization);
        
        if (!userId) {
            return res.status(403).json({message: "Forbidden"});
        }
        
        return next();
            
    }

    deleteJWT(authorization);

    return res.status(403).json({ message: "forbidden" });
};

You have to assign whole user when authorize.您必须在授权时分配整个用户。 This is how I solved this problem.这就是我解决这个问题的方法。 Auth.js (middleware) Auth.js (中间件)


module.exports = function (req, res, next) {
  // Getting token from the header.
  const token = req.header("x-auth-token");

  // Checking if there is a token.
  if (!token) {
    return res.status(401).json({ msg: "No token, authorization denied." });
  }

  try {
    const decoded = jwt.verify(token, process.env.REACT_APP_JWT_SECRET);
    req.user = decoded.user;
    next();
  } catch (error) {
      res.status(401).json({msg: "Token is not valid."})
  }
};

If you are using JWT you should first of all decode and thenassign user as a req.如果您使用 JWT,您应该首先解码,然后将用户分配为请求。 Because that's a middleware, every route that has this middleware will have a user.因为这是一个中间件,所以每条有这个中间件的路由都会有一个用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM