Giter Club home page Giter Club logo

passport-reddit's Introduction

Passport-Reddit Build Status Coverage Status

Passport strategy for authenticating with Reddit using the OAuth 2.0 API.

This module lets you authenticate using Reddit in your Node.js applications. By plugging into Passport, Reddit authentication can be easily and unobtrusively integrated into any application or framework that supports Connect-style middleware, including Express.

Install

$ npm install passport-reddit

Usage

Configure Strategy

The Reddit authentication strategy authenticates users using a Reddit account and OAuth 2.0 tokens. The strategy requires a verify callback, which accepts these credentials and calls done providing a user, as well as options specifying a client ID, client secret, and callback URL.

passport.use(new RedditStrategy({
    clientID: REDDIT_CONSUMER_KEY,
    clientSecret: REDDIT_CONSUMER_SECRET,
    callbackURL: "http://127.0.0.1:3000/auth/reddit/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    User.findOrCreate({ redditId: profile.id }, function (err, user) {
      return done(err, user);
    });
  }
));

Authenticate Requests

Use passport.authenticate(), specifying the 'reddit' strategy, to authenticate requests.

For example, as route middleware in an Express application:

app.get('/auth/reddit', function(req, res, next){
  passport.authenticate('reddit', {
    duration: 'permanent',
  })(req, res, next);
});

app.get('/auth/reddit/callback', function(req, res, next){
  passport.authenticate('reddit', {
    successRedirect: '/',
    failureRedirect: '/login'
  })(req, res, next);
});
duration option on authenticate call

This strategy supportsduration option on authenticate call, to request an indefinite authorization as opposed to 1 hour default.
Possible values: permanent and temporary (1 hour).

Defined in the official Reddit OAuth spec

Examples

For a complete, working example, refer to the login example.

Tests

$ npm install --dev
$ make test

Credits

License

The MIT License

Original work Copyright (c) 2012-2013 Jared Hanson <http://jaredhanson.net/>

Modified work Copyright (c) 2013 Dmytro Soltys <http://slotos.net/>

Modified work Copyright (c) 2013 Brian Partridge <http://brianpartridge.com/>

passport-reddit's People

Contributors

abdulhannanali avatar aevange avatar bpartridge83 avatar jaredhanson avatar jihokoo avatar jlei523 avatar slotos avatar zdwolfe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

passport-reddit's Issues

The example code no longer functions at all

the example code does not work with the latest express, it relays on a outdated config methodology and uses services no longer packaged with express. Can you update the example so it works

problem setting duration parameter

according to reddit docs it's possible to specify duration parameter.

I have following code:

app.get('/auth/reddit', function (req, res, next) {
    req.session.state = global.crypto.randomBytes(32)
      .toString('hex');
    global.passport.authenticate('reddit', {
      scope: 'identity',
      duration: 'permanent',
      state: req.session.state
    })(req, res, next);
  });

and duration is not get passed into URL. So I'm always getting message about 1 hour expiration.

If add add that parameter directly into the query everything works fine.

Am I missing something and not setting duration in the correct place?

app has no method 'configure'

npm list express
[email protected] /opt/apps
└── [email protected]

express 4.0 doesn't have a configure method. You can either update package.json to not support version 4. or modify it as indicated here:
http://blog.tompawlak.org/new-features-node-express-4


Here is the error

node app.js

