I am starting a CodeLab Series in which I will building something cool and sharing with the community.
Today, We are going to implement Authentica...
For further actions, you may consider blocking this person and/or reporting abuse
I cannot get the test for the signup step to work in postman. I get errors for username, email and password. I have copied exactly what is in the github repo. It is also not adding an entry to the DB.
Old comment, but...
In Postman, go to the 'Headers' tab and set the 'Content-Type' value to 'application/json', by default it sends 'x-www-form-urlencoded'
I was getting the same error. i fixed it by adding
under
index.js ends up looking like this:
I have the same issue "cannot get" I think that everything is well configured in postman and I add this lines suggested but still it didn't work... and I'm testing with the original repo I can connect to my db but I can't get anything with submit
Did you add/replace your username password in MongoURI ?
Yes, it is not a DB connection issue. No errors on the console.
Try running the GitHub clone with your Db username password.
How do you now connect it to a frontend login/signup page?
Hi Eugene,
You can simply call the API using axios or fetch to get data.
Here is a sample code snippet on how you can do it.
I hope this answers your question.
It does, thanks!
Eugene, could you paste the full code oh how to link front end and back end and specify where it should be added
Fantastic article. Covered all major topics - Sign up, Login, Authentication using JWT, MongoDB through this app.
Here are few changes that I had to do as
mLab
is now part of MongoDB family.MongoURI
in the code (config/db.js
)routes/user.js
file, I had to add this line at the end of file.Hope this will help someone like me 😉
Yes, you are right! thanks for sharing !!
This is the process for new users.
POST localhost:3000/undefined/user/regi... 404 (Not Found)
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:61
Axios. @ Axios.js:86
wrap @ bind.js:9
sendDetailsToServer @ RegistrationForm.js:28
handleSubmitClick @ RegistrationForm.js:61
callCallback @ react-dom.development.js:188
invokeGuardedCallbackDev @ react-dom.development.js:237
invokeGuardedCallback @ react-dom.development.js:292
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:306
executeDispatch @ react-dom.development.js:389
executeDispatchesInOrder @ react-dom.development.js:414
executeDispatchesAndRelease @ react-dom.development.js:3278
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:3287
forEachAccumulated @ react-dom.development.js:3259
runEventsInBatch @ react-dom.development.js:3304
runExtractedPluginEventsInBatch @ react-dom.development.js:3514
handleTopLevel @ react-dom.development.js:3558
batchedEventUpdates$1 @ react-dom.development.js:21871
batchedEventUpdates @ react-dom.development.js:795
dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3568
attemptToDispatchEvent @ react-dom.development.js:4267
dispatchEvent @ react-dom.development.js:4189
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
discreteUpdates$1 @ react-dom.development.js:21887
discreteUpdates @ react-dom.development.js:806
dispatchDiscreteEvent @ react-dom.development.js:4168
RegistrationForm.js:43 Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)
HELP ME OUT!
sIGNUP , LOGIN BUTTONS ARENT WORKING .They are showing this error
:):):):):):):):):):):):):):)
i stiill didnt get to know on how you connected front and backend.plz let me now
It's really going to ,cause am having a hard creating the URI from mLab thanks.
Really great article. On the last step in the user.js file I didn't see mentioned to import
const auth = require("./../middleware/auth");
I really just wanted to say thank you for this straight forward step by step tutorial.
Yeah he totally mised that
Nice article, quick and properly demonstrated. just one note. below "secret" is used for token, instead of 'randomString'.
jwt.sign(
payload,
"secret",
{
expiresIn: 3600
},
(err, token) => {
if (err) throw err;
res.status(200).json({
token
});
}
);
Thanks for correcting. I have updated in the code !
Did you just do it in the repo? The blog entry is still showing the previous i believe. The thing is in signup you are using "randomString" whereas in login you are using "secret". The middleware is using "secret" so maybe making all those consistent, or even better moving it to a environment variable, would be better.
Apart from that, lovely blog entry! Thanks!
Thanks @andres for feedback. I have just updated it in the blog post also.
Thank you for the article!
It is better to have one error message
User not exists or Incorrect password
instead of two different because of security.I suggest you to add login brute-force protection with rate-limiter-flexible package. You can read more here
Love the blog, I learned so much.
Will there be a part 2 showing how to use the JWT token to navigate through private pages, such as the user's edit page? I know there's resources out there that show how to do it, but I like your style of code!
Yes, definitely I am writing a series of articles on these.
Feel free to subscribe to get an instant update when I post the blog.
dipakkr.substack.com
Thanks a lot ! I am glad you liked the post.
This article is absolutely fantastic and very timely for me. Everything worked perfectly. I did want to point out one thing in the "/me" function that was confusing but I figured it out. Quick notes in case the screenshot doesn't update:
@method - POST should be GET in the "/me" function (minor typo)
A screenshot should be provided to show the const auth = require()... being added to the top of the script so we know where that "auth" came from.
Instead of saying "Now, ...", which seems like it's about to come up (but doesn't), it would be better to say "As you can see, we added the auth middleware as a parameter in the get function...". I was confused since the const auth was not shown and on first view I missed the "auth" in the get "/me" function since the "Now, " made me think it was coming up. Stupid mistake on my part but I think the combination of these 2 things made for some confusion.
Hi Arion,
I really appreciate your reply and the time you took to write such great feedback.
I am absolutely overwhelmed. I have done the required changes. .
Thanks a lot and wish you a very happy new year!
Would anyone be able to help me?
Looking to try and convert the email to all lowercase before it gets posted to the database within the signin and then convert to lowercase before it gets compared on login?
Thanks
In JavaScript to convert a string to lowercase you can string method 'toLowerCase()'
I hope it answers your question.
Thanks for the response,
I have managed to figure this out.
Just as simple as adding a Constraint into the model for
Lowercase: true
I noticed that we need to "await" on the existing user check before saving the new user. If I'm not mistaken, it would be possible for 2 identical request to "await" at this line at the same time, then both allowed to proceed to save duplicate users.
Any recommended way around this?
Anyways, thanks for article - learned a lot :)
Thank you so much for your article. Really helped me.
I just faced a error with auth middleware:
The error comes from
If you are using x-www-form-urlencoded you can get the params with req.body
Same is you send a json object from raw instead of x-www-form-urlencoded
Did you manage to fix this? getting same error
I am getting the following error.
Error: Illegal arguments: undefined, undefined
at _async (/home/tarun/Projects/extra/node-auth/node_modules/bcryptjs/dist/bcrypt.js:286:46)
at /home/tarun/Projects/extra/node-auth/node_modules/bcryptjs/dist/bcrypt.js:307:17
at new Promise (<anonymous>)
at Object.bcrypt.compare (/home/tarun/Projects/extra/node-auth/node_modules/bcryptjs/dist/bcrypt.js:306:20)
at router.post (/home/tarun/Projects/extra/node-auth/routes/user.js:117:36)
at process._tickCallback (internal/process/next_tick.js:68:7)
Can you please help me here ?
Can you also show me how to write logout API?
Nice intro, I went throught the code and there's one little mistake. You did not export the router after defining the signup route
hello Clement, am having a challenge connecting this backend to my html front end , can you write the syntax.
Thanks for appreciation !!
Sorry, I might have forgot. I will fix it asap.
You missed the name of the user file when you are creating the '/me' route, this supossed to be in user, also, if you are using a middleware you should explain to the rookies how to use this module, you are ecporting the middleware but didin't explain how to use it.
TypeError: Cannot read property 'id' of null.
I am getting the above error while signup. Infact, the data is saving in mongoDB but it is returning error status 500.Below is where there is problem with the code i think so.Tried many solution but none is working Please help to resolve this.
const payload = {
user: {
id: user.id
}
};
Hello! I am trying to built an app with a platform login which is connect with mongodb cluster. so, I changed the MongoUri with connection link with my cluster but I have this message to the terminal screen.
dev-to-uploads.s3.amazonaws.com/i/...
dev-to-uploads.s3.amazonaws.com/i/...
is problem that there is not server.js file?
Do i have to add something in Json?
I read so many hours and there is noone to help.
Sorry for my "English writting".
Thanks for the amazing explanation, I tried this with similar code as you type. But I got a 404 response error when testing the API from google chrome. I tried looking for some solving problems in StackOverflow but didn't work. Do you have any idea what is the reason?
Hey, I was able to sign up and log in but when I try to go to /me, I get an error like this: {"message":"Auth Error"}
please help!!
EDIT: this was a mistake on my part, i forgot to add token to the header! Great tutorial, thank you so much. I'd love to see you making a tutorial on how to connect it to a front end (Angular would be nice haha!)
Nice! I just started learning Node.js this wknd.
I hope it's helps !
Thanks, it does!
Hello excellent tuto bravo à vous mais concernant le test de connexion de recuperation de "me" postman ne sort rien comme resultat aussi j'ai pas d'erreur j'ai recommencer en creant un autre user/signup mais quand je lance c'et la meme chose rien ne sort i need help
I realize this is an older post, but this might help some people who stumbled on it, as it really is a very good guide. If you're stuck at the first signup tests you probably just need to remove some deprecated config flags in your mongo connection. You can remove the whole config, as all of those flags are now implied in later versions and explicitly calling them seems to cause problems. I'm referring to this in the mongoose.connect: {
useNewUrlParser: true
}
Just remove it and it should connect. Took me way too long to find that.
Great Bro!
Thanks a lot !
Thank you for posting this! I am working on an application that will use a very similar stack :D Good timing!
Why do this yourself? Just use AWS Cognito. You should never use that sort of DIY stuff really. Use this as a learning tool instead.
Yeah its help me, I am tring to understand authencation for very long time, I read so many article but unable to understand. You make my day, its vey simple... keep posting article like this.. -:)
json web token invalid how can i resolve this error /
JsonWebTokenError: invalid signature
at C:\Users\shiva\Documents\mongotut\node_modules\jsonwebtoken\verify.js:133:19
at getSecret (C:\Users\shiva\Documents\mongotut\node_modules\jsonwebtoken\verify.js:90:14)
at Object.module.exports as verify
at module.exports (C:\Users\shiva\Documents\mongotut\controllers\auth.js:10:21)
at Layer.handle as handle_request
at next (C:\Users\shiva\Documents\mongotut\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\shiva\Documents\mongotut\node_modules\express\lib\router\route.js:112:3)
at Layer.handle as handle_request
at C:\Users\shiva\Documents\mongotut\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\shiva\Documents\mongotut\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\shiva\Documents\mongotut\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\shiva\Documents\mongotut\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\shiva\Documents\mongotut\node_modules\express\lib\router\index.js:47:12)
at Layer.handle as handle_request
at trim_prefix (C:\Users\shiva\Documents\mongotut\node_modules\express\lib\router\index.js:317:13)
at C:\Users\shiva\Documents\mongotut\node_modules\express\lib\router\index.js:284:7
Thanks Man nice article !
cant i use the same routes thats created already? because it seems not to creating on my vs.code.
Would this be easy to implement into a previous project using MongoDB, Node, and Express?
WOW!! Thank you for this great article
Thanks ! Glad you like it !
Hii I'm ok with token part but i want to send all the user info except password along with the token. how can i do that?
Is there a part 2 to this article?
Very nice article and well written.
You covered basically everything .
Good post
woowwww
I loved everything but /me api is gving auth error to me . Can you please help. Also the token is changing every time ,What is reason behind it ?
Hey Vivek,
you need to require auth from the middleware folder in your user.js file:
How do i connect this to front end? I have successfully connected the login and signup page but the user/me gives me "Auth Error". Looking for an answer. Thanks in advance.
Has there been any thought put in to how a log out function would look in this?
Great article! I was able to get the code up and running in no time :)
Hey great post, how you do it to logout the user?
Thanks a lot! I use Atlas instead of mLab.
hii I'm ok with the jwt part but now I want send all the user info except password from the server so how can I do that