Skip to content

Commit

Permalink
organized github auth routes and functions
Browse files Browse the repository at this point in the history
  • Loading branch information
kaxada committed Dec 10, 2023
1 parent 68a5f82 commit ea150d0
Show file tree
Hide file tree
Showing 6 changed files with 88 additions and 92 deletions.
79 changes: 59 additions & 20 deletions src/routes/github.js → authentication/github.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,66 @@
const { Octokit } = require("@octokit/rest");
const axios = require("axios");
const { saveUser } = require("../database/controllers/user.controller.js");
const github_helper = require("../src/helpers/github.js");

const { saveUser } = require("../../database/controllers/user.controller.js");
const github_helper = require("../helpers/github.js");
/**
* Starts the authorization process with the GitHub OAuth system
* @param {*} res Response to send back to the caller
*/
const githubAuth = (req, res) => {
if (!process.env.GITHUB_APP_CLIENT_ID) {
res.status(500).send("GitHub provider is not configured");
return;
}

const scopes = ["user", "repo"];
const url = `https://github.com/login/oauth/authorize?client_id=${
process.env.GITHUB_APP_CLIENT_ID
}&scope=${scopes.join(",")}`;

res.redirect(url);
};

/**
* Calls the GitHub API to get an access token from the OAuth code.
* @param {*} code Code returned by the GitHub OAuth authorization API
* @returns A json object with `access_token` and `errors`
*/
const requestAccessToken = async (code) => {
try {
const {
data: { access_token },
} = await axios.post(
"https://github.com/login/oauth/access_token",
{
client_id: process.env.GITHUB_APP_CLIENT_ID,
client_secret: process.env.GITHUB_APP_CLIENT_SECRET,
code,
},
{
headers: {
Accept: "application/json",
},
}
);

const handleOAuthCallback = async (req, res) => {
return {
access_token,
errors: [],
};
} catch (error) {
return {
access_token: "",
errors: [error.message],
};
}
};

const githubAuthCallback = async (req, res) => {
const code = req.body.code ?? req.query.code;

const { access_token, errors: access_token_errors } =
await github_helper.requestAccessToken(code);
await requestAccessToken(code);
if (access_token_errors.length > 0) {
res.status(500).send(access_token_errors.join());
return;
Expand Down Expand Up @@ -91,21 +144,7 @@ const handleOAuthCallback = async (req, res) => {
}
};

/**
* Sets up the provided Express app routes for GitHub
* @param {*} app Express application instance
*/
const setupGitHubRoutes = (app) => {
if (
process.env.NODE_ENV === "production" ||
process.env.RETURN_JSON_ON_LOGIN
) {
app.post("/api/callback/github", handleOAuthCallback);
} else if (process.env.NODE_ENV === "development") {
app.get("/api/callback/github", handleOAuthCallback);
}
};

module.exports = {
setupGitHubRoutes,
githubAuth,
githubAuthCallback,
};
1 change: 1 addition & 0 deletions database/helpers/dbconnect.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const sequelize = require("./sequelize");

const dbconnect = async () => {
try {
await sequelize.authenticate();
Expand Down
1 change: 0 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const routes = require("./src/routes/index.js");
require("dotenv").config();

const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"precommit": "lint-staged",
"format": "npm run prettier:fix && npm run lint:fix",
"test": "npm run test",
"dev": "NODE_ENV=development node configure.js && nodemon index.js",
"dev": "NODE_ENV=development node configure.js && NODE_ENV=development nodemon index.js",
"start": "NODE_ENV=production node index.js",
"prepare": "husky install",
"build": "webpack"
Expand Down
56 changes: 0 additions & 56 deletions src/helpers/github.js
Original file line number Diff line number Diff line change
@@ -1,62 +1,8 @@
const { Octokit } = require("@octokit/rest");
const axios = require("axios");
const Repo = require("../../database/models/repo.model.js");
const bronzeBadge = require("../badges/bronzeBadge.js");
const mailer = require("../helpers/mailer.js");

/**
* Starts the authorization process with the GitHub OAuth system
* @param {*} res Response to send back to the caller
*/
const authorizeApplication = (res) => {
if (!process.env.GITHUB_APP_CLIENT_ID) {
res.status(500).send("GitHub provider is not configured");
return;
}

const scopes = ["user", "repo"];
const url = `https://github.com/login/oauth/authorize?client_id=${
process.env.GITHUB_APP_CLIENT_ID
}&scope=${scopes.join(",")}`;

res.redirect(url);
};

/**
* Calls the GitHub API to get an access token from the OAuth code.
* @param {*} code Code returned by the GitHub OAuth authorization API
* @returns A json object with `access_token` and `errors`
*/
const requestAccessToken = async (code) => {
try {
const {
data: { access_token },
} = await axios.post(
"https://github.com/login/oauth/access_token",
{
client_id: process.env.GITHUB_APP_CLIENT_ID,
client_secret: process.env.GITHUB_APP_CLIENT_SECRET,
code,
},
{
headers: {
Accept: "application/json",
},
}
);

return {
access_token,
errors: [],
};
} catch (error) {
return {
access_token: "",
errors: [error.message],
};
}
};

/**
* Calls the GitHub API to get the user info.
* @param {*} octokit Octokit instance with autorization already set up
Expand Down Expand Up @@ -281,8 +227,6 @@ const scanRepositories = async (userId, name, email, repositoryIds) => {
};

module.exports = {
authorizeApplication,
requestAccessToken,
getUserInfo,
getUserRepositories,
scanRepositories,
Expand Down
41 changes: 27 additions & 14 deletions src/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,30 @@
const { findUser } = require("../../database/controllers/user.controller.js");
const Repo = require("../../database/models/repo.model.js");
const github_helpers = require("../helpers/github.js");
const github_routes = require("./github.js");
const {
githubAuth,
githubAuthCallback,
} = require("../../authentication/github.js");
const gitlab_helpers = require("../helpers/gitlab.js");
const gitlab_routes = require("./gitlab.js");

/**
* Redirects the user to the GitHub OAuth login page for authentication.
* Redirects the user to the OAuth login pages for authentication.
* @param {*} req - object containing the client req details.
* @param {*} res - object used to send a redirect response.
*/
const login = (req, res) => {
const provider = req.query.provider;

if (provider === "github") {
github_helpers.authorizeApplication(res);
} else if (provider === "gitlab") {
gitlab_helpers.authorizeApplication(res);
} else {
res.status(400).send(`Unknown provider: ${provider}`);
}
};
// const login = (req, res) => {
// const provider = req.query.provider;

// if (provider === "github") {
// github_helpers.authorizeApplication(res);
// } else if (provider === "gitlab") {
// gitlab_helpers.authorizeApplication(res);
// } else {
// res.status(400).send(`Unknown provider: ${provider}`);
// }
// };

const reposToBadge = async (req, res) => {
const selectedRepos = (await req.body.repos) || [];
Expand Down Expand Up @@ -97,11 +101,20 @@ const badgedRepos = async (req, res) => {
};

const setupRoutes = (app) => {
app.get("/api/login", login);
// logins
app.get("/api/auth/github", (req, res) => {
githubAuth(req, res);
});

//redirects
app.get("/api/callback/github", (req, res) => {
githubAuthCallback(req, res);
});

app.get("/api/badgedRepos", badgedRepos);
app.post("/api/repos-to-badge", reposToBadge);

github_routes.setupGitHubRoutes(app);
// github_routes.setupGitHubRoutes(app);
gitlab_routes.setupGitLabRoutes(app);
};

Expand Down

0 comments on commit ea150d0

Please sign in to comment.