Skip to content

Instantly share code, notes, and snippets.

@gristoi
Created August 20, 2021 11:06
Show Gist options
  • Save gristoi/094a77a36d156bf1a1d6528617d6627c to your computer and use it in GitHub Desktop.
Save gristoi/094a77a36d156bf1a1d6528617d6627c to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const initialContext = { username: '', password: '', jwt: '' }
// taken from https://www.w3resource.com/javascript/form/email-validation.php
const emailReg = /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/
// taken from https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a
const passwordReg = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/
function mockAuthenticate(username, password, ms = 1500) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < 0.5) resolve(username)
else reject('oopsy doopsy')
}, ms)
})
}
const authMachine = Machine(
{
id: 'authentication',
initial: 'loggedOut',
context: initialContext,
states: {
loggedOut: {
initial: 'noErrors',
on: {
SIGN_UP: [
// check if everything is valid
{
target: '.invalidEmail',
cond: 'checkEmail',
},
{
target: '.invalidPassword',
cond: 'checkPassword',
},
// if all worked out, go ahead and authenticate
{
target: 'authenticating',
actions: 'saveData',
},
],
},
states: {
noErrors: {},
invalidEmail: {},
invalidPassword: {},
authFailed: {},
},
},
authenticating: {
invoke: {
id: 'authenticateUser',
src: 'authenticateUser',
onDone: {
target: 'loggedIn',
actions: 'clearSignUp',
},
onError: {
target: 'loggedOut.authFailed',
},
},
},
loggedIn: {
on: {
LOGOUT: 'loggedOut',
},
},
},
},
{
actions: {
clearSignUp: assign(initialContext),
saveData: assign({
username: (_, e) => e.username,
password: (_, e) => e.password,
}),
},
guards: {
checkEmail: (_, e) => !emailReg.test(e.username),
checkPassword: (_, e) => !passwordReg.test(e.password),
},
services: {
authenticateUser: (ctx) => {
const { username, password } = ctx
return mockAuthenticate(username, password)
},
},
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment