-
-
Save emanor-okta/8bb1c746a42df24540b0938510832007 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const { OktaAuth, AuthenticatorKey } = require('@okta/okta-auth-js'); | |
const myMemoryStore = {}; | |
const storageProvider = { | |
getItem: function (key) { | |
return myMemoryStore[key]; | |
}, | |
setItem: function (key, val) { | |
myMemoryStore[key] = val; | |
}, | |
removeItem: function (key) { | |
delete myMemoryStore[key]; | |
} | |
}; | |
// const { CLIENT_ID, LOGIN_URL } = process.env; | |
const authClient = new OktaAuth({ | |
issuer: `https://domain.okta.com/oauth2/default`, | |
clientId: '0oa...', | |
clientSecret: 'Jvo...', | |
redirectUri: 'http://localhost:3000/api/magic-link/callback', | |
storageManager: { | |
token: { | |
storageProvider, | |
}, | |
transaction: { | |
storageProvider, | |
} | |
} | |
}); | |
/* | |
const htmlRouter = express.Router(); | |
htmlRouter.get('/magic-link/email-input', (req, res) => { | |
res.sendFile(__dirname + '/html/email-input.html'); | |
}); | |
htmlRouter.get('/magic-link/code-input', (req, res) => { | |
res.sendFile(__dirname + '/html/code-input.html'); | |
}); | |
htmlRouter.get('/magic-link/complete', (req, res) => { | |
res.sendFile(__dirname + '/html/magic-link-complete.html'); | |
}); | |
*/ | |
const apiRouter = express.Router(); | |
// Callback URL that validates the magic link and gets and displays token info | |
apiRouter.get('/magic-link/callback', async (req, res) => { | |
const search = `?${new URLSearchParams(req.query).toString()}`; | |
const transaction = await authClient.idx.handleEmailVerifyCallback(search); | |
if (!transaction || transaction.status !== 'SUCCESS') { | |
return res.status(400).json({ | |
error: true, | |
query: req.query, | |
transactionStatus: transaction?.status || 'no transaction', | |
}); | |
} | |
const { accessToken } = transaction.tokens.accessToken; | |
console.log(accessToken); | |
/*const { refreshToken } = transaction.tokens.refreshToken; | |
const tokenPayload = jwt.decode(accessToken); | |
const queryParams = { | |
accessToken, | |
refreshToken, | |
userId: tokenPayload.virtru_user_id, | |
sessionId: tokenPayload.virtru_session_id, | |
}; | |
const query = new URLSearchParams(queryParams).toString(); | |
return res.redirect(`/magic-link/complete?${query}`); | |
*/ | |
}); | |
// Request the verification email for the givne email address in the query | |
apiRouter.get('/magic-link/start', async (req, res) => { | |
const { email } = req.query; | |
if (!email) { | |
return res.status(400).json({ error: 'must provide email query param' }); | |
} | |
console.log('Sending verification email to', email); | |
await authClient.idx.clearTransactionMeta(); | |
const { status, nextStep: {inputs,} } = await authClient.idx.authenticate({ | |
username: email | |
}); | |
processResponse(status, inputs); | |
/* | |
const { state } = transaction.meta; | |
if (transaction.nextStep.name !== 'challenge-authenticator') { | |
console.error('got unexpected next step:', transaction.nextStep.name); | |
} else { | |
console.log('Good state for user.', transaction.nextStep.name); | |
} | |
return res.redirect(`/magic-link/code-input?state=${state}`); | |
*/ | |
}); | |
function processResponse(status, inputs) { | |
console.log(status); | |
console.log(inputs); | |
if (inputs[0].name === 'verificationCode') { | |
// usually display html for code imput if not using magic link | |
console.log('>>>> Use Magic Link from Email <<<<<'); | |
} else if (inputs[0].name === 'methodType') { | |
//automate selecting "email" for method type - | |
//for production should verify email is a valid option in array (inputs[0].options[i].value === 'email') | |
authClient.idx.proceed({ methodType: 'email' }) | |
.then( ( { status, nextStep: {inputs,} }) => { | |
processResponse(status, inputs); | |
}) | |
.catch(err => { | |
console.log('Error in chooseMethod:' + err); | |
}); | |
} else if (inputs[0].name === 'authenticator') { | |
//automate selecting "okta_email" for authenticator type | |
//for production should verify email is a valid option in array (inputs[0].options[i].value === 'okta_email') | |
authClient.idx.proceed({ authenticator: 'okta_email' }) | |
.then( ( { status, nextStep: {inputs,} }) => { | |
processResponse(status, inputs); | |
}) | |
.catch(err => { | |
console.log('Error in chooseAuthenticator:' + err); | |
}); | |
} else if (inputs[0].name === 'password') { | |
console.log('password?'); | |
} else { | |
console.log('Unexpected nextStep: ' + inputs[0].name); | |
} | |
} | |
const app = express(); | |
app.get('/', (_, res) => res.redirect('/magic-link/email-input')); | |
app.use('/api', apiRouter); | |
//app.use('/', htmlRouter); | |
app.listen(3000, () => console.log('Example app listening on port 3000!')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment