Home > Blockchain >  How to get userId as ClientId?
How to get userId as ClientId?

Time:11-12

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

User.schema.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

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.

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.

const userId = req.User._id;

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

Any help and suggestions would be appreciated.

authorization.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" });
};

CodePudding user response:

You have to assign whole user when authorize. This is how I solved this problem. Auth.js (middleware)


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. Because that's a middleware, every route that has this middleware will have a user.

  • Related