Skip to content

Commit

Permalink
Allow oauth from any domain (#52)
Browse files Browse the repository at this point in the history
* Allow oauth from any url

* use template strings

* refactor

* Account for forwarded protocol, like tunnels
  • Loading branch information
ryanwi authored Feb 17, 2024
1 parent 02acbf3 commit 89c5f01
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
1 change: 0 additions & 1 deletion env.example
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ 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

SESSION_SECRET=

Expand Down
16 changes: 12 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ const FIREBASE_CONFIG = JSON.stringify({
const host = process.env.RELAY_HOST
const fabricApiUrl = process.env.SIGNALWIRE_FABRIC_API_URL


function getCallbackUrl(req) {
const protocol = req.get('x-forwarded-proto') || req.protocol
return `${protocol}://${req.get('host')}/callback`
}

async function apiRequest(uri, options) {
const response = await fetch(uri, options)

Expand All @@ -44,12 +50,12 @@ async function apiRequest(uri, options) {
return await response.json()
}

async function getAccessToken(code, verifier) {
async function getAccessToken(code, verifier, callbackUrl) {
const params = new URLSearchParams()
params.append('client_id', process.env.OAUTH_CLIENT_ID)
params.append('grant_type', 'authorization_code')
params.append('code', code)
params.append('redirect_uri', process.env.OAUTH_REDIRECT_URI)
params.append('redirect_uri', callbackUrl)
params.append('code_verifier', verifier)

return await apiRequest(process.env.OAUTH_TOKEN_URI, {
Expand Down Expand Up @@ -130,11 +136,12 @@ app.get('/oauth', (req, res) => {
const challenge = base64url(
crypto.createHash('sha256').update(verifier).digest()
)
const currentHost = `${req.protocol}://${req.get('host')}`

const queryParams = new URLSearchParams({
response_type: 'code',
client_id: process.env.OAUTH_CLIENT_ID,
redirect_uri: process.env.OAUTH_REDIRECT_URI,
redirect_uri: getCallbackUrl(req),
code_challenge: challenge,
code_challenge_method: 'S256',
})
Expand All @@ -146,9 +153,10 @@ app.get('/oauth', (req, res) => {

app.get('/callback', async (req, res) => {
console.log('oauth: process callback')
const callbackUrl = getCallbackUrl(req)

try {
const tokenData = await getAccessToken(req.query.code, req.session.verifier)
const tokenData = await getAccessToken(req.query.code, req.session.verifier, callbackUrl)
const token = tokenData.access_token
req.session.token = token

Expand Down

0 comments on commit 89c5f01

Please sign in to comment.