/opt/apps/app.js:55
app.configure(function() {
^
TypeError: Object function (req, res, next) {
app.handle(req, res, next);
} has no method 'configure'
at Object. (/opt/apps/app.js:55:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3

Continual prompting of permission to allow

Each time I log in with Reddit, I am asked to "Allow" my app to permanently login the user:

reddit_auth

My config:

    reddit: {
        clientID: "...",
        clientSecret: "...",
        callbackURL: "http://.../auth/reddit/callback"
    }

My setup:

    passport.use(new RedditStrategy(
        authMethods.reddit,
        function(accessToken, refreshToken, profile, done) {
            process.nextTick(function () {
                return done(null, profile);
            });
        }
    ));

        // ...
        app.get('/auth/reddit', function(req, res, next) {
            req.log({
                network: "reddit"
            }, "social login");
            req.session.state = crypto.randomBytes(32).toString('hex');
            passport.authenticate('reddit', {
                state: req.session.state,
                duration: 'permanent',
            })(req, res, next);
        });

        app.get('/auth/reddit/callback', function(req, res, next) {
            // Check for origin via state token 
            if (req.query.state == req.session.state) {
                passport.authenticate('reddit', {
                    successRedirect: loginSuccessRedirect,
                    failureRedirect: loginFailureRedirect
                })(req, res, next);
            } else {
                res.status(403).send('Forbidden');
            }
        });

If I logout and return to the Reddit auth, I'm prompted again - same with restarting the server.

Versions:

$ node -v; npm -v
v0.10.40
2.13.0

The server is node and express (latest) on Ubuntu 14.04.

Examples and Documented Authorizations are No Longer Accurate

Not sure if this project it still maintained or not. The examples and documentation authorization no longer works. For those of you who've been attempting to use this strategy and receive a bad request response from Reddit be sure you're passing along a state parameter to the strategy. Reddit's OAuth documentation (https://github.com/reddit-archive/reddit/wiki/oauth2) requires a state parameter be passed. This is passed back to the callback to your URL to do with what you'd like. For that reason it can be an arbitrary string.

In practice your strategy can look like this

passport.use(new RedditStrategy({
    clientID: REDDIT_CONSUMER_KEY,
    clientSecret: REDDIT_CONSUMER_SECRET,
    callbackURL: "http://127.0.0.1:3000/auth/reddit/callback",
    state: "someState"
  },
  function(accessToken, refreshToken, profile, done) {
    User.findOrCreate({ redditId: profile.id }, function (err, user) {
      return done(err, user);
    });
  }

I'd suggest the docs and examples be updated as well as the state parameters required.

Duration parameter not showing up in query string

Hey! First off I wanted to say thank you for creating this passport strategy.

I'm not getting the duration parameter on the query string, even when I try to set it manually.

passport.use(new RedditStrategy({
        clientID: KEYS.REDDIT_CONSUMER_KEY,
        clientSecret: KEYS.REDDIT_CONSUMER_SECRET,
        callbackURL: `http://${KEYS.ENV_DEV_HOSTNAME}:${KEYS.ENV_PORT}/auth/reddit/redirect`,
        scope: 'history',
        duration: 'temporary',
        passReqToCallback: true
    },

Generates the following url:

https://ssl.reddit.com/api/v1/authorize?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Freddit%2Fredirect&scope=identity%2Chistory&state=f3613db4a7fde660abf18ecffcc9fe71634ae976b5e020773e496b59250eced4&client_id=***

Thanks in advance for taking a look!

Duration in Strategy configuration

Instead of including the state and duration options on the route handler, can it not be included in the strategy's options? I know it works when setting the state, but it does not for duration.

For example:

passport.use(new RedditStrategy({
    clientID: REDDIT_CONSUMER_KEY,
    clientSecret: REDDIT_CONSUMER_SECRET,
    callbackURL: "http://127.0.0.1:3000/auth/reddit/callback",
    state: "exampleState",        // works
    duration: "permanent"         // does not work
  },
  function(...

refresh_token flow

Hi,

I can't get the refresh_token process to work. My initial authentication works:

req.session.state = utils.randomString(32);
passport.authenticate('reddit', {
  state: req.session.state,
  duration: 'permanent',
  scope: 'read,vote'
})(req, res, next);

Now, I can, say, vote (via an AJAX call from the client) on a reddit link and it works fine. After an hour, the token expires as expected and I get an {error: 401} response when I try to vote. So when this happens I want to go away in the background, update my token using the refresh token, then continue on with the voting call. So I try this (in the callback from the vote request):

if (data.error === 401) {
  req.session.state = utils.randomString(32);
  passport.authenticate('reddit', {
    state: req.session.state,
    refresh_token: refreshToken,
    grant_type: 'refresh_token'
  })(req, res, next);
}

But this tries to redirect the client so I get this error (in the browser console):
XMLHttpRequest cannot load https://ssl.reddit.com/api/v1/authorize?response_type=code&redirect_uri=[my callback url]&scope=identity&client_id=[my client id]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

Please forgive me if this is the wrong place to be asking, I'm not sure if it's an actual issue with passport-reddit or not. I suspect it's me just not understanding something.

Thanks heaps in advance...

logger not bundled with Express 4

node app.js

Error: Most middleware (like logger) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
at Function.Object.defineProperty.get (/opt/apps/prod/spyglass-login/node_modules/express/lib/express.js:89:13)
at Object. (/opt/apps/prod/spyglass-login/app.js:58:19)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3

ES6 module is baaadd :(

Let me take you on a journey....
apu-holding-water

So i bundle my app with babel and webpack and exclude the external modules from the bundle, like it seems to be very common with node-externals.

Webpack bundles in commonjs per default and with externals, it uses require().

Require obviously doesn't work with ESM modules. So i could either tell webpack to import it as type 'import' and enable dynamic import, which then uses import() for it... or change my app to be a module and... or just bundle it.
Which i decided to do, and made an exception for it and all other passport-x modules.

    externals: [
      nodeExternals({
        // passport-reddit is an ESM module
        // bundle it, then we don't have to import it
        allowlist: [ /^passport-/ ],
      }),
    ],

but oh wait, passport-reddit has a:

import { createRequire } from "module"
const version = createRequire(import.meta.url)('../../package.json').version

which webpack doesn't bundle and then it throws errrors on runtime. So i had to change the import to:

import RedditStrategy from 'passport-reddit/lib/passport-reddit/strategy';

to not include that crap.
None of this pain is neccessary for any other passport strategy.

How to use without sessions

If I try to use:

passport.use(new RedditStrategy({
    callbackURL:  myCallback
    clientID: clientID,
    clientSecret: clientSecret,
    state: "test"
}, etc..

passport-reddit throws the error Error: OAuth 2.0 authentication requires session support when using state. Did you forget to use express-session middleware?

I don't use sessions in my server and still would like to not use them, so I would like to manually verify the "state" random string. Is this possible ?

getting an error when trying to use this module V1.1.0

When trying to run my app with this code:

var RedditStrategy = require("passport-reddit").Strategy

passport.use(new RedditStrategy({
    clientID: process.env.REDDIT_CONSUMER_KEY,
    passReqToCallback: true,
    clientSecret: process.env.REDDIT_CONSUMER_SECRET,
    callbackURL: "http://localhost:3000/auth/reddit/callback"
},
    async function (req, token, tokenSecret, profile, done) {....})

I get this error:

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.