node-restful icon indicating copy to clipboard operation
node-restful copied to clipboard

node-restful with passportjs

Open sandeepraju opened this issue 9 years ago • 3 comments

Hi @baugarten, Is there a way to use node-restful easily with passport.js.

Any examples?

sandeepraju avatar Apr 10 '16 03:04 sandeepraju

I don't have any examples, but...

Resource.route('login', 'post', passport.authenticate('local', { successRedirect: '/',
                                                    failureRedirect: '/login' }));
Resource.route('login_facebook', 'post', passport.authenticate('facebook'));

etc.

passport.authenticate(...) just returns a function(req, res, next) { ... } which should work with node-restful (i.e. node-restful does nothing that would prevent this from working), though tbh I have not tested this

baugarten avatar Apr 17 '16 20:04 baugarten

For some reason this structure refused to work for me. The error wasn't really explicit and was happening somewhere after passport returned a success. Possibly cause i didn't pass some value to something while requiring a route, though i haven't tested it further. But i've managed to get it working in a slightly different way. I'll leave the workaround below in case anyone would have a similar problem.

//./app.js

app.use('/api', require('./routes/api'));
// you could also chain middleware if you need to just secure all requests on the api route
// app.use('/api', passport.authenticate('basic', { session: false, failureRedirect: '/unauthorised' }), require('./routes/api'));

//./routes/api.js

var router = express.Router();
var Posts = require('../models/posts') //restful.model('posts', postsSchema);
Posts.methods(['get', 'post']);
router.post('/posts', passport.authenticate('basic', { session: false, failureRedirect: '/unauthorised' }));
Posts.register(router, '/posts');
module.exports = router;

Keep in mind though, that i'm really new to this, so i don't sure if there is no drawbacks in doing it this way. But basically what i think is happening is we're introducing passport and node-restful as separate middlewares to express router. And those shouldn't really care about each other as long as both are working by themselves.

keithriver avatar Nov 25 '16 02:11 keithriver

This is alternative way

// first list your routes that doesn't require authentication
// route.get , or x.register, etc ...

// then use router.all and with Passport.authenticate middleware function,
// it will require authentication for any following registered routes
router.all('*', Passport.authenticate('basic', { session: false }));

//then list your routes that require authentication
Posts.register(router, '/posts');
/// ....

abou-emish avatar Apr 27 '17 21:04 abou-emish