简体   繁体   English

如何生成令牌?

[英]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. 这是Helper utils文件:这是我具有生成令牌功能的文件。

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. 我相信您的ID必须是一个对象。 From the docs : 文档

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

Try 尝试

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

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

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