N
N
Night_Harpy2021-03-02 13:55:47
JSON Web Token
Night_Harpy, 2021-03-02 13:55:47

Why is the token not generated?

Services:

addUser = async (body) => {
    const user = new User(body);
    await user.save();
    if (!(await fs.pathExists(`public/images/users/${user._id}`))) {
      await fs.ensureDir(`public/images/users/${user._id}`);
    }
    const token = await user.generateAuthToken();
    console.log(token)
    return { ...user, token };
  };

Scheme for token generation:
const userSchema = new mongoose.Schema({
    login: {
        type: String,
        unique: true,
        required: true,
        trim: true
    },
    firstName: {
        type: String
    },
    lastName: {
        type: String
    },
    email: {
        type: String
    },
    password: {
        type: String,
        required: true,
        minlength: 3,
        trim: true,
        validate(value) {
            if (value.toLowerCase().includes('password')){
                throw new Error('Password cannot contain "password"');
            }
        }
    },
    avatar: {
        type: String
    },
    role: {
        type: String,
        default: 'user'
    },
    tokens: [
        {
            token: {
                type: String,
                required: true
            }
        }
    ]    
});

userSchema.methods.generateAuthToken = async function() {
    const user = this;
    const token = jwt.sign({ _id: user._id.toString() }, process.env.KeyWord);
    user.tokens = await user.tokens.concat({ token });
    user.save();
    return token;
};

 const User = mongoose.model("Users", userSchema);

an entry in the database is added, but without a token, the token is not generated in principle. What could be the problem?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
lxfr, 2017-11-29
@lxfr

And what error does it give? :)

D
Dmitry, 2017-11-29
@slo_nik

Replace $db->hostwith $this->host, change the rest too.

A
Alexander Gamov, 2017-11-29
@slowdream

class DB
  {
    private static $db;
    private $host = 'localhost';
    private $dbname = 'test';
    private $charset = 'utf8';
    private $username = 'root';
    private $password = '';
    
    static public function connect()
    {
      if (self::$db === Null) {
        self::$db = new self();
      }
      return self::$db;
    }
    private function __clone() {}
    private function __construct()
   {
      return new \PDO("mysql:host=".$this->host.";dbname=".$this->dbname.";charset=".$this->charset, $this->username, $this->password);
   }
  }
  
  $db = DB::connect();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question