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 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
43 changes: 27 additions & 16 deletions site/src/components/SignInForm/SignInForm.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Story } from "@storybook/react"
import { SignInForm, SignInFormProps } from "./SignInForm"
import { makeMockApiError } from "testHelpers/entities"
import { LoginErrors, SignInForm, SignInFormProps } from "./SignInForm"

export default {
title: "components/SignInForm",
Expand All @@ -15,7 +16,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 +35,39 @@ 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.",
},
],
},
},
isAxiosError: true,
loginErrors: {
[LoginErrors.AUTH_ERROR]: makeMockApiError({
message: "Email or password was invalid",
validations: [
{
field: "password",
detail: "Password is invalid.",
},
],
}),
},
initialTouched: {
password: true,
},
}

export const WithCheckPermissionsError = Template.bind({})
WithCheckPermissionsError.args = {
...SignedOut.args,
loginErrors: {
[LoginErrors.CHECK_PERMISSIONS_ERROR]: makeMockApiError({
message: "Unable to fetch user permissions",
detail: "Resource not found or you do not have access to this resource.",
}),
},
}

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

export const WithGithub = Template.bind({})
Expand Down
37 changes: 25 additions & 12 deletions site/src/components/SignInForm/SignInForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,22 @@ interface BuiltInAuthFormValues {
password: string
}

export enum LoginErrors {
AUTH_ERROR = "authError",
CHECK_PERMISSIONS_ERROR = "checkPermissionsError",
GET_METHODS_ERROR = "getMethodsError",
}

