Skip to content

Commit

Permalink
Add service for github authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
nlaz committed Feb 26, 2019
1 parent 77ec1f2 commit dc01c03
Show file tree
Hide file tree
Showing 8 changed files with 1,740 additions and 22 deletions.
25 changes: 22 additions & 3 deletions app/controllers/auth.js
@@ -1,17 +1,36 @@
const express = require("express"); const express = require("express");


const config = require("../../config");
const User = require("../models/user");
const GitHub = require("../services/github");

const router = express.Router(); const router = express.Router();


router.get("/logout", function(req, res) { router.get("/logout", function(req, res) {
// TODO // TODO
}); });


router.get("/login/github", function(req, res) { router.get("/login/github", function(req, res) {
// TODO const github = new GitHub(config.githubClientId, config.githubClientSecret);
res.redirect(github.authorization_url("public_repo"));
}); });


router.get("/callback/github", function(req, res) { router.get("/callback/github", async function(req, res) {
// TODO if (!req.query.code) {
return res.render("500");
}

// Fetch user from GitHub OAuth and store in session
const github = new GitHub(config.githubClientId, config.githubClientSecret);
const access_token = await github.get_token(req.query.code);

if (!access_token) {
return res.render("404");
}

const user = User.find_or_create_from_token(access_token);

return res.redirect("/");
}); });


module.exports = router; module.exports = router;
24 changes: 17 additions & 7 deletions app/index.js
@@ -1,25 +1,35 @@
const express = require("express"); const express = require("express");
const bodyParser = require("body-parser");
const compression = require("compression"); const compression = require("compression");
const handlebars = require("express-handlebars"); const handlebars = require("express-handlebars");
const logger = require("morgan");


const config = require("../config"); const config = require("../config");
const paths = require("../config/paths"); const paths = require("../config/paths");
const { registerRoutes, registerErrorHandlers } = require("./routes"); const routes = require("./routes");


// Set up the express app
const app = express(); const app = express();


// Log requests to the console.
app.use(logger("dev"));

// Will attempt to compress responses.
app.use(compression()); app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(paths.staticEntry));


// Parse incoming requests data.
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Set up handlebars templating engine for layout files.
app.engine("html", handlebars({ defaultLayout: "layout", extname: ".html" })); app.engine("html", handlebars({ defaultLayout: "layout", extname: ".html" }));
app.set("views", "app/templates"); app.set("views", "app/templates");
app.set("view engine", "html"); app.set("view engine", "html");


registerRoutes(app); // Set up the routes for the static assets.
// registerErrorHandlers(app); app.use(express.static(paths.staticEntry));

routes.registerRoutes(app);
routes.registerErrorHandlers(app);


app.listen(config.port, () => { app.listen(config.port, () => {
console.log(`🚀 Server started on port ${config.port}.`); console.log(`🚀 Server started on port ${config.port}.`);
Expand Down
21 changes: 21 additions & 0 deletions app/models/user.js
@@ -0,0 +1,21 @@
const GitHub = require("../services/github");

class User {
constructor(username, avatar_url, github_id) {
this.username = username;
this.avatar_url = avatar_url;
this.github_id = github_id;
}

static async find_or_create_from_token(access_token) {
try {
const data = await GitHub.get_user_from_token(access_token);
} catch (error) {
console.log("ERROR", error);
}

/* Find existing user or create new User instances */
}
}

module.exports = User;
2 changes: 1 addition & 1 deletion app/routes.js
Expand Up @@ -10,7 +10,7 @@ module.exports.registerRoutes = app => {
module.exports.registerErrorHandlers = app => { module.exports.registerErrorHandlers = app => {
app.use(function(err, req, res, next) { app.use(function(err, req, res, next) {
res.status(err.status || 500); res.status(err.status || 500);
res.render("error", { res.render("500", {
message: err.message, message: err.message,
error: config.env === "development" ? err : {} error: config.env === "development" ? err : {}
}); });
Expand Down
41 changes: 41 additions & 0 deletions app/services/github.js
@@ -0,0 +1,41 @@
const axios = require("axios");

const api_url = "https://api.github.com";
const authorize_url = "https://github.com/login/oauth/authorize";
const token_url = "https://github.com/login/oauth/access_token";

class GitHub {
constructor(client_id = "", client_secret = "", access_token = "") {
this.client_id = client_id;
this.client_secret = client_secret;
this.access_token = access_token;
}

authorization_url(scope = "") {
return `${authorize_url}?client_id=${this.client_id}&client_secret=${this.client_secret}&scope=${scope}`;
}

async get_token(code) {
/* Fetch GitHub Access Token for GitHub OAuth */
const config = { headers: { Accept: "application/json" } };
const params = {
code,
client_id: this.client_id,
client_secret: this.client_secret
};

const { data } = await axios.post(token_url, params, config);
return data.access_token;
}

static async get_user_from_token(access_token) {
/* Fetch user data using the access token. */
const url = api_url + "/user";
const config = { params: { access_token: access_token } };

const response = await axios.get(url, config);
return response.data;
}
}

module.exports = GitHub;
8 changes: 7 additions & 1 deletion config/index.js
@@ -1,4 +1,10 @@
const dotenv = require("dotenv");

dotenv.config({ path: ".env" });

module.exports = { module.exports = {
port: process.env.PORT || 5000, port: process.env.PORT || 5000,
env: process.env.NODE_ENV || "development" env: process.env.NODE_ENV || "development",
githubClientId: process.env.GITHUB_CLIENT_ID || "",
githubClientSecret: process.env.GITHUB_CLIENT_SECRET || ""
}; };
13 changes: 8 additions & 5 deletions package.json
Expand Up @@ -3,15 +3,18 @@
"version": "0.1.0", "version": "0.1.0",
"description": "A hackathon starting point for new Nodejs applications", "description": "A hackathon starting point for new Nodejs applications",
"scripts": { "scripts": {
"start": "node app/index.js", "start": "nodemon app/index.js",
"deploy": "NODE_ENV=production node app/index.js", "deploy": "NODE_ENV=production node app/index.js"
"test": "echo \"Error: no test specified\" && exit 1"
}, },
"dependencies": { "dependencies": {
"body-parser": "^1.18.3", "axios": "^0.18.0",
"compression": "^1.7.3", "compression": "^1.7.3",
"dotenv": "^6.2.0", "dotenv": "^6.2.0",
"express": "^4.16.4", "express": "^4.16.4",
"express-handlebars": "^3.0.2" "express-handlebars": "^3.0.2",
"morgan": "^1.9.1"
},
"devDependencies": {
"nodemon": "^1.18.10"
} }
} }

0 comments on commit dc01c03

Please sign in to comment.