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

Manual OAuth 2.0 #16

Merged
merged 13 commits into from
Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
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
7 changes: 6 additions & 1 deletion env.example
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,9 @@ OAUTH_CLIENT_ID=<foo>
OAUTH_SECRET=<foo>
OAUTH_TOKEN_URI=https://id.fabric.swire.io/oauth/token
OAUTH_AUTH_URI=https://id.fabric.swire.io/login/oauth/authorize
OAUTH_REDIRECT_URI=https://<foo>.ngrok-free.app/callback
OAUTH_REDIRECT_URI=https://<foo>.ngrok-free.app/callback

SESSION_SECRET=

SUBSCRIBER_REFERENCE=
SUBSCRIBER_PASSWORD=
72 changes: 50 additions & 22 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
require('dotenv').config();
const express = require('express');
const session = require('express-session');
const app = express();
const axios = require('axios');
const ClientOAuth2 = require('client-oauth2')
const base64url = require('base64url');
const crypto = require('crypto');

app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static('public'));
app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: true }));

const FIREBASE_CONFIG = JSON.stringify({
apiKey: process.env.FIREBASE_API_KEY,
Expand All @@ -28,16 +31,6 @@ const token_request = {

const host = process.env.RELAY_HOST

const oauthConfig = {
clientId: process.env.OAUTH_CLIENT_ID,
clientSecret: process.env.OAUTH_SECRET,
accessTokenUri: process.env.OAUTH_TOKEN_URI,
authorizationUri: process.env.OAUTH_AUTH_URI,
redirectUri: process.env.OAUTH_REDIRECT_URI
}

const oauthClient = new ClientOAuth2(oauthConfig)

async function apiRequest(endpoint, payload = {}, method = 'POST') {
var url = `https://${process.env.SIGNALWIRE_SPACE}${endpoint}`

Expand Down Expand Up @@ -71,21 +64,56 @@ app.get('/minimal', async (req, res) => {
});

app.get('/oauth', (req, res) => {
const authorizationUri = oauthClient.code.getUri()
console.log("oauth: begin initiation");
// console.log("Request Headers: ", req.headers);
ryanwi marked this conversation as resolved.
Show resolved Hide resolved

const authEndpoint = process.env.OAUTH_AUTH_URI;
const verifier = base64url(crypto.pseudoRandomBytes(32));
req.session.verifier = verifier;
const challenge = base64url(crypto.createHash('sha256').update(verifier).digest());

const queryParams = new URLSearchParams({
response_type: 'code',
client_id: process.env.OAUTH_CLIENT_ID,
redirect_uri: process.env.OAUTH_REDIRECT_URI,
code_challenge: challenge,
code_challenge_method: 'S256'
})

res.redirect(authorizationUri)
const authorizationUri = `${authEndpoint}?${queryParams}`

res.redirect(authorizationUri);
});

app.get('/callback', async (req, res) => {
const credentials = await oauthClient.code.getToken(req.originalUrl);

res.render('index', {
host,
token: credentials.accessToken,
destination: process.env.DEFAULT_DESTINATION,
firebaseConfig: FIREBASE_CONFIG,
console.log("oauth: process callback");
// console.log("Request Headers: ", req.headers);
ryanwi marked this conversation as resolved.
Show resolved Hide resolved

const params = new URLSearchParams();
params.append('client_id', process.env.OAUTH_CLIENT_ID);
params.append('grant_type', 'authorization_code');
params.append('code', req.query.code);
params.append('redirect_uri', process.env.OAUTH_REDIRECT_URI);
params.append('code_verifier', req.session.verifier);

const response = await fetch(process.env.OAUTH_TOKEN_URI, {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have axios installed as well. I think for consistency, we should stick to one. Maybe we can remove the axios.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, seeing that auth.js relies on fetch made we wonder why we use axios still, I can convert the other method and remove axios if we think removing it is fine.

method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: params
});
})

if (response.ok) {
const data = await response.json();
res.render('index', {
host,
token: data.access_token,
destination: process.env.DEFAULT_DESTINATION,
firebaseConfig: FIREBASE_CONFIG,
});
} else {
throw new Error(`HTTP error! status: ${response.status}`);
}
});

app.get('/service-worker.js', async (req, res) => {
res.set({
Expand All @@ -99,4 +127,4 @@ app.get('/service-worker.js', async (req, res) => {

app.listen(process.env.PORT || 3000, () => {
console.log("Server running on port 3000");
});
});
Loading