export const Language = {
emailLabel: "Email",
passwordLabel: "Password",
emailInvalid: "Please enter a valid email address.",
emailRequired: "Please enter an email address.",
authErrorMessage: "Incorrect email or password.",
methodsErrorMessage: "Unable to fetch auth methods.",
errorMessages: {
[LoginErrors.AUTH_ERROR]: "Incorrect email or password.",
[LoginErrors.CHECK_PERMISSIONS_ERROR]: "Unable to fetch user permissions.",
[LoginErrors.GET_METHODS_ERROR]: "Unable to fetch auth methods.",
},
passwordSignIn: "Sign In",
githubSignIn: "GitHub",
}
Expand Down Expand Up @@ -68,8 +77,7 @@ const useStyles = makeStyles((theme) => ({
export interface SignInFormProps {
isLoading: boolean
redirectTo: string
authError?: Error | unknown
methodsError?: Error | unknown
loginErrors: Partial<Record<LoginErrors, Error | unknown>>
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,24 @@ 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} />
)}
{methodsError && (
<ErrorSummary error={methodsError} defaultMessage={Language.methodsErrorMessage} />
{Object.keys(loginErrors).map((errorKey: string) =>
loginErrors[errorKey as LoginErrors] ? (
<ErrorSummary
key={errorKey}
error={loginErrors[errorKey as LoginErrors]}
defaultMessage={Language.errorMessages[errorKey as LoginErrors]}
/>
) : null,
)}
<TextField
{...getFieldHelpers("email")}
Expand Down
4 changes: 2 additions & 2 deletions site/src/pages/LoginPage/LoginPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ describe("LoginPage", () => {
server.use(
// Make login fail
rest.post("/api/v2/users/login", async (req, res, ctx) => {
return res(ctx.status(500), ctx.json({ message: Language.authErrorMessage }))
return res(ctx.status(500), ctx.json({ message: Language.errorMessages.authError }))
}),
)

Expand All @@ -45,7 +45,7 @@ describe("LoginPage", () => {
act(() => signInButton.click())

// Then
const errorMessage = await screen.findByText(Language.authErrorMessage)
const errorMessage = await screen.findByText(Language.errorMessages.authError)
expect(errorMessage).toBeDefined()
expect(history.location.pathname).toEqual("/login")
})
Expand Down
9 changes: 7 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, checkPermissionsError, getMethodsError } = authState.context

if (authState.matches("signedIn")) {
return <Navigate to={redirectTo} replace />
} else {
Expand All @@ -54,8 +56,11 @@ 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,
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 @@ -4,6 +4,7 @@ import { GlobalSnackbar } from "../../../components/GlobalSnackbar/GlobalSnackba
import { MockGitSSHKey, renderWithAuth } from "../../../testHelpers/renderHelpers"
import { Language as authXServiceLanguage } from "../../../xServices/auth/authXService"
import { Language as SSHKeysPageLanguage, SSHKeysPage } from "./SSHKeysPage"
import { Language as SSHKeysPageViewLanguage } from "./SSHKeysPageView"

describe("SSH keys Page", () => {
it("shows the SSH key", async () => {
Expand All @@ -26,7 +27,7 @@ describe("SSH keys Page", () => {

// Click on the "Regenerate" button to display the confirm dialog
const regenerateButton = screen.getByRole("button", {
name: SSHKeysPageLanguage.regenerateLabel,
name: SSHKeysPageViewLanguage.regenerateLabel,
})
fireEvent.click(regenerateButton)
const confirmDialog = screen.getByRole("dialog")
Expand Down Expand Up @@ -72,7 +73,7 @@ describe("SSH keys Page", () => {

// Click on the "Regenerate" button to display the confirm dialog
const regenerateButton = screen.getByRole("button", {
name: SSHKeysPageLanguage.regenerateLabel,
name: SSHKeysPageViewLanguage.regenerateLabel,
})
fireEvent.click(regenerateButton)
const confirmDialog = screen.getByRole("dialog")
Expand All @@ -85,7 +86,7 @@ describe("SSH keys Page", () => {
fireEvent.click(confirmButton)

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

// Check if the API was called correctly
expect(API.regenerateUserSSHKey).toBeCalledTimes(1)
Expand Down
45 changes: 17 additions & 28 deletions site/src/pages/UserSettingsPage/SSHKeysPage/SSHKeysPage.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
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 React, { useContext, useEffect } from "react"
import { CodeExample } from "../../../components/CodeExample/CodeExample"
import { ConfirmDialog } from "../../../components/ConfirmDialog/ConfirmDialog"
import { Section } from "../../../components/Section/Section"
import { Stack } from "../../../components/Stack/Stack"
import { XServiceContext } from "../../../xServices/StateContext"
import { SSHKeysPageView } from "./SSHKeysPageView"

export const Language = {
title: "SSH keys",
description:
"Coder automatically inserts a private key into every workspace; you can add the corresponding public key to any services (such as Git) that you need access to from your workspace.",
regenerateLabel: "Regenerate",
regenerateDialogTitle: "Regenerate SSH key?",
regenerateDialogMessage:
"You will need to replace the public SSH key on services you use it with, and you'll need to rebuild existing workspaces.",
Expand All @@ -24,36 +19,30 @@ export const Language = {
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" })
}, [authSend])

const isLoading = authState.matches("signedIn.ssh.gettingSSHKey")
const hasLoaded = authState.matches("signedIn.ssh.loaded")

const onRegenerateClick = () => {
authSend({ type: "REGENERATE_SSH_KEY" })
}

return (
<>
<Section title={Language.title} description={Language.description}>
{!sshKey && (
<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>
)}
<SSHKeysPageView
isLoading={isLoading}
hasLoaded={hasLoaded}
getSSHKeyError={getSSHKeyError}
regenerateSSHKeyError={regenerateSSHKeyError}
sshKey={sshKey}
onRegenerateClick={onRegenerateClick}
/>
</Section>

<ConfirmDialog
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { Story } from "@storybook/react"
import { makeMockApiError } from "testHelpers/entities"
import { SSHKeysPageView, SSHKeysPageViewProps } from "./SSHKeysPageView"

export default {
title: "components/SSHKeysPageView",
component: SSHKeysPageView,
argTypes: {
onRegenerateClick: { action: "Submit" },
},
}

const Template: Story<SSHKeysPageViewProps> = (args: SSHKeysPageViewProps) => (
<SSHKeysPageView {...args} />
)

export const Example = Template.bind({})
Example.args = {
isLoading: false,
hasLoaded: true,
sshKey: {
user_id: "test-user-id",
created_at: "2022-07-28T07:45:50.795918897Z",
updated_at: "2022-07-28T07:45:50.795919142Z",
public_key: "SSH-Key",
},
onRegenerateClick: () => {
return Promise.resolve()
},
}

export const Loading = Template.bind({})
Loading.args = {
...Example.args,
isLoading: true,
}

export const WithGetSSHKeyError = Template.bind({})
WithGetSSHKeyError.args = {
...Example.args,
hasLoaded: false,
getSSHKeyError: makeMockApiError({
message: "Failed to get SSH key",
}),
}

export const WithRegenerateSSHKeyError = Template.bind({})
WithRegenerateSSHKeyError.args = {
...Example.args,
regenerateSSHKeyError: makeMockApiError({
message: "Failed to regenerate SSH key",
}),
}
Loading