Created
April 1, 2020 10:08
-
-
Save RickyCook/5a74eaa211929f4f19fa2c9be7feb2d7 to your computer and use it in GitHub Desktop.
Authentication state machine
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 TIMEOUT_MS = 2000; | |
const FSM_DEF = { | |
id: 'tokenRequest', | |
initial: 'timing', | |
context: { | |
payload: { statusCode: 500, body: '{"error":"Unknown error [init]"}'}, | |
}, | |
states: { | |
timing: { | |
initial: 'authenticating', | |
after: { | |
[TIMEOUT_MS]: 'resolve', | |
}, | |
states: { | |
authenticating: { | |
invoke: { | |
id: 'authenticate', | |
src: ctx => cb => { | |
ctx.authenticate() | |
.then(auth => cb(auth ? 'AUTHORIZED' : 'UNAUTHORIZED')) | |
.catch(() => cb('ERROR')); | |
}, | |
onError: { actions: send('ERROR') }, | |
}, | |
on: { | |
UNAUTHORIZED: { actions: 'setUnauthorized' }, | |
AUTHORIZED: { | |
actions: 'setAuthorized', | |
target: 'done', | |
}, | |
ERROR: { actions: 'setError' }, | |
}, | |
}, | |
done: { type: 'final' }, | |
}, | |
onDone: 'resolve', | |
}, | |
resolve: { | |
type: 'final', | |
}, | |
}, | |
}; | |
const FSM_OPTS = { | |
actions: { | |
setTryAgain: assign({ | |
payload: ctx => ({ | |
statusCode: 503, | |
body: '{"error":"Try again later"}', | |
}), | |
}), | |
setUnauthorized: assign({ | |
payload: ctx => ({ | |
statusCode: 401, | |
body: JSON.stringify(ctx.getUnauthorizedDetail(ctx.event)), | |
}), | |
}), | |
setAuthorized: assign({ | |
payload: ctx => ({ | |
statusCode: 201, | |
body: JSON.stringify(ctx.getPayload()), | |
}), | |
}), | |
setError: assign({ | |
payload: ctx => ({ | |
statusCode: 500, | |
body: '{"error":"Unknown error"}', | |
}), | |
}), | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment