Паспорт. js: Почему стратегия passport-local вернулась (null, user); но стратегия passport-jwt сделала (ноль, пользователь)? - PullRequest
0 голосов
/ 29 января 2020

Вот определение JWTstrategy (С некоторыми моими комментариями, пытающимися объяснить себе, что происходит):

/**
 * For the jwt strategy, the JWT is passed back from the client with each call to the server 
 (I passed mine in an authorization header with the key: JWT)
which is extracted and then decoded using the secret (which is stored in another file, but
   should really be an environment variable known only to the system).
 */
    const opts = {
      jwtFromRequest: ExtractJWT.fromAuthHeaderWithScheme('JWT'),
      secretOrKey: jwtSecret.secret,
    };

        passport.use(
          'jwt',
          new JWTstrategy(opts, (jwt_payload, done) => {
            try {
              User.findOne({
                where: {
                  /**
                   * Once the JWT payload is decrypted, the ID (which for me is the username) can be searched for in 
                   * the database just like the passport-local strategy does,
                   * //TODO: Why is the ID the username? Where is the part where the token is created in the first place?
                   */
                  id: jwt_payload.id,
                },
              }).then(user => {
                if (user) {
                  console.log('user found in db in passport');
                  /**and either returned with done(null, user);, if the user is found */
                  done(null, user);
                } else {
                  /**
                   * with done(null, false); if it’s not (which should almost never happen because the JWT includes 
                   * the username in its encrypted form, so unless that’s somehow been tampered with or the db has been, 
                   * it should be able to find the user).
                   */
                  console.log('user not found in db');
                  done(null, false);
                }
              });
            } catch (err) {
              done(err);
            }
          }),
        );

А вот определение LocalStrategy :

passport.use(
  'login',
  new LocalStrategy(
    {
      usernameField: 'username',
      passwordField: 'password',
      session: false,
    },
    (username, password, done) => {
      try {
        User.findOne({
          where: {
            username,
          },
        }).then(user => {
          if (user === null) {
            return done(null, false, { message: 'bad username' });
          }
          /**
           *  it hashes the newly entered password and checks the passwords with bcrypt’s
           *  compare function before returning either a positive or negative on the verification.
           */
          bcrypt.compare(password, user.password).then(response => {
            if (response !== true) {
              //When we cannot find the user or the passwords do not match, we invoke done(null, false). 
              console.log('passwords do not match');
              return done(null, false, { message: 'passwords do not match' });
            }
            //If everything went fine and we want the user to login we invoke done(null, user).
            console.log('user found & authenticated');
            return done(null, user);
          });
        });
      } catch (err) {
        //In case of an Error interacting with our database, we need to invoke done(err)
        done(err);
      }
    },
  ),
);   

Обратите внимание, как:
Стратегия passport-local вернула done (null, user) ;
но стратегия passport-jwt имеет выполнено (null, пользователь) .
В учебнике , которому я следую, написано:

Это крохотно, но наличие (или удаление этого возврата) - это разница между пользовательскими данными, которые передаются обратно из промежуточного программного обеспечения на сервер, или нет. Так что знайте, когда возвращаться или нет.

Но не совсем понятно, почему стратегия passport-local имеет возвращение выполнено (null, пользователь) ; но стратегия passport-jwt имеет выполнено (null, пользователь) ?
И когда следует Данные пользователя будут возвращены из промежуточного программного обеспечения на сервер и почему? Может кто-нибудь пожалуйста прояснить эту путаницу?

...