Thanks to visit codestin.com
Credit goes to github.com

Skip to content

fix: handle all auth API errors #3241

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

Merged
merged 7 commits into from
Jul 28, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
79 changes: 66 additions & 13 deletions site/src/components/SignInForm/SignInForm.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const Template: Story<SignInFormProps> = (args: SignInFormProps) => <SignInForm
export const SignedOut = Template.bind({})
SignedOut.args = {
isLoading: false,
authError: undefined,
loginErrors: {},
onSubmit: () => {
return Promise.resolve()
},
Expand All @@ -34,29 +34,82 @@ Loading.args = {
export const WithLoginError = Template.bind({})
WithLoginError.args = {
...SignedOut.args,
authError: {
response: {
data: {
message: "Email or password was invalid",
validations: [
{
field: "password",
detail: "Password is invalid.",
},
],
loginErrors: {
authError: {
response: {
data: {
message: "Email or password was invalid",
validations: [
{
field: "password",
detail: "Password is invalid.",
},
],
},
},
isAxiosError: true,
},
isAxiosError: true,
},
initialTouched: {
password: true,
},
}

export const WithGetUserError = Template.bind({})
WithGetUserError.args = {
...SignedOut.args,
loginErrors: {
getUserError: {
response: {
data: {
message: "Unable to fetch user details",
detail: "Resource not found or you do not have access to this resource.",
},
},
isAxiosError: true,
},
},
}

export const WithCheckPermissionsError = Template.bind({})
WithCheckPermissionsError.args = {
...SignedOut.args,
loginErrors: {
checkPermissionsError: {
response: {
data: {
message: "Unable to fetch user permissions",
detail: "Resource not found or you do not have access to this resource.",
},
},
isAxiosError: true,
},
},
}

export const WithAuthMethodsError = Template.bind({})
WithAuthMethodsError.args = {
...SignedOut.args,
methodsError: new Error("Failed to fetch auth methods"),
loginErrors: {
getMethodsError: new Error("Failed to fetch auth methods"),
},
}

export const WithGetUserAndAuthMethodsErrors = Template.bind({})
WithGetUserAndAuthMethodsErrors.args = {
...SignedOut.args,
loginErrors: {
getUserError: {
response: {
data: {
message: "Unable to fetch user details",
detail: "Resource not found or you do not have access to this resource.",
},
},
isAxiosError: true,
},
getMethodsError: new Error("Failed to fetch auth methods"),
},
}

export const WithGithub = Template.bind({})
Expand Down
48 changes: 38 additions & 10 deletions site/src/components/SignInForm/SignInForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ export const Language = {
emailInvalid: "Please enter a valid email address.",
emailRequired: "Please enter an email address.",
authErrorMessage: "Incorrect email or password.",
methodsErrorMessage: "Unable to fetch auth methods.",
getUserErrorMessage: "Unable to fetch user details.",
checkPermissionsErrorMessage: "Unable to fetch user permissions.",
getMethodsErrorMessage: "Unable to fetch auth methods.",
passwordSignIn: "Sign In",
githubSignIn: "GitHub",
}
Expand Down Expand Up @@ -65,11 +67,17 @@ const useStyles = makeStyles((theme) => ({
},
}))

type LoginErrors = {
authError?: Error | unknown
getUserError?: Error | unknown
checkPermissionsError?: Error | unknown
getMethodsError?: Error | unknown
}

export interface SignInFormProps {
isLoading: boolean
redirectTo: string
authError?: Error | unknown
methodsError?: Error | unknown
loginErrors: LoginErrors
authMethods?: AuthMethods
onSubmit: ({ email, password }: { email: string; password: string }) => Promise<void>
// initialTouched is only used for testing the error state of the form.
Expand All @@ -80,8 +88,7 @@ export const SignInForm: FC<SignInFormProps> = ({
authMethods,
redirectTo,
isLoading,
authError,
methodsError,
loginErrors,
onSubmit,
initialTouched,
}) => {
Expand All @@ -101,18 +108,39 @@ export const SignInForm: FC<SignInFormProps> = ({
onSubmit,
initialTouched,
})
const getFieldHelpers = getFormHelpersWithError<BuiltInAuthFormValues>(form, authError)
const getFieldHelpers = getFormHelpersWithError<BuiltInAuthFormValues>(
form,
loginErrors.authError,
)

return (
<>
<Welcome />
<form onSubmit={form.handleSubmit}>
<Stack>
{authError && (
<ErrorSummary error={authError} defaultMessage={Language.authErrorMessage} />
{loginErrors.authError && (
<ErrorSummary
error={loginErrors.authError}
defaultMessage={Language.authErrorMessage}
/>
)}
{loginErrors.getUserError && (
<ErrorSummary
error={loginErrors.getUserError}
defaultMessage={Language.getUserErrorMessage}
/>
)}
{loginErrors.checkPermissionsError && (
<ErrorSummary
error={loginErrors.checkPermissionsError}
defaultMessage={Language.checkPermissionsErrorMessage}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

I would DRY this up by mapping over the keys of loginErrors

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thought about it, but we’ll have to map default messages in a separate object for that. I’ll try that!

Copy link
Contributor

@presleyp presleyp Jul 27, 2022

Choose a reason for hiding this comment

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

I was thinking if you map over the keys you could do defaultMessage={Language[errorKey]} if you name them the same

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Declared an enum with error types, and used a Record<enum, Error> for iterating through keys. I was not able iterate through the properties of a type or interface.

Copy link
Contributor

Choose a reason for hiding this comment

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

Oh I was thinking of iterating over Object.keys(loginErrors).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah, that threw some error and I wasn't able to proceed.

)}
{methodsError && (
<ErrorSummary error={methodsError} defaultMessage={Language.methodsErrorMessage} />
{loginErrors.getMethodsError && (
<ErrorSummary
error={loginErrors.getMethodsError}
defaultMessage={Language.getMethodsErrorMessage}
/>
)}
<TextField
{...getFieldHelpers("email")}
Expand Down
10 changes: 8 additions & 2 deletions site/src/pages/LoginPage/LoginPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ export const LoginPage: React.FC = () => {
authSend({ type: "SIGN_IN", email, password })
}

const { authError, getUserError, checkPermissionsError, getMethodsError } = authState.context

if (authState.matches("signedIn")) {
return <Navigate to={redirectTo} replace />
} else {
Expand All @@ -54,8 +56,12 @@ export const LoginPage: React.FC = () => {
authMethods={authState.context.methods}
redirectTo={redirectTo}
isLoading={isLoading}
authError={authState.context.authError}
methodsError={authState.context.getMethodsError as Error}
loginErrors={{
authError,
getUserError,
checkPermissionsError,
getMethodsError,
}}
Copy link
Contributor

Choose a reason for hiding this comment

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

Nice!

onSubmit={onSubmit}
/>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ describe("SSH keys Page", () => {
fireEvent.click(confirmButton)

// Check if the error message is displayed
await screen.findByText(authXServiceLanguage.errorRegenerateSSHKey)
await screen.findByText(SSHKeysPageLanguage.errorRegenerateSSHKey)

// Check if the API was called correctly
expect(API.regenerateUserSSHKey).toBeCalledTimes(1)
Expand Down
48 changes: 31 additions & 17 deletions site/src/pages/UserSettingsPage/SSHKeysPage/SSHKeysPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Box from "@material-ui/core/Box"
import Button from "@material-ui/core/Button"
import CircularProgress from "@material-ui/core/CircularProgress"
import { useActor } from "@xstate/react"
import { ErrorSummary } from "components/ErrorSummary/ErrorSummary"
import React, { useContext, useEffect } from "react"
import { CodeExample } from "../../../components/CodeExample/CodeExample"
import { ConfirmDialog } from "../../../components/ConfirmDialog/ConfirmDialog"
Expand All @@ -19,12 +20,13 @@ export const Language = {
"You will need to replace the public SSH key on services you use it with, and you'll need to rebuild existing workspaces.",
confirmLabel: "Confirm",
cancelLabel: "Cancel",
errorRegenerateSSHKey: "Error on regenerate the SSH Key",
}

export const SSHKeysPage: React.FC = () => {
const xServices = useContext(XServiceContext)
const [authState, authSend] = useActor(xServices.authXService)
const { sshKey } = authState.context
const { sshKey, getSSHKeyError, regenerateSSHKeyError } = authState.context

useEffect(() => {
authSend({ type: "GET_SSH_KEY" })
Expand All @@ -33,27 +35,39 @@ export const SSHKeysPage: React.FC = () => {
return (
<>
<Section title={Language.title} description={Language.description}>
{!sshKey && (
{authState.matches("signedIn.ssh.gettingSSHKey") && (
<Box p={4}>
<CircularProgress size={26} />
</Box>
)}

{sshKey && (
<Stack>
<CodeExample code={sshKey.public_key.trim()} />
<div>
<Button
variant="outlined"
onClick={() => {
authSend({ type: "REGENERATE_SSH_KEY" })
}}
>
{Language.regenerateLabel}
</Button>
</div>
</Stack>
)}
<Stack>
{/* Regenerating the key is not an option if getSSHKey fails.
Only one of the error messages will exist at a single time */}
{getSSHKeyError && <ErrorSummary error={getSSHKeyError} />}
{regenerateSSHKeyError && (
<ErrorSummary
error={regenerateSSHKeyError}
defaultMessage={Language.errorRegenerateSSHKey}
dismissible
/>
)}
{authState.matches("signedIn.ssh.loaded") && sshKey && (
<>
<CodeExample code={sshKey.public_key.trim()} />
<div>
<Button
variant="outlined"
onClick={() => {
authSend({ type: "REGENERATE_SSH_KEY" })
}}
>
{Language.regenerateLabel}
</Button>
</div>
</>
)}
</Stack>
</Section>

<ConfirmDialog
Expand Down
11 changes: 4 additions & 7 deletions site/src/xServices/auth/authXService.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { assign, createMachine } from "xstate"
import * as API from "../../api/api"
import * as TypesGen from "../../api/typesGenerated"
import { displayError, displaySuccess } from "../../components/GlobalSnackbar/utils"
import { displaySuccess } from "../../components/GlobalSnackbar/utils"

export const Language = {
successProfileUpdate: "Updated settings.",
successSecurityUpdate: "Updated password.",
successRegenerateSSHKey: "SSH Key regenerated successfully",
errorRegenerateSSHKey: "Error on regenerate the SSH Key",
}

export const checks = {
Expand Down Expand Up @@ -130,7 +129,7 @@ const sshState = {
],
onError: [
{
actions: ["assignRegenerateSSHKeyError", "notifySSHKeyRegenerationError"],
actions: ["assignRegenerateSSHKeyError"],
target: "#authState.signedIn.ssh.loaded.idle",
},
],
Expand Down Expand Up @@ -214,12 +213,13 @@ export const authMachine =
tags: "loading",
},
gettingUser: {
entry: "clearGetUserError",
invoke: {
src: "getMe",
id: "getMe",
onDone: [
{
actions: ["assignMe", "clearGetUserError"],
actions: ["assignMe"],
target: "gettingPermissions",
},
],
Expand Down Expand Up @@ -488,9 +488,6 @@ export const authMachine =
notifySuccessSSHKeyRegenerated: () => {
displaySuccess(Language.successRegenerateSSHKey)
},
notifySSHKeyRegenerationError: () => {
displayError(Language.errorRegenerateSSHKey)
},
},
},
)