Skip to content

Instantly share code, notes, and snippets.

@brookslybrand
Created January 31, 2020 18:22
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 brookslybrand/0c8200e75d16217270457809f770329c to your computer and use it in GitHub Desktop.
Save brookslybrand/0c8200e75d16217270457809f770329c to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// 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(email, password, ms = 1500) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < 0.5) resolve(email);
else reject("oopsy doopsy");
}, ms);
});
}
const initialContext = {
email: "",
password: ""
};
const authMachine = Machine(
{
id: "authentication",
initial: "loggedOut",
context: initialContext,
states: {
loggedOut: {
initial: "noErrors",
on: {
SIGN_UP: [
// check if everything is valid
{
target: ".invalidEmail",
cond: (_, e) => !emailReg.test(e.email)
},
{
target: ".invalidPassword",
cond: (_, e) => !passwordReg.test(e.password)
},
// if all worked out, go ahead and authenticate
{
target: "authenticating",
actions: assign({
email: (_, e) => e.email,
password: (_, e) => e.password
})
}
]
},
states: {
noErrors: {},
invalidEmail: {},
invalidPassword: {},
authFailed: {}
}
},
authenticating: {
invoke: {
id: "authenticateUser",
src: ctx => {
const { email, password } = ctx;
return mockAuthenticate(email, password);
},
onDone: {
target: "loggedIn",
actions: "clearSignUp"
},
onError: {
target: "loggedOut.authFailed"
}
}
},
loggedIn: {
on: {
LOGOUT: "loggedOut"
}
}
}
},
{
actions: {
clearSignUp: assign(initialContext)
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment