简体   繁体   中英

How can I generate the token?

I'm trying to generate a token as a user creates an account,but I seem to get an empty set? What could be wrong? Is anything wrong with the syntax?

This is the controller file:

import moment from 'moment';
import uuidv4 from 'uuidv4';
import db from '../db/index';
import Helper from '../middleware/helper';


const users = {

  async createAccount(req, res) {
    if (!req.body.email || !req.body.password) {
      return res.status(400).send({ 'message': 'Some values are missing' });
    }
    if (!Helper.isValidEmail(req.body.email)) {
      return res.status(400).send({ 'message': 'Please enter a valid email address' });
    }
    const hashPassword = Helper.hashPassword(req.body.password);

    const createQuery = `INSERT INTO
      users (id, firstName, lastName, otherNames, email, phoneNumber, userName, registered, isAdmin, password)
      VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
      returning *`;
    const values = [
      uuidv4(),
      req.body.firstName,
      req.body.lastName,
      req.body.otherNames,
      req.body.email,
      req.body.phoneNumber,
      req.body.userName,
      moment(new Date()),
      req.body.isAdmin,
      hashPassword,
    ];

    try {
      const { rows } = await db.query(createQuery, values);
      const token = Helper.generateToken(rows[0].id);
      return res.status(201).send({ token });
    } catch (error) {
      if (error.routine === '_bt_check_unique') {
        return res.status(400).send({ 'message': 'User with that EMAIL already exist' });
      }
      return res.status(400).send(error);
    }
  },

Here is the Helper utils File: This is the file where I have the function to generate a token.

import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';

const Helper = {

  generateToken(id) {
    const token = jwt.sign(id, process.env.SECRET, { expiresIn: '7d' });
    return token;
  },
};

export default Helper;

I believe your id needs to be an object. From the docs :

var token = jwt.sign({ foo: 'bar' }, 'shhhhh');

Try

var token = jwt.sign({id: id}, process.env.SECRET, {expiresIn: '7d'});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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