ealeksandrov / nodeapi Goto Github PK
View Code? Open in Web Editor NEWSimple RESTful API implementation on Node.js + MongoDB.
License: MIT License
Simple RESTful API implementation on Node.js + MongoDB.
License: MIT License
Hello, when I want to create a new user by changing the values in generateData.js file, our initial user is invalidated. New user also does not work.
Which parameters should we change to create more user in the application?
Shouldn't the basic auth verify function look something like this instead of the current implementation?
passport.use(new BasicStrategy(
function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) {
return done(err);
}
if (!user || !user.checkPassword(password)) {
return done(null, false);
}
return done(null, user);
});
}
));
Current implemenation:
passport.use(new BasicStrategy(
function(username, password, done) {
Client.findOne({ clientId: username }, function(err, client) {
if (err) {
return done(err);
}
if (!client) {
return done(null, false);
}
if (client.clientSecret !== password) {
return done(null, false);
}
return done(null, client);
});
}
));
First, many thanks for this example code--extremely helpful!
I noticed a minor error here in the code which exchanges a refresh token for a new access token:
https://github.com/ealeksandrov/NodeAPI/blob/master/libs/oauth2.js#L48-L49
Those two lines are duplicates. Perhaps in the second one you meant to verify that the refresh token's client ID matches the client ID of the caller? For example:
if (token.clientId !== client.clientId) {
return done(null, false);
}
Great example!
How do you log off? I used this code but it doesn't work.
router.post('/logoff', passport.authenticate('bearer', { session: false }),
function(req, res) {
req.logout();
return res.send({ authenticated: req.isAuthenticated() });
}
);
When a token overdue,server response Unauthorized. Can i change the response text? How to modify?thank you
this is my host
http://localhost:1337/api/oauth/token?grant_type=password&client_id=android&client_secret=SomeRandomCharsAndNumbers123
and username is myapi
password is abc1234
but when I post ,return 401,why?
I am an iOS developer. I refer your example to grant the user to be able to access my api. I have register and login apis. However, in register phase, a user only provides username and password. So how can I generate a clientId and clientSecret for my iOS app? Thank you.
I used the Docker setup (not the manual setup) as stated in the readme then I used
http POST http://localhost:1337/api/oauth/token grant_type=password client_id=android client_secret=SomeRandomCharsAndNumbers username=myapi password=abc1234
but received
http: error: Request timed out (30s).
and also tried using Postman like in here #32 but stays on "sending request" status.
Has anyone come across this issue using the Docker setup?
In the below code even if I throw custom message for token expiry, it only sends 'Unauthorized' message instead of 'Token Expired'.
return done(null, false, { message: 'Token expired' });
passport.use(new BearerStrategy(
function(accessToken, done) {
AccessToken.findOne({ token: accessToken }, function(err, token) {
if (err) {
return done(err);
}
if (!token) {
return done(null, false);
}
if( Math.round((Date.now()-token.created)/1000) > config.get('security:tokenLife') ) {
AccessToken.remove({ token: accessToken }, function (err) {
if (err) {
return done(err);
}
});
return done(null, false, { message: 'Token expired' });
}
User.findById(token.userId, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: 'Unknown user' });
}
var info = { scope: '*' };
done(null, user, info);
});
});
}
));
mongodb
in NodeAPI
? Not sql
mongodb
?What is the type of license your project uses ? It seems you have not included the type of the license.
when i hit these api in postman it asks username and password http://localhost:1337/api/oauth/token grant_type=password client_id=android client_secret=SomeRandomCharsAndNumbers username=myapi password=abc1234
Hello ealeksandrov,
Firstly, I thank you for excellent blog on implementing OAuth server in combo with passport-local, If I go with this strategy :
1)How can I work around for logout functionality, traditionally logout means either of user sessions or cookie object would be deleted/destroyed , which can be built again easily. But here as I authentication API endpoints using access token generated , can I consider OAuth access token revoke to achieve logout functionality , whether my analogy was correct?? Please suggest a better process if i'm wrong ??
Regards,
Sai.
Hi,
Thanks a lot! This is the best example for me to understand a RESTful API with tokens.
Just wondering - How would you extend this to include Facebook/Google Login?
Thanks
Tarush
As far as I see, there's no ability to sign up through API. Accounts are created with dataGen.js.
Is it correct to add route like this:
/api/sign_up/
so that clients can create accounts themselves?
When I run bin/www,I got:
1、[Error: Cannot find module '../build/browser_build/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
2、TypeError: Cannot read property 'length' of undefined
at processResults (/project/Nodejs/node_modules/express/express_project/TheOpenSourceNodeAPI/NodeAPI-master/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1581:31)
Thanks for this amazing example.It helped me a great deal.
Is there any way we can authenticate a client (not a user) against the authorization server?
Hi,
I've tried this implementation and works fine but is a good secure way to implement the Oauth2 authentication nowadays?
Sorry I'm noob on this and I'm looking for a secure way to do this.
Thanks
I like your api integration framework for oauth2 and i use it.. But i want also api documentation hopefully they have some code to ingtegrate swagger docs and the security #of oauth2 integration in swagger docs automatically..
Hi,
I am having trouble using the tokens created.
I have cloned the repo and have the following issues.
This works fine
http POST http://localhost:1337/api/oauth/token grant_type=password client_id=android client_secret=SomeRandomCharsAndNumbers username=myapi password=abc1234
http POST http://localhost:1337/api/oauth/token grant_type=refresh_token client_id=android client_secret=SomeRandomCharsAndNumbers refresh_token=[TOKEN]
(above the token is send in the body)
The following gives me an:
{
"error": "Validation error"
}
http POST http://localhost:1337/api/articles title=NewArticle author='John Doe' description='Lorem ipsum dolar sit amet' images:='[{"kind":"thumbnail", "url":"http://habrahabr.ru/images/write-topic.png"}, {"kind":"detail", "url":"http://habrahabr.ru/images/write-topic.png"}]' Authorization:'Bearer PUT_YOUR_TOKEN_HERE'
http PUT http://localhost:1337/api/articles/YOUR_ARTICLE_ID_HERE title=NewArticleUpdated author='John Doe' description='Lorem ipsum dolar sit amet' images:='[{"kind":"thumbnail", "url":"http://habrahabr.ru/images/write-topic.png"}, {"kind":"detail", "url":"http://habrahabr.ru/images/write-topic.png"}]' Authorization:'Bearer PUT_YOUR_TOKEN_HERE'
(here the token is sent in the header)
I am using postman and have the the post in a x-www-form-urlencoded body and the token ind the header with the Key: "Authorization" and the value: "Bearer fac4e8eeb862fe92c130ac872bd236b91d9d151f563b5f66033cd34e5edc4ea0"
I have also tried without Bearer in front of the token and with the token in the body, and with both the access token and refresh token.
What am I doing wrong?
I been hard integrate manually about ACL much better if have basic also in unit test
I've been working on a simple but powerful library (https://github.com/diegohaz/querymen) to parse querystrings to MongoDB queries. Converting, for example, /articles?page=2&limit=20
to {limit: 20, skip: 20}
and other stuff.
I used NodeAPI before and miss this kind of feature. Please, consider adding this or some other library to add this functionality. 😊
Hi,
Great tutorial 👍
Do you have any suggestions on how to use your implementation of oauth2 with socket.io ?
I saw a lot of passport/socket.io using passport session (such as this one) but none of them was implemented the way you do.
Thanks !
It would be great to be able to use this repo as a template to create a new repo on GitHub.
Do you think this could be a possibility?
node bin/www
##############################################################
#
# !!! MONGOOSE WARNING !!!
#
# This is an UNSTABLE release of Mongoose.
# Unstable releases are available for preview/testing only.
# DO NOT run this in production.
#
##############################################################
info: [bin/www] Express server listening on port 1337
info: [db/mongoose.js] Connected to DB!
/Users/sergiu/SrgSolutions/NodeAPI/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js:246
throw message;
^
TypeError: Cannot read property 'length' of undefined
at processResults (/Users/sergiu/SrgSolutions/NodeAPI/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1581:31)
at /Users/sergiu/SrgSolutions/NodeAPI/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1619:20
at /Users/sergiu/SrgSolutions/NodeAPI/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1157:7
at /Users/sergiu/SrgSolutions/NodeAPI/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1890:9
at Server.Base._callHandler (/Users/sergiu/SrgSolutions/NodeAPI/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js:448:41)
at /Users/sergiu/SrgSolutions/NodeAPI/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:481:18
at MongoReply.parseBody (/Users/sergiu/SrgSolutions/NodeAPI/node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5)
at null.<anonymous> (/Users/sergiu/SrgSolutions/NodeAPI/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:439:20)
at emit (events.js:107:17)
at null.<anonymous> (/Users/sergiu/SrgSolutions/NodeAPI/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:201:13)
TypeError: undefined is not a function
at Promise. (/Users/apple/Web/gottago/controllers/oauth2.js:40:3)
at Promise. (/Users/apple/Web/gottago/node_modules/mongoose/node_modules/mpromise/lib/promise.js:177:8)
at Promise.EventEmitter.emit (events.js:98:17)
at Promise.emit (/Users/apple/Web/gottago/node_modules/mongoose/node_modules/mpromise/lib/promise.js:84:38)
at Promise.fulfill (/Users/apple/Web/gottago/node_modules/mongoose/node_modules/mpromise/lib/promise.js:97:20)
at handleSave (/Users/apple/Web/gottago/node_modules/mongoose/lib/model.js:132:13)
at /Users/apple/Web/gottago/node_modules/mongoose/lib/utils.js:408:16
at /Users/apple/Web/gottago/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/core.js:123:9
at /Users/apple/Web/gottago/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1131:7
at /Users/apple/Web/gottago/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1847:9
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.