Skip to content
Permalink
Browse files

Add service for github authentication

  • Loading branch information...
nlaz committed Feb 26, 2019
1 parent 77ec1f2 commit dc01c030f311ab2eb04ea965db56b3dd6a82cbe5
Showing with 1,740 additions and 22 deletions.
  1. +22 −3 app/controllers/auth.js
  2. +17 −7 app/index.js
  3. +21 −0 app/models/user.js
  4. +1 −1 app/routes.js
  5. +41 −0 app/services/github.js
  6. +7 −1 config/index.js
  7. +8 −5 package.json
  8. +1,623 −5 yarn.lock
@@ -1,17 +1,36 @@
const express = require("express");

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

const router = express.Router();

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

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) {
// TODO
router.get("/callback/github", async function(req, res) {
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;
@@ -1,25 +1,35 @@
const express = require("express");
const bodyParser = require("body-parser");
const compression = require("compression");
const handlebars = require("express-handlebars");
const logger = require("morgan");

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

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

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

// Will attempt to compress responses.
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.set("views", "app/templates");
app.set("view engine", "html");

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

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

app.listen(config.port, () => {
console.log(`🚀 Server started on port ${config.port}.`);
@@ -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;
@@ -10,7 +10,7 @@ module.exports.registerRoutes = app => {
module.exports.registerErrorHandlers = app => {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render("error", {
res.render("500", {
message: err.message,
error: config.env === "development" ? err : {}
});
@@ -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;
@@ -1,4 +1,10 @@
const dotenv = require("dotenv");

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

module.exports = {
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 || ""
};
@@ -3,15 +3,18 @@
"version": "0.1.0",
"description": "A hackathon starting point for new Nodejs applications",
"scripts": {
"start": "node app/index.js",
"deploy": "NODE_ENV=production node app/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
"start": "nodemon app/index.js",
"deploy": "NODE_ENV=production node app/index.js"
},
"dependencies": {
"body-parser": "^1.18.3",
"axios": "^0.18.0",
"compression": "^1.7.3",
"dotenv": "^6.2.0",
"express": "^4.16.4",
"express-handlebars": "^3.0.2"
"express-handlebars": "^3.0.2",
"morgan": "^1.9.1"
},
"devDependencies": {
"nodemon": "^1.18.10"
}
}
Oops, something went wrong.

0 comments on commit dc01c03

Please sign in to comment.
You can’t perform that action at this time.