- Notifications
You must be signed in to change notification settings - Fork927
feat: Add setup page#3476
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
feat: Add setup page#3476
Changes fromall commits
Commits
Show all changes
19 commits Select commitHold shift + click to select a range
2eccbf1
Check if has first user
BrunoQuaresmaa3fabe3
Add missing handler
BrunoQuaresma5d3701b
Add setup
BrunoQuaresma87b55cc
Make user login after creation
BrunoQuaresmad6fe749
Authenticate user when setup is done
BrunoQuaresmaf81942d
Fix setup flow
7b37e0e
Apply suggestions from code review
BrunoQuaresma4e4008f
Add comment into hasFirtUser
a0ef036
Move to language object
186a37c
Refactor tests to not use spy
e50648f
Merge
2cdebbd
Merge branch 'bq/3225' of github.com:coder/coder into bq/3225
d88d470
Merge branch 'main' of github.com:coder/coder into bq/3225
42fd362
Add back first user on dev script
5d988cd
Update site/src/pages/SetupPage/SetupPage.tsx
BrunoQuaresma7959e44
Apply suggestions from code review
BrunoQuaresma3895a0b
Better handle hasFirstUser error
b5e0a63
Fix formatting
4d13c28
Fix login machine
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
4 changes: 2 additions & 2 deletionssite/e2e/globalSetup.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
2 changes: 2 additions & 0 deletionssite/src/AppRouter.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
19 changes: 18 additions & 1 deletionsite/src/api/api.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -282,7 +282,24 @@ export const suspendUser = async (userId: TypesGen.User["id"]): Promise<TypesGen | ||
return response.data | ||
} | ||
// API definition: | ||
// https://github.com/coder/coder/blob/db665e7261f3c24a272ccec48233a3e276878239/coderd/users.go#L33-L53 | ||
export const hasFirstUser = async (): Promise<boolean> => { | ||
try { | ||
// If it is success, it is true | ||
await axios.get("/api/v2/users/first") | ||
return true | ||
BrunoQuaresma marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
} catch (error) { | ||
// If it returns a 404, it is false | ||
if (axios.isAxiosError(error) && error.response?.status === 404) { | ||
return false | ||
} | ||
throw error | ||
} | ||
} | ||
export const createFirstUser = async ( | ||
req: TypesGen.CreateFirstUserRequest, | ||
): Promise<TypesGen.CreateFirstUserResponse> => { | ||
const response = await axios.post(`/api/v2/users/first`, req) | ||
35 changes: 35 additions & 0 deletionssite/src/components/SignInLayout/SignInLayout.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import { makeStyles } from "@material-ui/core/styles" | ||
import { FC } from "react" | ||
import { Footer } from "../../components/Footer/Footer" | ||
export const useStyles = makeStyles((theme) => ({ | ||
root: { | ||
height: "100vh", | ||
display: "flex", | ||
justifyContent: "center", | ||
alignItems: "center", | ||
}, | ||
layout: { | ||
display: "flex", | ||
flexDirection: "column", | ||
alignItems: "center", | ||
}, | ||
container: { | ||
marginTop: theme.spacing(-8), | ||
minWidth: "320px", | ||
maxWidth: "320px", | ||
}, | ||
})) | ||
export const SignInLayout: FC = ({ children }) => { | ||
const styles = useStyles() | ||
return ( | ||
<div className={styles.root}> | ||
<div className={styles.layout}> | ||
<div className={styles.container}>{children}</div> | ||
<Footer /> | ||
</div> | ||
</div> | ||
) | ||
} |
12 changes: 10 additions & 2 deletionssite/src/components/Welcome/Welcome.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
17 changes: 16 additions & 1 deletionsite/src/pages/LoginPage/LoginPage.test.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
62 changes: 18 additions & 44 deletionssite/src/pages/LoginPage/LoginPage.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,80 +1,54 @@ | ||
import { useActor } from "@xstate/react" | ||
import { SignInLayout } from "components/SignInLayout/SignInLayout" | ||
import React, { useContext } from "react" | ||
import { Helmet } from "react-helmet" | ||
import { Navigate, useLocation } from "react-router-dom" | ||
import { LoginErrors, SignInForm } from "../../components/SignInForm/SignInForm" | ||
import { pageTitle } from "../../util/page" | ||
import { retrieveRedirect } from "../../util/redirect" | ||
import { XServiceContext } from "../../xServices/StateContext" | ||
interface LocationState { | ||
isRedirect: boolean | ||
} | ||
export const LoginPage: React.FC = () => { | ||
const location = useLocation() | ||
const xServices = useContext(XServiceContext) | ||
const [authState, authSend] = useActor(xServices.authXService) | ||
const isLoading = authState.hasTag("loading") | ||
const redirectTo = retrieveRedirect(location.search) | ||
const locationState = location.state ? (location.state as LocationState) : null | ||
const isRedirected = locationState ? locationState.isRedirect : false | ||
const { authError, getUserError, checkPermissionsError, getMethodsError } = authState.context | ||
const onSubmit = async ({ email, password }: { email: string; password: string }) => { | ||
authSend({ type: "SIGN_IN", email, password }) | ||
} | ||
if (authState.matches("signedIn")) { | ||
return <Navigate to={redirectTo} replace /> | ||
} else { | ||
return ( | ||
<> | ||
<Helmet> | ||
<title>{pageTitle("Login")}</title> | ||
</Helmet> | ||
<SignInLayout> | ||
<SignInForm | ||
authMethods={authState.context.methods} | ||
redirectTo={redirectTo} | ||
isLoading={isLoading} | ||
loginErrors={{ | ||
[LoginErrors.AUTH_ERROR]: authError, | ||
[LoginErrors.GET_USER_ERROR]: isRedirected ? getUserError : null, | ||
[LoginErrors.CHECK_PERMISSIONS_ERROR]: checkPermissionsError, | ||
[LoginErrors.GET_METHODS_ERROR]: getMethodsError, | ||
}} | ||
onSubmit={onSubmit} | ||
/> | ||
</SignInLayout> | ||
</> | ||
) | ||
} | ||
} |
99 changes: 99 additions & 0 deletionssite/src/pages/SetupPage/SetupPage.test.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
import { screen, waitFor } from "@testing-library/react" | ||
import userEvent from "@testing-library/user-event" | ||
import * as API from "api/api" | ||
import { rest } from "msw" | ||
import { history, MockUser, render } from "testHelpers/renderHelpers" | ||
import { server } from "testHelpers/server" | ||
import { Language as SetupLanguage } from "xServices/setup/setupXService" | ||
import { SetupPage } from "./SetupPage" | ||
import { Language as PageViewLanguage } from "./SetupPageView" | ||
const fillForm = async ({ | ||
username = "someuser", | ||
email = "someone@coder.com", | ||
password = "password", | ||
organization = "Coder", | ||
}: { | ||
username?: string | ||
email?: string | ||
password?: string | ||
organization?: string | ||
} = {}) => { | ||
const usernameField = screen.getByLabelText(PageViewLanguage.usernameLabel) | ||
const emailField = screen.getByLabelText(PageViewLanguage.emailLabel) | ||
const passwordField = screen.getByLabelText(PageViewLanguage.passwordLabel) | ||
const organizationField = screen.getByLabelText(PageViewLanguage.organizationLabel) | ||
await userEvent.type(organizationField, organization) | ||
await userEvent.type(usernameField, username) | ||
await userEvent.type(emailField, email) | ||
await userEvent.type(passwordField, password) | ||
const submitButton = screen.getByRole("button", { name: PageViewLanguage.create }) | ||
submitButton.click() | ||
} | ||
describe("Setup Page", () => { | ||
beforeEach(() => { | ||
history.replace("/setup") | ||
// appear logged out | ||
server.use( | ||
rest.get("/api/v2/users/me", (req, res, ctx) => { | ||
return res(ctx.status(401), ctx.json({ message: "no user here" })) | ||
}), | ||
) | ||
}) | ||
it("shows validation error message", async () => { | ||
render(<SetupPage />) | ||
await fillForm({ email: "test" }) | ||
const errorMessage = await screen.findByText(PageViewLanguage.emailInvalid) | ||
expect(errorMessage).toBeDefined() | ||
}) | ||
it("shows generic error message", async () => { | ||
jest.spyOn(API, "createFirstUser").mockRejectedValueOnce({ | ||
data: "unknown error", | ||
}) | ||
render(<SetupPage />) | ||
await fillForm() | ||
const errorMessage = await screen.findByText(SetupLanguage.createFirstUserError) | ||
expect(errorMessage).toBeDefined() | ||
}) | ||
it("shows API error message", async () => { | ||
const fieldErrorMessage = "invalid username" | ||
server.use( | ||
rest.post("/api/v2/users/first", async (req, res, ctx) => { | ||
return res( | ||
ctx.status(400), | ||
ctx.json({ | ||
message: "invalid field", | ||
validations: [ | ||
{ | ||
detail: fieldErrorMessage, | ||
field: "username", | ||
}, | ||
], | ||
}), | ||
) | ||
}), | ||
) | ||
render(<SetupPage />) | ||
await fillForm() | ||
const errorMessage = await screen.findByText(fieldErrorMessage) | ||
expect(errorMessage).toBeDefined() | ||
}) | ||
it("redirects to workspaces page when success", async () => { | ||
render(<SetupPage />) | ||
// simulates the user will be authenticated | ||
server.use( | ||
rest.get("/api/v2/users/me", (req, res, ctx) => { | ||
return res(ctx.status(200), ctx.json(MockUser)) | ||
}), | ||
) | ||
await fillForm() | ||
await waitFor(() => expect(history.location.pathname).toEqual("/workspaces")) | ||
}) | ||
}) | ||
BrunoQuaresma marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. |
47 changes: 47 additions & 0 deletionssite/src/pages/SetupPage/SetupPage.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import { useActor, useMachine } from "@xstate/react" | ||
import { FC, useContext, useEffect } from "react" | ||
import { Helmet } from "react-helmet" | ||
import { useNavigate } from "react-router-dom" | ||
import { pageTitle } from "util/page" | ||
import { setupMachine } from "xServices/setup/setupXService" | ||
import { XServiceContext } from "xServices/StateContext" | ||
import { SetupPageView } from "./SetupPageView" | ||
export const SetupPage: FC = () => { | ||
const navigate = useNavigate() | ||
const xServices = useContext(XServiceContext) | ||
const [authState, authSend] = useActor(xServices.authXService) | ||
const [setupState, setupSend] = useMachine(setupMachine, { | ||
actions: { | ||
onCreateFirstUser: ({ firstUser }) => { | ||
if (!firstUser) { | ||
throw new Error("First user was not defined.") | ||
} | ||
authSend({ type: "SIGN_IN", email: firstUser.email, password: firstUser.password }) | ||
}, | ||
}, | ||
}) | ||
const { createFirstUserFormErrors, createFirstUserErrorMessage } = setupState.context | ||
useEffect(() => { | ||
if (authState.matches("signedIn")) { | ||
return navigate("/workspaces") | ||
} | ||
}, [authState, navigate]) | ||
return ( | ||
<> | ||
<Helmet> | ||
<title>{pageTitle("Set up your account")}</title> | ||
</Helmet> | ||
<SetupPageView | ||
isLoading={setupState.hasTag("loading")} | ||
formErrors={createFirstUserFormErrors} | ||
genericError={createFirstUserErrorMessage} | ||
onSubmit={(firstUser) => { | ||
setupSend({ type: "CREATE_FIRST_USER", firstUser }) | ||
}} | ||
/> | ||
</> | ||
) | ||
} |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.