Skip to content

Instantly share code, notes, and snippets.

@RickyCook
Created April 1, 2020 10:08
Show Gist options
  • Save RickyCook/5a74eaa211929f4f19fa2c9be7feb2d7 to your computer and use it in GitHub Desktop.
Save RickyCook/5a74eaa211929f4f19fa2c9be7feb2d7 to your computer and use it in GitHub Desktop.
Authentication state machine
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