Closed andreashp96 closed 4 years ago
Unfortunately, I'm not able to troubleshoot other peoples code. If you discover a reproducible issue with this module please open an issue with a unit test, succinct code snippet or detailed instructions to reproduce.
Consider asking a question on stack overflow. Best of luck.
@andreashp96 , did you find the solution?
I have a difficulty on authentication. User login and registration work perfectly, but not for the authentication.
Here's the passport.js:
const JwtStrategy = require('passport-jwt').Strategy; const ExtractJwt = require('passport-jwt').ExtractJwt; const User = require('../model/User'); const key = require('./keys');
module.exports = (passport) => { let opts = {}; opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt'); opts.secretOrKey = key.secret; passport.use(new JwtStrategy (opts, (jwt_payload, done) => { User.getUserById(jwt_payload.data._id, (err, user)=>{ if (err) return done(err,false); if (user) return done(null, user); return done(null, false); }) } ) ); }
and here's the users.js: const express = require('express'); const router = express.Router(); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const passport = require('passport'); const User = require('../../model/User'); const key = require('../../config/keys').secret;
/**
@access Public */ router.post('/register', (req, res) => { let { name, username, email, password, address, birthday, confirm_password } = req.body if(password !== confirm_password) { return res.status(400).json({ msg: "Password do not match" }); }
//check username User.findOne({ username: username }).then(user => { if(user){ return res.status(400).json({ msg: "Username is already taken" }); } }); //check email User.findOne({ email:email }).then(user => { if(user){ return res.status(400).json({ msg: "Email is already registered" }); } });
//data is valid create new user let newUser = new User({ name, username, password, email, address, birthday });
//hash password bcrypt.genSalt(10, (err, salt) => { bcrypt.hash(newUser.password, salt, (err, hash) => { if(err) throw err; newUser.password = hash; newUser.save().then(user => { return res.status(201).json({ success: true, msg: "User is registered" }); }); }); });
});
/**
Bearer ${token}
, msg: "You are logged in" }) }) } else { //incorrect password return res.status(404).json({ msg: "Incorrect Password", success: false }); } }) }) });/**
module.exports = router;
Any idea why it's 401 unauthorized? Thank you!