Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the firebase site framework to carbon-lang. #9

Merged
merged 3 commits into from
May 6, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions firebase/.firebaserc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"projects": {
"default": "carbon-language"
}
}
68 changes: 68 additions & 0 deletions firebase/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
firebase-debug.log*

# Firebase cache
.firebase/

# Firebase config

# Uncomment this if you'd like others to create their own Firebase project.
# For a team working on the same Firebase project(s), it is recommended to leave
# it commented so all members can deploy to the same project(s) in .firebaserc.
# .firebaserc

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

# npm package-lock
package-lock.json
1 change: 1 addition & 0 deletions firebase/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
4 changes: 4 additions & 0 deletions firebase/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Generated documentation goes to a minimal site at carbon-lang.dev.

This is the framework for that site, including authorization. Only
carbon-language members should be able to access the site.
16 changes: 16 additions & 0 deletions firebase/firebase.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"hosting": {
"public": "public",
"rewrites": [
{
"source":"**/*",
"function":"site"
}
],
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}
1 change: 1 addition & 0 deletions firebase/functions/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
84 changes: 84 additions & 0 deletions firebase/functions/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Part of the Carbon Language, under the Apache License v2.0 with LLVM
EricWF marked this conversation as resolved.
Show resolved Hide resolved
// Exceptions.
// See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const express = require('express');
const cookieParser = require('cookie-parser')();
const cors = require('cors')({origin: true});
const app = express();
jonmeow marked this conversation as resolved.
Show resolved Hide resolved

const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');
const secrets = new SecretManagerServiceClient();

const { Octokit } = require('@octokit/rest');

const {Storage} = require('@google-cloud/storage');
const gcs = new Storage();

// Checks for a session cookie. If present, the content will be added as
// req.user.
const validateFirebaseIdToken = async (req, res, next) => {
if (!req.cookies || !req.cookies.__session) {
// Not logged in.
res.redirect(302, "/login.html");
return;
}

// Validate the cookie, and get user info from it.
const idToken = req.cookies.__session;
try {
req.user = await admin.auth().verifyIdToken(idToken);
} catch (error) {
// Invalid login, use logout to clear it.
res.redirect(302, "/logout.html");
return;
}

// Load the GitHub auth token. The associated secret is attached to the
// CarbonLangInfra GitHub account.
const [secret] = await secrets.accessSecretVersion({
name: 'projects/985662022432/secrets/github-org-lookup-token-for-www/versions/latest',
});
const octokit = new Octokit({
auth: secret.payload.data.toString('utf8'),
});

// Validate that the GitHub user is in carbon-language.
const { data: members } = await octokit.orgs.listMembers({
jonmeow marked this conversation as resolved.
Show resolved Hide resolved
org: 'carbon-language',
});
const wantId = req.user.firebase.identities["github.com"][0];
for (var i = 0; i < members.length; ++i) {
jonmeow marked this conversation as resolved.
Show resolved Hide resolved
if (members[i].id == wantId) {
next();
return;
}
}

// No access, force logout.
res.redirect(302, "/logout.html");
};

app.use(cors);
app.use(cookieParser);
app.use(validateFirebaseIdToken);

app.get('*', (req, res) => {
// Serve the requested data from the carbon-lang bucket.
const bucket = gcs.bucket("gs://www.carbon-lang.dev");
const stream = bucket.file(req.path.replace(/^(\/)/, "")).createReadStream();
//stream.on('error', function(err) { res.status(404).send(err.message); });
stream.on('error', function(err) {
console.log(err.message);
res.status(404).send("Not found");
});
stream.pipe(res);
});

exports.site = functions.https.onRequest(app);
27 changes: 27 additions & 0 deletions firebase/functions/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "10"
},
"dependencies": {
"@google-cloud/secret-manager": "^3.0.0",
"@google-cloud/storage": "^4.3.1",
"@octokit/rest": "^17.6.0",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"firebase-admin": "^8.10.0",
"firebase-functions": "^3.6.1"
},
"devDependencies": {
"firebase-functions-test": "^0.2.0"
},
"private": true
}
Binary file added firebase/public/favicon.ico
Binary file not shown.
42 changes: 42 additions & 0 deletions firebase/public/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<!DOCTYPE html>
<!--
Part of the Carbon Language, under the Apache License v2.0 with LLVM Exceptions.
See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-->
<html>
<head>
<title>Carbon: Login</title>
<script src="/__/firebase/7.14.0/firebase-app.js"></script>
<script src="/__/firebase/7.14.0/firebase-auth.js"></script>
<script src="/__/firebase/init.js"></script>
<script type="text/javascript">
function login() {
var provider = new firebase.auth.GithubAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
var user = result.user;
user.getIdToken(true).then(function(token) {
document.cookie = '__session=' + token + ';max-age=25920000';
window.location.href = window.location.href.replace(
"/login.html", "/index.html");
});
});
};

firebase.auth().onAuthStateChanged(function(user) {
// If there's no user, we can redirect.
if (!user) redirect();
});

window.onload = function() {
document.cookie = "__session=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
firebase.auth().signOut();
};
</script>
</head>
<body>
<p>Currently logged out.</p>

<button onclick="login()">Log in using GitHub</button>
</body>
</html>
35 changes: 35 additions & 0 deletions firebase/public/logout.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<!DOCTYPE html>
<!--
Part of the Carbon Language, under the Apache License v2.0 with LLVM Exceptions.
See /LICENSE for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-->
<html>
<head>
<title>Carbon: Access denied -- logging out</title>
<script src="/__/firebase/7.14.0/firebase-app.js"></script>
<script src="/__/firebase/7.14.0/firebase-auth.js"></script>
<script src="/__/firebase/init.js"></script>
<script type="text/javascript">
function redirect() {
// Re-clear the cookie, just in case.
document.cookie = "__session=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
window.location.href = window.location.href.replace(
"/logout.html", "/login.html");
};

firebase.auth().onAuthStateChanged(function(user) {
// If there's no user, we can redirect.
if (!user) redirect();
});

window.onload = function() {
document.cookie = "__session=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
firebase.auth().signOut();
};
</script>
</head>
<body>
Access denied -- logging out
</body>
</html>