Skip to content

Instantly share code, notes, and snippets.

@tklepzig
Last active August 18, 2020 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tklepzig/dd2cdada57402f89e11687b8fdb332f3 to your computer and use it in GitHub Desktop.
Save tklepzig/dd2cdada57402f89e11687b8fdb332f3 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const requestDuration = 1000;
const postLogin = () =>
new Promise((resolve, reject) =>
setTimeout(() => reject(401), requestDuration),
);
const validateOTP = () =>
new Promise((resolve, reject) =>
setTimeout(() => resolve(202), requestDuration),
);
const validateBackupCode = () =>
new Promise((resolve, reject) =>
setTimeout(() => resolve(202), requestDuration),
);
const machine = Machine(
{
id: '2fa',
initial: 'idle',
states: {
idle: {
on: {
LOGIN: 'loginAttempt',
},
},
loginAttempt: {
initial: 'loading',
states: {
loading: {
invoke: {
id: 'postLogin',
src: postLogin,
onDone: [
{ target: '#2fa.redirect', cond: 'redirect' },
{ target: '#2fa.redirectToUserStartPage', cond: 'isSuccess' },
{ target: '#2fa.otpRequired', cond: 'isIncomplete' },
],
onError: [
{ target: 'errorInvalid', cond: 'isInvalid' },
{ target: 'errorOther' },
],
},
},
errorInvalid: {},
errorOther: {},
},
},
otpRequired: {
on: {
SUBMIT_OTP: 'validateOTP',
SUBMIT_BACKUP_CODE: 'validateBackupCode',
},
},
validateOTP: {
initial: 'loading',
states: {
loading: {
invoke: {
id: 'validateOTP',
src: validateOTP,
onDone: [
{ target: '#2fa.redirect', cond: 'redirect' },
{ target: '#2fa.redirectToUserStartPage', cond: 'isSuccess' },
],
onError: [
{ target: 'errorInvalid', cond: 'isInvalid' },
{ target: 'errorOTPTimeout', cond: 'isOTPTimeout' },
{ target: 'errorOther' },
],
},
},
errorOTPTimeout: {},
errorInvalid: {},
errorOther: {},
},
},
validateBackupCode: {
initial: 'loading',
states: {
loading: {
invoke: {
id: 'validateBackupCode',
src: validateBackupCode,
onDone: [
{ target: '#2fa.redirect', cond: 'redirect' },
{ target: '#2fa.redirectToUserStartPage', cond: 'isSuccess' },
],
onError: [
{ target: 'errorInvalid', cond: 'isInvalid' },
{ target: 'errorOTPTimeout', cond: 'isOTPTimeout' },
{ target: 'errorOther' },
],
},
},
errorOTPTimeout: {},
errorInvalid: {},
errorOther: {},
},
},
redirect: {},
redirectToUserStartPage: {},
},
},
{
guards: {
redirect: (_, e) => e.data === 'redirect',
isSuccess: (_, e) => e.data === 200,
isIncomplete: (_, e) => e.data === 202,
isInvalid: (_, e) => e.data === 401,
isOTPTimeout: (_, e) => e.data === 403,
},
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment