naimiii
January 21, 2021, 10:47am
1
Here’s my code
//users.js
const express = require('express');
const router= express.Router();
const User= require('../../Models/User');
const bcrypt = require('bcryptjs');
const keys = require('../../config/keys');
const jwt = require('jsonwebtoken');
//const passport =require ('passport');
router.get('/test', (req,res) =>{
res.json({msg:"This is a user route"});
});
/*router.get("/current", passport.authenticate ("jwt",{session: false}),
(res,req) =>{
res.send(req.user);
}
) */
router.post('/register', (req, res) => {
// Check to make sure nobody has already registered with a duplicate email
User.findOne({ email: req.body.email })
.then(user => {
if (user) {
// Throw a 400 error if the email address already exists
return res.status(400).json({email: "A user has already registered with this address"})
} else {
// Otherwise create a new user
const newUser = new User({
handle: req.body.handle,
email: req.body.email,
password: req.body.password
})
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser.save()
.then(user => res.json(user))
.catch(err => console.log(err));
})
})
}
})
})
router.post('/login', (req,res) =>{
const email= req.body.email;
const password =req.body.password;
User.findOne({email})
.then(user =>{
if(!user){
return res.status(400).json({email:"This email does not exist."});
}
bcrypt.compare(password, user.password)
.then(isMatch =>{
if(isMatch){
const payload ={
id: user.id,
handle:user.handle,
email: user.email
}
jwt.sign(
payload,
keys.secretOrkey,
{expiresin: 3600},
(err,token) => {
res.json({
success: true,
token: "Bearer" + token
});
}
)
} else{
return res.status(400).json({password: "Incorrect password"});
}
})
})
})
module.exports= router;
//app.js
const express = require ('express');
const bodyParser = require('body-parser');
const app= express();
const mongoose = require('mongoose');
const db = require('./config/keys').mongoURI;
const users = require("./routes/api/users");
//const tweets = require("./routes/api/tweets");
const User= require('./Models/User');
mongoose
.connect(db, { useNewUrlParser: true ,useUnifiedTopology: true})
.then(() => console.log("Connected to MongoDB successfully"))
.catch(err => console.log(err));
app.use(bodyParser.urlencoded({
extended: false }));
app.use(bodyParser.json());
app.get('/', (req,res) => {
const user = new User({
handle: user.handle,
email: user.email,
password: user.password
})
user.save()
res.send('Hello world');
});
//middleware
app.use("/api/users", users);
//app.use("/api/tweets", tweets);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server is running on port ${port}`));
//passport.js
const JwtStragety = require ('passport-jwt').Stragety;
const ExtractJwt = require ('passport-jwt').ExtractJwt;
const mongoose = require ('mongoose');
const User =mongoose.model('users');
const keys= require('./keys');
const options ={};
options.jwtFromRequest= ExtractJwt.fromAuthHeaderAsBearerToken();
options.secretOrkey = keys.secretOrkey;
module.exports = passport =>{
passport.use(new JwtStragety (options, (jwt_payload,done) =>{
console.log(jwt_payload);
done();
}) )
}
Hey, have you registered the user before trying to login? Can you please also post the response of that as well?
Also it’s probably easier to understand it if you used service like https://repl.it/ and posted link to it.
@akashrajum7 Yes I registered the user before trying to login.Here is my project repo https://github.com/naima-shk/Twitter-Clone
const express = require ('express');
const bodyParser = require('body-parser');
const app= express();
const mongoose = require('mongoose');
const db = require('./config/keys').mongoURI;
const users = require("./routes/api/users");
//const tweets = require("./routes/api/tweets");
const User= require('./Models/User');
mongoose
.connect(db, { useNewUrlParser: true ,useUnifiedTopology: true})
.then(() => console.log("Connected to MongoDB successfully"))
.catch(err => console.log(err));
app.use(bodyParser.urlencoded({
extended: false }));
app.use(bodyParser.json());
app.get('/', (req,res) => {
const user = new User({
handle: "nimi",
email: "nimi@nimi.nim",
password: "nim1234"
})
user.save()
res.send('Hello world');
});
//middleware
app.use("/api/users", users);
//app.use("/api/tweets", tweets);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server is running on port ${port}`)); ```
Here’s a trick for you to use in future when you have a GitHub repo, you can add box to github in the URL to open it in codesandbox, for example to open your repo in codesandbox, you can do https://githubbox.com/naima-shk/Twitter-Clone/
I am looking at your code and will let you know what’s going wrong.
Okay here’s the first issue I found, in Models/User.js
, you have done
module.exports = User = mongoose.model('User', userSchema);
In order to export mongoose model, you have to first assign it to a variable and then export it as a module. So your code becomes
const User = mongoose.model('User', userSchema);
module.exports = User;
or you can skip this altogether and export the model directly like this
module.exports = mongoose.model("User", userSchema);
Why do you need this piece of code in your /
GET ?
Please fix these two issues and try again, let me know if you face any issues.
I used this piece of code to register the user manually before creating a login route.
@akashrajum7 I removed that piece of code and modify the schema file as well But still it’s not generating a token when i test it on postman.
const express = require ('express');
const bodyParser = require('body-parser');
const app= express();
const mongoose = require('mongoose');
const db = require('./config/keys').mongoURI;
const users = require("./routes/api/users");
//const tweets = require("./routes/api/tweets");
const User= require('./Models/User');
mongoose
.connect(db, { useNewUrlParser: true ,useUnifiedTopology: true})
.then(() => console.log("Connected to MongoDB successfully"))
.catch(err => console.log(err));
app.use(bodyParser.urlencoded({
extended: false }));
app.use(bodyParser.json());
app.get('/', (req,res) => {
res.send('Hello world');
});
//middleware
app.use("/api/users", users);
//app.use("/api/tweets", tweets);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server is running on port ${port}`));
Here are few suggestions I have for you on how you go about debugging in situations like these.
You break down the task into smaller tasks and then test and debug smaller tasks.
For example let’s take registering user as an example.
Test 1 - First make sure /api/user/register is working by commenting out all the code in the handler function and sending a mock response.
Test 2 - If that’s working, then please first try to get user info like email, username and password from the request and send it as a response and check if you are extracting info properly from the request.
Test 3 - if that’s working, now please uncomment the code that creates an user in the database and make a request and check if the user is really getting created in the database.
If all these are working, you can be sure that registeration route is working fine. You can do a similar thing for login.
Please do this and let me know if you have any queries, all the best.
naimiii
January 22, 2021, 9:19am
10
@akashrajum7 The user is already created when i try dummy data in the database before creating a login route but the login route is failing… I don’t know why !!! … I create this document using this code
const user = new User({
handle: "nimi",
email: "nimi@nimi.nim",
password: "nim1234"
})
user.save()
jenovs
January 22, 2021, 6:49pm
11
Remove quotes from values in Postman
naimiii
January 23, 2021, 7:01am
12
@jenovs It is still throwing the same error after removing the quotes
naimiii
January 23, 2021, 9:29am
14
@jenovs Then why it is not working at my end… Maybe I have to signout from this session but coould not find any option to logout. Can you please help?
jenovs
January 23, 2021, 9:41am
15
Try deleting database and restart server.
naimiii
January 23, 2021, 10:04am
16
I tried twice but it did not work for me!! @jenovs
naimiii
January 23, 2021, 10:07am
17
@akashrajum7 Waiting for your reply!
jenovs
January 23, 2021, 10:31am
18
I only changed secret to hardcoded value (because ./config/keys.js
file is gitignored) and mongodb connection url. Everything else is the same.
BTW, you have incorrect token generation logic. It should be:
const token = jwt.sign(payload, 'secret', { expiresIn: 3600 });
res.json({
success: true,
token: 'Bearer ' + token,
});
naimiii
January 23, 2021, 8:49pm
19
@jenovs I just correct the generation logic but it’s still not working at my end.
naimiii
January 23, 2021, 8:59pm
20
Thanks ,Now it’s working fine.