Skip to content

Commit

Permalink
ADD getDiscordOAuthToken
Browse files Browse the repository at this point in the history
Add utility script to get OAuth token for test user. Use `npm run oauth:discord` to update the .env file.
  • Loading branch information
jpvanoosten committed Aug 26, 2020
1 parent b068484 commit 5ed7e1b
Show file tree
Hide file tree
Showing 5 changed files with 113 additions and 3 deletions.
6 changes: 6 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@
"request": "launch",
"name": "Debug Config Env",
"program": "${workspaceFolder}/utils/configEnv.js"
},
{
"type": "node",
"request": "launch",
"name": "Request Discord OAUth token",
"program": "${workspaceFolder}/utils/getDiscordOAuthToken.js"
}
]
}
1 change: 0 additions & 1 deletion bin/www
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ models.sequelize
/**
* Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
const port = parseInt(val, 10);

Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"main": "./bin/www",
"scripts": {
"configure": "node ./utils/configEnv.js",
"oauth:discord": "node ./utils/getDiscordOAuthToken.js",
"start": "node ./bin/www",
"start:watch": "nodemon ./bin/www",
"test": "jest"
Expand Down Expand Up @@ -47,8 +48,10 @@
"eslint-plugin-prettier": "^3.1.4",
"jest": "^24.9.0",
"nodemon": "^1.19.2",
"open": "^7.2.0",
"prettier": "^2.1.0",
"sequelize-cli": "^5.5.1",
"stoppable": "^1.1.0",
"yargs": "^14.0.0"
}
}
}
1 change: 0 additions & 1 deletion utils/configEnv.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ try {
crypto = require("crypto");
} catch (err) {
console.log("Crypto support is disabled!");
return;
}

function generatePassword(length = 256) {
Expand Down
103 changes: 103 additions & 0 deletions utils/getDiscordOAuthToken.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
require("dotenv").config();
const debug = require("debug")("discord-user-manager:get-oauth-token");
const express = require("express");
const session = require("express-session");
const stoppable = require("stoppable");
const open = require("open");
const fs = require("fs");
const path = require("path");
const passport = require("passport");
const DiscordStrategy = require("passport-discord").Strategy;

/**
* Write the access token to the .env file.
*
* @param token {string} The OAuth access token.
* @param id {string} The ID of the Discord user.
*/
function writeAccessToken(token, id) {
const envFile = path.join(__dirname, "..", ".env");
if (!fs.existsSync(envFile)) {
throw new Error(`${envFile} does not exist. Use utils/confiEnv.js to auto configure the .env file.`);
}

let env = fs.readFileSync(envFile, "utf8");
debug(`Access token: ${token}`);
debug(`Profile ID: ${id}`);

env = env.replace(/^TEST_USER_ACCESS_TOKEN=(.*)$/m, `TEST_USER_ACCESS_TOKEN=${token}`);
env = env.replace(/^TEST_USER_DISCORD_ID=(.*)$/m, `TEST_USER_DISCORD_ID=${id}`);

fs.writeFileSync(envFile, env);

debug(`${envFile} file updated with new access token.`);
}

const app = express();
const port = process.env.PORT || "3000";
app.set("port", port);

passport.serializeUser((user, done) => {
done(null, user);
});

passport.deserializeUser((obj, done) => {
done(null, obj);
});

passport.use(
new DiscordStrategy(
{
clientID: process.env.DISCORD_CLIENT_ID,
clientSecret: process.env.DISCORD_CLIENT_SECRET,
callbackURL: process.env.DISCORD_REDIRECT_URI,
scope: ["identify", "email", "guilds", "guilds.join"],
prompt: "none",
},
(accessToken, refreshToken, profile, done) => {
if (accessToken && profile && profile.id) {
writeAccessToken(accessToken, profile.id);
}
done(null, profile);
}
)
);

app.use(
session({
secret: process.env.SESSION_SECRET,
saveUninitialized: false,
resave: false,
})
);
app.use(passport.initialize());
app.use(passport.session());

app.get("/", passport.authenticate("discord"));
app.get(
"/discord/callback",
passport.authenticate("discord", {
failureRedirect: "/failed",
}),
(req, res) => {
res.redirect("/success"); // Authentication was successfull.
}
);

app.get("/success", (req, res) => {
res.send("Success! You can close this browser window.");
server.stop();
});

app.get("/failed", (req, res) => {
res.send("Something went wrong...");
server.stop();
});

const server = stoppable(
app.listen(port, (err) => {
if (err) return debug(err);
open(`http://localhost:${port}/`);
}),
1000
);

0 comments on commit 5ed7e1b

Please sign in to comment.