Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Attempt #2: Add explicit state for initializing authMachine (#1142) #1162

Merged
merged 2 commits into from
Jan 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/lucky-numbers-lay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@aws-amplify/ui-react": patch
"@aws-amplify/ui": patch
"@aws-amplify/ui-vue": patch
"@aws-amplify/ui-angular": patch
---

Add explicit `INIT` step for initializing authMachine
23 changes: 18 additions & 5 deletions docs/src/pages/components/authenticator/LabelsAndTextDemo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,28 @@ function Screen({ Component }: ScreenProps) {
}

export function LabelsAndTextDemo({ Component }: ScreenProps) {
const OnMachineInit = ({ children }) => {
/**
* This waits for Authenticator machine to init before its inner components
* start consuming machine context.
*/
const { route } = useAuthenticator();
if (!route || route === 'idle' || route === 'setup') return null;

return <>{children}</>;
};
Comment on lines +74 to +83
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the only additional change since #1142.

Labels and Text demo was using Authenticator.<SubComponent> directly, which relied on authMachine to be already initialized and ready. With #1142, authMachine isn't fully initiated when this demo renders, which caused a runtime error. This component goes around it by rendering demo only if the machine is set up.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kapture.2022-01-18.at.15.19.03.mp4

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good enough for me!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And there is no where else we use these subcomponents?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, this is the only place i could find it used 👍


return (
<Authenticator.Provider>
<View data-amplify-authenticator="">
<View data-amplify-container="">
<View data-amplify-body>
<Screen Component={Component} />
<OnMachineInit>
<View data-amplify-authenticator="">
<View data-amplify-container="">
<View data-amplify-body>
<Screen Component={Component} />
</View>
</View>
</View>
</View>
</OnMachineInit>
</Authenticator.Provider>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,21 @@ export class AuthenticatorService implements OnDestroy {
signUpAttributes,
socialProviders,
}: AuthenticatorMachineOptions) {
const machine = createAuthenticatorMachine({
initialState,
loginMechanisms,
services,
signUpAttributes,
socialProviders,
const machine = createAuthenticatorMachine();

const authService = interpret(machine).start();

authService.send({
type: 'INIT',
data: {
initialState,
loginMechanisms,
socialProviders,
signUpAttributes,
services,
},
});

const authService = interpret(machine, {
devTools: process.env.NODE_ENV === 'development',
}).start();

this._subscription = authService.subscribe((state) => {
this._authState = state;
this._facade = getServiceContextFacade(state);
Expand Down
21 changes: 11 additions & 10 deletions packages/react/src/components/Authenticator/Provider/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,20 @@ const useAuthenticatorValue = ({
signUpAttributes,
services,
}: ProviderProps) => {
const [state, send] = useMachine(
() =>
createAuthenticatorMachine({
const [state, send] = useMachine(() => createAuthenticatorMachine());

React.useEffect(() => {
send({
type: 'INIT',
data: {
initialState,
loginMechanisms,
services,
signUpAttributes,
socialProviders,
}),
{
devTools: process.env.NODE_ENV === 'development',
}
);
signUpAttributes,
services,
},
});
}, []);

const components = React.useMemo(
() => ({ ...defaultComponents, ...customComponents }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export function Router({
{(() => {
switch (route) {
case 'idle':
case 'setup':
return null;
case 'confirmSignUp':
return <ConfirmSignUp />;
Expand Down
2 changes: 2 additions & 0 deletions packages/ui/src/helpers/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,8 @@ export const getServiceContextFacade = (state: AuthMachineState) => {
switch (true) {
case state.matches('idle'):
return 'idle';
case state.matches('setup'):
return 'setup';
case state.matches('signOut'):
return 'signOut';
case state.matches('authenticated'):
Expand Down
71 changes: 46 additions & 25 deletions packages/ui/src/machines/authenticator/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,50 +9,54 @@ import { createSignUpMachine } from './signUp';
const DEFAULT_COUNTRY_CODE = '+1';

export type AuthenticatorMachineOptions = AuthContext['config'] & {
initialState?: 'signIn' | 'signUp' | 'resetPassword';
services?: Partial<typeof defaultServices>;
services?: AuthContext['services'];
};

export function createAuthenticatorMachine({
initialState = 'signIn',
loginMechanisms,
signUpAttributes,
socialProviders,
services: customServices,
}: AuthenticatorMachineOptions) {
const services = {
...defaultServices,
...customServices,
};

export function createAuthenticatorMachine() {
return createMachine<AuthContext, AuthEvent>(
{
id: 'authenticator',
initial: 'idle',
context: {
user: undefined,
config: {
loginMechanisms,
signUpAttributes,
socialProviders,
},
config: {},
services: {},
actorRef: undefined,
},
states: {
// See: https://xstate.js.org/docs/guides/communication.html#invoking-promises
idle: {
on: {
INIT: {
target: 'setup',
actions: 'configure',
},
},
},
setup: {
invoke: [
{
// TODO Wait for Auth to be configured
src: 'getCurrentUser',
src: (context, _) => context.services.getCurrentUser(),
onDone: {
actions: 'setUser',
target: 'authenticated',
},
onError: initialState,
onError: [
{
target: 'signUp',
cond: (context) => context.config.initialState === 'signUp',
},
{
target: 'resetPassword',
cond: (context) =>
context.config.initialState === 'resetPassword',
},
{ target: 'signIn' },
],
},
{
src: 'getAmplifyConfig',
src: (context, _) => context.services.getAmplifyConfig(),
onDone: {
actions: 'applyAmplifyConfig',
},
Expand Down Expand Up @@ -87,7 +91,7 @@ export function createAuthenticatorMachine({
on: {
SIGN_IN: 'signIn',
'done.invoke.signUpActor': {
target: 'idle',
target: 'setup',
actions: 'setUser',
},
},
Expand Down Expand Up @@ -159,7 +163,14 @@ export function createAuthenticatorMachine({
cliLoginMechanisms.push('username');
}

// Prefer explicitly configured settings over default CLI values
// Prefer explicitly configured settings over default CLI values\

const {
loginMechanisms,
signUpAttributes,
socialProviders,
initialState,
} = context.config;
return {
loginMechanisms: loginMechanisms ?? cliLoginMechanisms,
signUpAttributes:
Expand All @@ -171,11 +182,13 @@ export function createAuthenticatorMachine({
])
),
socialProviders: socialProviders ?? cliSocialProviders.sort(),
initialState,
};
},
}),
spawnSignInActor: assign({
actorRef: (context, event) => {
const { services } = context;
const actor = signInActor({ services }).withContext({
authAttributes: event.data?.authAttributes,
user: event.data?.user,
Expand All @@ -192,6 +205,7 @@ export function createAuthenticatorMachine({
}),
spawnSignUpActor: assign({
actorRef: (context, event) => {
const { services } = context;
const actor = createSignUpMachine({ services }).withContext({
authAttributes: event.data?.authAttributes ?? {},
country_code: DEFAULT_COUNTRY_CODE,
Expand All @@ -207,6 +221,7 @@ export function createAuthenticatorMachine({
}),
spawnResetPasswordActor: assign({
actorRef: (context, event) => {
const { services } = context;
const actor = resetPasswordActor({ services }).withContext({
formValues: {},
touched: {},
Expand All @@ -225,6 +240,13 @@ export function createAuthenticatorMachine({
return spawn(actor, { name: 'signOutActor' });
},
}),
configure: assign((_, event) => {
const { services: customServices, ...config } = event.data;
return {
services: { ...defaultServices, ...customServices },
config,
};
}),
},
guards: {
shouldRedirectToSignUp: (_, event): boolean => {
Expand All @@ -236,7 +258,6 @@ export function createAuthenticatorMachine({
return event.data.intent === 'confirmPasswordReset';
},
},
services,
}
);
}
4 changes: 4 additions & 0 deletions packages/ui/src/types/authMachine.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { CognitoUser, CodeDeliveryDetails } from 'amazon-cognito-identity-js';
import { Interpreter, State } from 'xstate';
import { ValidationError } from './validator';
import { defaultServices } from '../machines/authenticator/defaultServices';

export type AuthFormData = Record<string, string>;

Expand All @@ -10,7 +11,9 @@ export interface AuthContext {
loginMechanisms?: LoginMechanism[];
signUpAttributes?: SignUpAttribute[];
socialProviders?: SocialProvider[];
initialState?: 'signIn' | 'signUp' | 'resetPassword';
};
services?: Partial<typeof defaultServices>;
user?: CognitoUserAmplify;
username?: string;
password?: string;
Expand Down Expand Up @@ -131,6 +134,7 @@ export type AuthEventTypes =
| 'SIGN_UP'
| 'SKIP'
| 'SUBMIT'
| 'INIT'
| InvokeActorEventTypes;

export enum AuthChallengeNames {
Expand Down
27 changes: 16 additions & 11 deletions packages/vue/src/components/authenticator.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { useAuth } from '../composables/useAuth';
import { ref, computed, useAttrs, watch, Ref } from 'vue';
import { ref, computed, useAttrs, watch, Ref, onMounted } from 'vue';
import { useActor, useInterpret } from '@xstate/vue';
import {
getActorState,
Expand Down Expand Up @@ -58,21 +58,26 @@ const emit = defineEmits([
'verifyUserSubmit',
'confirmVerifyUserSubmit',
]);
const machine = createAuthenticatorMachine({
initialState,
loginMechanisms,
services,
signUpAttributes,
socialProviders,
});
const machine = createAuthenticatorMachine();

const service = useInterpret(machine, {
devTools: process.env.NODE_ENV === 'development',
});
const service = useInterpret(machine);

const { state, send } = useActor(service);
useAuth(service);

onMounted(() => {
send({
type: 'INIT',
data: {
initialState,
loginMechanisms,
socialProviders,
signUpAttributes,
services,
},
});
});

const actorState = computed(() => getActorState(state.value));

const signInComponent = ref();
Expand Down