nicholastay / passport-discord

Passport strategy for authentication with Discord (discordapp.com)
ISC License
172 stars 55 forks source link

Successor Package for passport-discord #60

Open bjn7 opened 1 month ago

bjn7 commented 1 month ago

Since you are no longer working on it, I’ve created a new package as a successor to passport-discord: discord-strategy. It would be great if you marked it as successor.

I have added some useful functions. If you need specific data, you can invoke these functions, which will automatically update themselves with the new results.

The doc can be found at https://github.com/bjn7/discord-strategy/README.md

You can also create your own API resolver using a function like this:

function verify(accessToken, refreshToken, profile, done) {
  profile.resolver("guilds", "users/@me/guilds", accessToken, (err) => {
    if (err) return done(err);
    done(null, profile); // Stored in profile[given_key]
  });
}

Here’s a sample code for using this successor package:

const express = require("express");
const passport = require("passport");
const Strategy = require("discord-strategy");

const app = express();

// Define options for the Strategy
const options = {
  clientID: "YOUR_CLIENT_ID",
  clientSecret: "YOUR_CLIENT_SECRET",
  callbackURL: "http://localhost:3000/auth/discord/callback",
  scope: ["identify", "email", "guilds", "connections"], // Example scopes
};

// Create a new instance of the Strategy
passport.use(new Strategy(options, verify));

// Define the verify function
function verify(accessToken, refreshToken, profile, done) {
  profile.connection((err) => {
    if (err) return done(err, false);
    profile.guilds((err) => {
      if (err) return done(err, false);
      console.log("Authentication successful!", profile);
      // Call clean before saving to the database.
      // Since we're not using any other functionalities,
      // there's no need to call clean here.
      done(null, profile);
    });
  });
}

// Initialize Passport
app.use(passport.initialize());

// Define routes
app.get("/auth/discord", passport.authenticate("discord"));

app.get(
  "/auth/discord/callback",
  passport.authenticate("discord", { session: false }),
  (req, res) => {
    res.send(`
      <h1>Authentication successful!</h1>
      <h2>User Profile:</h2>
      <pre>${JSON.stringify(req.user, null, 2)}</pre>
    `);
  }
);

app.listen(3000, () => {
  console.log("Login via http://localhost:3000/auth/discord");
});