Skip to content

feat: add user password change page #1866

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 3 commits into from
May 27, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat: add user password change page
  • Loading branch information
f0ssel committed May 27, 2022
commit 3cd7b00b2098fffdcf9b9232cae9d214ff837720
4 changes: 2 additions & 2 deletions site/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,8 @@ export const suspendUser = async (userId: TypesGen.User["id"]): Promise<TypesGen
return response.data
}

export const updateUserPassword = async (password: string, userId: TypesGen.User["id"]): Promise<undefined> =>
axios.put(`/api/v2/users/${userId}/password`, { password })
export const updateUserPassword = async (userId: TypesGen.User["id"], updatePassword: TypesGen.UpdateUserPasswordRequest): Promise<undefined> =>
axios.put(`/api/v2/users/${userId}/password`, updatePassword)

export const getSiteRoles = async (): Promise<Array<TypesGen.Role>> => {
const response = await axios.get<Array<TypesGen.Role>>(`/api/v2/users/roles`)
Expand Down
100 changes: 100 additions & 0 deletions site/src/components/SettingsSecurityForm/SettingsSecurityForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import FormHelperText from "@material-ui/core/FormHelperText"
import TextField from "@material-ui/core/TextField"
import { FormikContextType, FormikErrors, useFormik } from "formik"
import React from "react"
import * as Yup from "yup"
import { getFormHelpers, nameValidator, onChangeTrimmed } from "../../util/formUtils"
import { LoadingButton } from "../LoadingButton/LoadingButton"
import { Stack } from "../Stack/Stack"

interface SecurityFormValues {
old_password: string
password: string
confirm_password: string
}

export const Language = {
oldPasswordLabel: "Old Password",
newPasswordLabel: "New Password",
confirmPasswordLabel: "Confirm Password",
oldPasswordRequired: "Old password is required",
newPasswordRequired: "New password is required",
confirmPasswordRequired: "Password confirmation is required",
passwordMinLength: "Password must be at least 8 characters",
passwordMaxLength: "Password must be no more than 64 characters",
confirmPasswordMatch: "Password and confirmation must match",
updatePassword: "Update password",
}

const validationSchema = Yup.object({
old_password: Yup.string().trim().required(Language.oldPasswordRequired),
password: Yup.string().trim().min(8, Language.passwordMinLength).max(64, Language.passwordMaxLength).required(Language.newPasswordRequired),
confirm_password: Yup.string().trim().test("passwords-match", Language.confirmPasswordMatch, function (value) {
return (this.parent as SecurityFormValues).password === value
})
})

export type SecurityFormErrors = FormikErrors<SecurityFormValues>
export interface SecurityFormProps {
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
export interface SecurityFormProps {
export interface SecurityFormProps {

isLoading: boolean
initialValues: SecurityFormValues
onSubmit: (values: SecurityFormValues) => void
formErrors?: SecurityFormErrors
error?: string
}

export const SecurityForm: React.FC<SecurityFormProps> = ({
isLoading,
onSubmit,
initialValues,
formErrors = {},
error,
}) => {
const form: FormikContextType<SecurityFormValues> = useFormik<SecurityFormValues>({
initialValues,
validationSchema,
onSubmit,
})
const getFieldHelpers = getFormHelpers<SecurityFormValues>(form, formErrors)

return (
<>
<form onSubmit={form.handleSubmit}>
<Stack>
<TextField
{...getFieldHelpers("old_password")}
onChange={onChangeTrimmed(form)}
autoComplete="old_password"
fullWidth
label={Language.oldPasswordLabel}
variant="outlined"
/>
<TextField
{...getFieldHelpers("password")}
onChange={onChangeTrimmed(form)}
autoComplete="password"
fullWidth
label={Language.newPasswordLabel}
variant="outlined"
/>
<TextField
{...getFieldHelpers("confirm_password")}
onChange={onChangeTrimmed(form)}
autoComplete="confirm_password"
fullWidth
label={Language.confirmPasswordLabel}
variant="outlined"
/>

{error && <FormHelperText error>{error}</FormHelperText>}

<div>
<LoadingButton loading={isLoading} type="submit" variant="contained">
{isLoading ? "" : Language.updatePassword}
</LoadingButton>
</div>
</Stack>
</form>
</>
)
}
12 changes: 0 additions & 12 deletions site/src/pages/SettingsPages/AccountPage/LinkedAccountsPage.tsx

This file was deleted.

107 changes: 107 additions & 0 deletions site/src/pages/SettingsPages/SecurityPage/SecurityPage.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { fireEvent, screen, waitFor } from "@testing-library/react"
import React from "react"
import * as API from "../../../api/api"
import { GlobalSnackbar } from "../../../components/GlobalSnackbar/GlobalSnackbar"
import * as AccountForm from "../../../components/SettingsAccountForm/SettingsAccountForm"
import { renderWithAuth } from "../../../testHelpers/renderHelpers"
import * as AuthXService from "../../../xServices/auth/authXService"
import { SecurityPage, Language } from "./SecurityPage"

const renderPage = () => {
return renderWithAuth(
<>
<AccountPage />
<GlobalSnackbar />
</>,
)
}

const newData = {
email: "user@coder.com",
username: "user",
}

const fillAndSubmitForm = async () => {
await waitFor(() => screen.findByLabelText("Email"))
fireEvent.change(screen.getByLabelText("Email"), { target: { value: newData.email } })
fireEvent.change(screen.getByLabelText("Username"), { target: { value: newData.username } })
fireEvent.click(screen.getByText(AccountForm.Language.updateSettings))
}

describe("AccountPage", () => {
describe("when it is a success", () => {
it("shows the success message", async () => {
jest.spyOn(API, "updateProfile").mockImplementationOnce((userId, data) =>
Promise.resolve({
id: userId,
created_at: new Date().toString(),
status: "active",
organization_ids: ["123"],
roles: [],
...data,
}),
)
const { user } = renderPage()
await fillAndSubmitForm()

const successMessage = await screen.findByText(AuthXService.Language.successProfileUpdate)
expect(successMessage).toBeDefined()
expect(API.updateProfile).toBeCalledTimes(1)
expect(API.updateProfile).toBeCalledWith(user.id, newData)
})
})

describe("when the email is already taken", () => {
it("shows an error", async () => {
jest.spyOn(API, "updateProfile").mockRejectedValueOnce({
isAxiosError: true,
response: {
data: { message: "Invalid profile", errors: [{ detail: "Email is already in use", field: "email" }] },
},
})

const { user } = renderPage()
await fillAndSubmitForm()

const errorMessage = await screen.findByText("Email is already in use")
expect(errorMessage).toBeDefined()
expect(API.updateProfile).toBeCalledTimes(1)
expect(API.updateProfile).toBeCalledWith(user.id, newData)
})
})

describe("when the username is already taken", () => {
it("shows an error", async () => {
jest.spyOn(API, "updateProfile").mockRejectedValueOnce({
isAxiosError: true,
response: {
data: { message: "Invalid profile", errors: [{ detail: "Username is already in use", field: "username" }] },
},
})

const { user } = renderPage()
await fillAndSubmitForm()

const errorMessage = await screen.findByText("Username is already in use")
expect(errorMessage).toBeDefined()
expect(API.updateProfile).toBeCalledTimes(1)
expect(API.updateProfile).toBeCalledWith(user.id, newData)
})
})

describe("when it is an unknown error", () => {
it("shows a generic error message", async () => {
jest.spyOn(API, "updateProfile").mockRejectedValueOnce({
data: "unknown error",
})

const { user } = renderPage()
await fillAndSubmitForm()

const errorMessage = await screen.findByText(Language.unknownError)
expect(errorMessage).toBeDefined()
expect(API.updateProfile).toBeCalledTimes(1)
expect(API.updateProfile).toBeCalledWith(user.id, newData)
})
})
})
42 changes: 42 additions & 0 deletions site/src/pages/SettingsPages/SecurityPage/SecurityPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { useActor } from "@xstate/react"
import React, { useContext } from "react"
import { isApiError, mapApiErrorToFieldErrors } from "../../../api/errors"
import { Section } from "../../../components/Section/Section"
import { SecurityForm } from "../../../components/SettingsSecurityForm/SettingsSecurityForm"
import { XServiceContext } from "../../../xServices/StateContext"

export const Language = {
title: "Security",
unknownError: "Oops, an unknown error occurred.",
}

export const AccountPage: React.FC = () => {
const xServices = useContext(XServiceContext)
const [authState, authSend] = useActor(xServices.authXService)
const { me, updateProfileError } = authState.context
const hasError = !!updateProfileError
const formErrors =
hasError && isApiError(updateProfileError) ? mapApiErrorToFieldErrors(updateProfileError.response.data) : undefined
const hasUnknownError = hasError && !isApiError(updateProfileError)

if (!me) {
throw new Error("No current user found")
}

return (
<Section title={Language.title}>
<SecurityForm
error={hasUnknownError ? Language.unknownError : undefined}
formErrors={formErrors}
isLoading={authState.matches("signedIn.profile.updatingProfile")}
initialValues={{ old_password: "", password: "", confirm_password: "" }}
onSubmit={(data) => {
authSend({
type: "UPDATE_PASSWORD",
data,
})
}}
/>
</Section>
)
}
2 changes: 1 addition & 1 deletion site/src/pages/UsersPage/UsersPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ describe("Users Page", () => {

// Check if the API was called correctly
expect(API.updateUserPassword).toBeCalledTimes(1)
expect(API.updateUserPassword).toBeCalledWith(expect.any(String), MockUser.id)
expect(API.updateUserPassword).toBeCalledWith(MockUser.id, {password: expect.any(String), old_password: ""})
})
})

Expand Down
16 changes: 16 additions & 0 deletions site/src/xServices/auth/authXService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export interface AuthContext {
getMethodsError?: Error | unknown
authError?: Error | unknown
updateProfileError?: Error | unknown
updateSecurityError?: Error | unknown
me?: TypesGen.User
methods?: TypesGen.AuthMethods
permissions?: Permissions
Expand All @@ -64,6 +65,7 @@ export type AuthEvent =
| { type: "SIGN_OUT" }
| { type: "SIGN_IN"; email: string; password: string }
| { type: "UPDATE_PROFILE"; data: TypesGen.UpdateUserProfileRequest }
| { type: "UPDATE_SECURITY"; data: TypesGen.UpdateUserPasswordRequest }
| { type: "GET_SSH_KEY" }
| { type: "REGENERATE_SSH_KEY" }
| { type: "CONFIRM_REGENERATE_SSH_KEY" }
Expand Down Expand Up @@ -145,6 +147,7 @@ export const authMachine =
getUserError: undefined,
authError: undefined,
updateProfileError: undefined,
updateSecurityError: undefined,
methods: undefined,
getMethodsError: undefined,
},
Expand All @@ -165,6 +168,9 @@ export const authMachine =
updateProfile: {
data: TypesGen.User
}
updateSecurity: {
data: TypesGen.UpdateUserPasswordRequest
}
checkPermissions: {
data: TypesGen.UserAuthorizationResponse
}
Expand Down Expand Up @@ -279,6 +285,9 @@ export const authMachine =
UPDATE_PROFILE: {
target: "updatingProfile",
},
UPDATE_SECURITY: {
target: "updatingSecurity",
},
},
},
updatingProfile: {
Expand Down Expand Up @@ -345,6 +354,13 @@ export const authMachine =

return API.updateProfile(context.me.id, event.data)
},
updateSecurity: async (context, event) => {
if (!context.me) {
throw new Error("No current user found")
}

return API.updateUserPassword(context.me.id, event.data)
},
checkPermissions: async (context) => {
if (!context.me) {
throw new Error("No current user found")
Expand Down
2 changes: 1 addition & 1 deletion site/src/xServices/users/usersXService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ export const usersMachine = createMachine(
throw new Error("newUserPassword not generated")
}

return API.updateUserPassword(context.newUserPassword, context.userIdToResetPassword)
return API.updateUserPassword(context.userIdToResetPassword, {password: context.newUserPassword, old_password: ""})
},
updateUserRoles: (context, event) => {
if (!context.userIdToUpdateRoles) {
Expand Down