Паспорт. js: «Регистрация» локальной стратегии возвращает 401? Откуда это? - PullRequest
0 голосов
/ 18 апреля 2020

Даже не уверен, что посылает ответ 401, но я видел, как разные люди создавали стратегии только для registration;

В любом случае, это моя стратегия, я также включил «местную», которая обслуживает маршрут /login.

var passport = require('passport');
var nodemailer = require('nodemailer');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/UserModel');

var Token = require('../models/TokenSchema');

passport.use(
  'local',
  new LocalStrategy(
    { usernameField: 'username', passwordField: 'password' },
    async (username, password, done) => {
      try {
        const user = await UserModel.findOne({ username: username }).exec();
        if (!user) {
          return done(null, false, { message: 'Invalid username!' });
        }
        const passwordOk = await user.comparePassword(password);

        if (!passwordOk) {
          return done(null, false, {
            message: 'Invalid password!'
          });
        }
        return done(null, user);
      } catch (err) {
        return done(err);
      }
    }
  )
);

passport.use(
  'registration',
  new LocalStrategy(
    {
      usernameField: 'username',
      passwordField: 'password',
      passReqToCallback: true // allows us to pass back the entire request to the callback
    },
    function(req, username, password, done) {
      // find a user whose email is the same as the forms email
      // we are checking to see if the user trying to login already exists
      User.findOne({ username: username }, function(err, user) {
        // if there are any errors, return the error
        if (err) return done(err);

        // check to see if theres already a user with that email
        if (user) {
          req.userExists = [
            'The email address you have entered is already associated with another account.',
            'Please re-enter another email address.'
          ];
          return done(null, false);
        } else {
          // if there is no user with that email
          // create the user
          var user = new User({
            username: req.body.username,
            password: req.body.password
          });

          user.save(err => {
            if (err) throw err;
            nodeMailerFunc(
              user,
              `Account Verification`,
              `Hello, Welcome to Hillfinder! An app on the decline—er about declines!\nPlease verify your account by clicking the following link:\nhttp://${
                req.headers.host
              }/confirmed`,
              'verification email'
            );
            return done(null, user);
          });
        }
      });
    }
  )
);

// eslint-disable-next-line no-underscore-dangle
passport.serializeUser((user, done) => done(null, user._id));

passport.deserializeUser(async (id, done) => {
  try {
    const user = await UserModel.findById(id).exec();
    return done(null, user);
  } catch (err) {
    return done(err);
  }
});

function nodeMailerFunc(user, subjectField, textField, emailType) {
  var token = new Token({
    _userId: user._id,
    token: crypto.randomBytes(16).toString('hex')
  });

  // Save the token
  token.save(function(err) {
    if (err) {
      return res.status(500).send({ msg: err.message });
    }

    // Send the email
    var transporter = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        user: `${process.env.EMAIL_ADDRESS}`,
        pass: `${process.env.EMAIL_PASSWORD}`
      }
    });

    function outputTokenInEmail(emailType) {
      if (emailType !== 'change of password') return `/${token.token}`;
      else return '';
    }

    var mailOptions = {
      from: '17antonio.ortiz@gmail.com',
      to: `${user.username}`,
      subject: subjectField,
      text: `${textField}${outputTokenInEmail(emailType)}`
    };

    transporter.sendMail(mailOptions, function(err) {
      if (err) {
        return res.status(500).send({ msg: 'foo' });
      }
      res.status(200).send(`A ${emailType} has been sent to ${user.username}`);
    });
  });
}

module.exports = {
  nodeMailerFunc: nodeMailerFunc,
  initialize: passport.initialize(),
  session: passport.session(),
  setUser: (req, res, next) => {
    res.locals.user = req.user;
    return next();
  }
};

И это мой маршрут registration:

 router.route('/registration').post(passport.authenticate('registration'), (req, res) => {
      res.status(200).send({
        msg: [
          'Your user registration was successful.',
          'Please check your email to complete your registration!'
        ]
      });
      return;
    });

Так, как я могу проверить пользователя (по электронной почте и паролю), если он существует, отправить обратно 409 и если он не делает пользователя?

Заранее спасибо!

...