diff --git a/server/routes/blaiseApi.ts b/server/routes/blaiseApi.ts index b7695e6..6d1c0a9 100644 --- a/server/routes/blaiseApi.ts +++ b/server/routes/blaiseApi.ts @@ -55,10 +55,6 @@ export default function blaiseApi(config: CustomConfig, auth: Auth, blaiseApiCli }); router.get("/api/users/:user", auth.Middleware, async function (req: Request, res: Response) { - if (!req.params.user) { - return res.status(400).json("No user provided"); - } - try { const user = await blaiseApiClient.getUser(req.params.user); const successMessage = `Successfully fetched user details for ${req.params.user}`; @@ -75,19 +71,19 @@ export default function blaiseApi(config: CustomConfig, auth: Auth, blaiseApiCli } }); - router.get("/api/change-password/:user", auth.Middleware, async function (req: Request, res: Response) { + router.post("/api/change-password/:user", auth.Middleware, async function (req: Request, res: Response) { const currentUser = auth.GetUser(auth.GetToken(req)); - let { password } = req.headers; + const data = req.body; - if (Array.isArray(password)) { - password = password.join(""); + if (Array.isArray(data.password)) { + data.password = data.password.join(""); } - if (!req.params.user || !password) { + if (!req.params.user || !data.password) { return res.status(400).json("No user or password provided"); } - blaiseApiClient.changePassword(req.params.user, password).then(() => { + blaiseApiClient.changePassword(req.params.user, data.password).then(() => { auditLogger.info(req.log, `${currentUser.name || "Unknown"} has successfully changed the password for ${req.params.user}`); return res.status(204).json(null); }).catch((error: unknown) => { @@ -123,7 +119,7 @@ export default function blaiseApi(config: CustomConfig, auth: Auth, blaiseApiCli const currentUser = auth.GetUser(auth.GetToken(req)); const data = req.body; - if(!data.role) { + if (!data.role) { return res.status(400).json({ message: "No role provided for user creation" }); } diff --git a/server/tests/routes/blaiseApi.test.ts b/server/tests/routes/blaiseApi.test.ts index 96430ab..d8ded84 100644 --- a/server/tests/routes/blaiseApi.test.ts +++ b/server/tests/routes/blaiseApi.test.ts @@ -54,15 +54,14 @@ describe("POST /api/users endpoint", () => { it("should call Blaise API createUser endpoint with correct serverParks for each role EXISTING in server/role-to-serverparks-map.json AND return http status OK_200", async () => { let currentRoleNo = 0; const totalRoleCount = size(role_to_serverparks_map); - for (const roleName in role_to_serverparks_map) - { + for (const roleName in role_to_serverparks_map) { logInfo.mockReset(); blaiseApiMock.reset(); console.log("Running for role %i of %i: %s", ++currentRoleNo, totalRoleCount, roleName); const spmap = role_to_serverparks_map[roleName]; - const newUser : NewUser = { - name: "name1", + const newUser: NewUser = { + name: "name1", password: "password1", role: roleName, serverParks: spmap, @@ -78,7 +77,7 @@ describe("POST /api/users endpoint", () => { expect(logInfo.mock.calls[0][0]).toEqual(`AUDIT_LOG: ${mockUser.name} has successfully created user, ${newUser.name}, with an assigned role of ${roleName}`); expect(response.statusCode).toEqual(200); blaiseApiMock.verify(a => a.createUser(It.is( - x=> x.defaultServerPark == newUser.defaultServerPark + x => x.defaultServerPark == newUser.defaultServerPark && x.role == newUser.role && Array.isArray(x.serverParks) && x.serverParks.every(item => typeof item === "string") && x.serverParks.every((val, idx) => val === newUser.serverParks[idx]) @@ -90,8 +89,8 @@ describe("POST /api/users endpoint", () => { it("should call Blaise API createUser endpoint with DEFAULT serverParks for a role MISSING in server/role-to-serverparks-map.json AND return http status OK_200)", async () => { const roleName = "this role is missing in server/role-to-serverparks-map.json file"; const spmap = role_to_serverparks_map.DEFAULT; - const newUser : NewUser = { - name: "name1", + const newUser: NewUser = { + name: "name1", password: "password1", role: roleName, serverParks: spmap, @@ -108,7 +107,7 @@ describe("POST /api/users endpoint", () => { expect(log).toEqual(`AUDIT_LOG: ${mockUser.name} has successfully created user, ${newUser.name}, with an assigned role of ${roleName}`); expect(response.statusCode).toEqual(200); blaiseApiMock.verify(a => a.createUser(It.is( - x=> x.defaultServerPark == newUser.defaultServerPark + x => x.defaultServerPark == newUser.defaultServerPark && x.role == newUser.role && Array.isArray(x.serverParks) && x.serverParks.every(item => typeof item === "string") && x.serverParks.every((val, idx) => val === newUser.serverParks[idx]) @@ -133,8 +132,8 @@ describe("POST /api/users endpoint", () => { it("should return http status INTERNAL_SERVER_ERROR_500 if Blaise API client throws an error", async () => { const roleName = "IPS Manager"; const spmap = role_to_serverparks_map.DEFAULT; - const newUser : NewUser = { - name: "name1", + const newUser: NewUser = { + name: "name1", password: "password1", role: roleName, serverParks: spmap, @@ -215,8 +214,8 @@ describe("GET /api/users endpoint", () => { }); it("should call Blaise API getUsers endpoint AND return http status OK_200", async () => { - const newUser1 : NewUser = { - name: "name1", + const newUser1: NewUser = { + name: "name1", password: "password1", role: "role1", serverParks: ["sp1", "sp2"], @@ -226,7 +225,7 @@ describe("GET /api/users endpoint", () => { newUser2.name = "name2"; const newUser3 = newUser2; newUser3.name = "name3"; - const userArray : NewUser [] = [newUser1, newUser2, newUser3]; + const userArray: NewUser[] = [newUser1, newUser2, newUser3]; blaiseApiMock.setup((api) => api.getUsers()).returns(_ => Promise.resolve(userArray)); const response = await sut.get("/api/users") @@ -243,8 +242,8 @@ describe("GET /api/roles endpoint", () => { }); it("should call Blaise API getUserRoles endpoint AND return http status OK_200", async () => { - const userRole1 : UserRole = { - name: "name1", + const userRole1: UserRole = { + name: "name1", description: "desc1", permissions: ["perm1", "perm2"] }; @@ -252,7 +251,7 @@ describe("GET /api/roles endpoint", () => { userRole2.name = "name2"; const userRole3 = userRole2; userRole3.name = "name3"; - const userRoleArray : UserRole [] = [userRole1, userRole2, userRole3]; + const userRoleArray: UserRole[] = [userRole1, userRole2, userRole3]; blaiseApiMock.setup((api) => api.getUserRoles()).returns(_ => Promise.resolve(userRoleArray)); const response = await sut.get("/api/roles") @@ -263,24 +262,22 @@ describe("GET /api/roles endpoint", () => { }); }); -describe("GET /api/change-password/:user endpoint", () => { +describe("POST /api/change-password/:user endpoint", () => { beforeEach(() => { blaiseApiMock.reset(); jest.clearAllMocks(); }); - afterAll(() => { blaiseApiMock.reset(); }); - it("should call Blaise API changePassword endpoint for VALID request AND return http status NO_CONTENT_204", async () => { const username = "user1"; const password = "password-1234"; blaiseApiMock.setup((api) => api.changePassword(It.isAnyString(), It.isAnyString())).returns(_ => Promise.resolve(null)); - const response = await sut.get("/api/change-password/"+username) + const response = await sut.post(`/api/change-password/${username}`) .set("Authorization", `${mockAuthToken}`) - .set("password", password); + .field("password", password); const log = logInfo.mock.calls[0][0]; expect(log).toEqual(`AUDIT_LOG: ${mockUser.name} has successfully changed the password for ${username}`); @@ -292,9 +289,9 @@ describe("GET /api/change-password/:user endpoint", () => { const username = "user1"; const password = ""; - const response = await sut.get("/api/change-password/"+ username) + const response = await sut.post(`/api/change-password/${username}`) .set("Authorization", `${mockAuthToken}`) - .set("password", password); + .field("password", password); expect(response.statusCode).toEqual(400); blaiseApiMock.verify(a => a.changePassword(It.isAnyString(), It.isAnyString()), Times.never()); @@ -304,12 +301,11 @@ describe("GET /api/change-password/:user endpoint", () => { const username = "user1"; const password = "password-1234"; const errorMessage = "Error occured when calling changePassword on Blaise API Rest Service"; - blaiseApiMock.setup((a) => a.changePassword(It.isAnyString(), It.isAnyString())) - .returns(_ => Promise.reject(errorMessage)); + blaiseApiMock.setup((api) => api.changePassword(It.isAnyString(), It.isAnyString())).returns(_ => Promise.reject(errorMessage)); - const response = await sut.get("/api/change-password/"+ username) + const response = await sut.post(`/api/change-password/${username}`) .set("Authorization", `${mockAuthToken}`) - .set("password", password); + .field("password", password); const log = logError.mock.calls[0][0]; expect(log).toEqual(`AUDIT_LOG: Error whilst trying to change password for ${username}: ${errorMessage}`); @@ -317,6 +313,30 @@ describe("GET /api/change-password/:user endpoint", () => { blaiseApiMock.verify(a => a.changePassword(It.isAnyString(), It.isAnyString()), Times.once()); expect(response.body).toStrictEqual(errorMessage); }); + + it("should call Blaise API changePassword endpoint for VALID request even if password is array of characters AND return http status NO_CONTENT_204 ", async () => { + const username = "user1"; + const password = ["p", "a", "s", "s", "w", "o", "r", "d"]; + blaiseApiMock.setup((api) => api.changePassword(It.isAnyString(), It.isAnyString())).returns(_ => Promise.resolve(null)); + + const response = await sut.post(`/api/change-password/${username}`) + .set("Authorization", `${mockAuthToken}`) + .field("password", password); + + const log = logInfo.mock.calls[0][0]; + expect(log).toEqual(`AUDIT_LOG: ${mockUser.name} has successfully changed the password for ${username}`); + expect(response.statusCode).toEqual(204); + blaiseApiMock.verify(a => a.changePassword(It.isValue(username), It.isValue("password")), Times.once()); + }); + + it("should join the password if an array is passed", async () => { + const data: { password: string | string[] } = { password: ["p", "a", "s", "s", "w", "o", "r", "d"] }; + + if (Array.isArray(data.password)) { + data.password = data.password.join(""); + } + expect(data.password).toBe("password"); + }); }); describe("PATCH /api/users/:user/rolesAndPermissions endpoint", () => { @@ -381,4 +401,46 @@ describe("PATCH /api/users/:user/rolesAndPermissions endpoint", () => { expect(response.statusCode).toEqual(500); expect(response.body.message).toContain("Failed to update user role and permissions to admin for testUser"); }); -}); \ No newline at end of file +}); + +describe("GET /api/users/:user endpoint", () => { + beforeEach(() => { + blaiseApiMock.reset(); + jest.clearAllMocks(); + }); + afterAll(() => { + blaiseApiMock.reset(); + }); + + it("should call Blaise API getUser endpoint if user param is valid and return user if exists in blaise", async () => { + + const user: NewUser = { + name: "test", + password: "password1", + role: "DST", + serverParks: ["gusty", "cma"], + defaultServerPark: "gusty" + }; + + blaiseApiMock.setup((api) => api.getUser(It.isAnyString())).returns(async () => user); + const response = await sut.get("/api/users/test") + .set("Authorization", `${mockAuthToken}`); + + blaiseApiMock.verify(api => api.getUser(It.isValue("test")), Times.once()); + expect(response.statusCode).toEqual(200); + expect(response.body.data).toEqual(user); + }); + + it("should call Blaise API getUser endpoint if user param is valid and return error if user does not exists in blaise", async () => { + + const errorMessage = "Blaise API client error"; + blaiseApiMock.setup((api) => api.getUser(It.isAnyString())).returns(_ => Promise.reject(errorMessage)); + const response = await sut.get("/api/users/invalidUser") + .set("Authorization", `${mockAuthToken}`); + + expect(response.statusCode).toEqual(500); + expect(response.body.message).toContain("Error whilst trying to retrieve user"); + expect(response.body.error).toEqual(errorMessage); + }); + +}); diff --git a/src/api/http/users.test.ts b/src/api/http/users.test.ts index ef4387a..e48beca 100644 --- a/src/api/http/users.test.ts +++ b/src/api/http/users.test.ts @@ -1,11 +1,20 @@ /** * @jest-environment jsdom */ - import { cleanup } from "@testing-library/react"; import { mock_server_request_function, mock_server_request_Return_JSON } from "../../tests/utils"; -import { addNewUser, deleteUser, getAllUsers } from "./users"; +import { addNewUser, deleteUser, editPassword, getAllUsers } from "./users"; import { NewUser, User } from "blaise-api-node-client"; +import { requestPromiseJson } from "./requestPromise"; + +jest.mock("./requestPromise", () => { + const actualModule = jest.requireActual("./requestPromise"); + return { + ...actualModule, + requestPromiseJson: jest.fn() + }; +}); +const requestPromiseJsonMock = requestPromiseJson as jest.Mock>; const userList: User[] = [ { defaultServerPark: "gusty", name: "TestUser123", role: "DST", serverParks: ["gusty"] }, @@ -57,7 +66,6 @@ describe("Function getAllUsers(filename: string) ", () => { mock_server_request_function(jest.fn(() => { throw new Error("Network error"); })); - const [success, users] = await getAllUsers(); expect(success).toBeFalsy(); expect(users).toEqual([]); @@ -79,14 +87,20 @@ const newUser: NewUser = { describe("Function addNewUser(user: User) ", () => { + let promiseResponse: [number, JSON]; + it("It should return true if the user has been created successfully", async () => { - mock_server_request_Return_JSON(201, {}); + promiseResponse = [201, JSON.parse("{}")]; + requestPromiseJsonMock.mockResolvedValue(promiseResponse); + const success = await addNewUser(newUser); expect(success).toBeTruthy(); }); it("It should return false if a password is not provided", async () => { - mock_server_request_Return_JSON(201, {}); + promiseResponse = [201, JSON.parse("{}")]; + requestPromiseJsonMock.mockResolvedValue(promiseResponse); + const newUser: NewUser = { defaultServerPark: "", name: "username", @@ -100,22 +114,21 @@ describe("Function addNewUser(user: User) ", () => { }); it("It should return false if a 404 is returned from the server", async () => { - mock_server_request_Return_JSON(404, []); + promiseResponse = [404, JSON.parse("[]")]; + requestPromiseJsonMock.mockResolvedValue(promiseResponse); const success = await addNewUser(newUser); expect(success).toBeFalsy(); }); it("It should return false if request returns an error code", async () => { - mock_server_request_Return_JSON(500, {}); + promiseResponse = [500, JSON.parse("{}")]; + requestPromiseJsonMock.mockResolvedValue(promiseResponse); const success = await addNewUser(newUser); expect(success).toBeFalsy(); }); it("It should return false if request call fails", async () => { - mock_server_request_function(jest.fn(() => { - throw new Error("Network error"); - })); - + requestPromiseJsonMock.mockRejectedValue(new Error("Async error")); const success = await addNewUser(newUser); expect(success).toBeFalsy(); }); @@ -129,30 +142,31 @@ describe("Function addNewUser(user: User) ", () => { describe("Function deleteUser(username: string) ", () => { const userToDelete = "dave01"; + let promiseResponse: [number, JSON]; it("It should return true if the user has been deleted successfully", async () => { - mock_server_request_Return_JSON(204, {}); + promiseResponse = [204, JSON.parse("{}")]; + requestPromiseJsonMock.mockResolvedValue(promiseResponse); const success = await deleteUser(userToDelete); expect(success).toBeTruthy(); }); it("It should return false if a 404 is returned from the server", async () => { - mock_server_request_Return_JSON(404, []); + promiseResponse = [404, JSON.parse("[]")]; + requestPromiseJsonMock.mockResolvedValue(promiseResponse); const success = await deleteUser(userToDelete); expect(success).toBeFalsy(); }); it("It should return false if request returns an error code", async () => { - mock_server_request_Return_JSON(500, {}); + promiseResponse = [500, JSON.parse("{}")]; + requestPromiseJsonMock.mockResolvedValue(promiseResponse); const success = await deleteUser(userToDelete); expect(success).toBeFalsy(); }); it("It should return false if request call fails", async () => { - mock_server_request_function(jest.fn(() => { - throw new Error("Network error"); - })); - + requestPromiseJsonMock.mockRejectedValue(new Error("Network error")); const success = await deleteUser(userToDelete); expect(success).toBeFalsy(); }); @@ -162,3 +176,52 @@ describe("Function deleteUser(username: string) ", () => { cleanup(); }); }); + +describe("Function editPassword(username: string, newPassword: string) ", () => { + + const username = "testUser"; + const newPassword = "password123"; + + let promiseResponse: [number, JSON]; + + it("It should return true if the password has been updated successfully", async () => { + promiseResponse = [204, JSON.parse("{}")]; + requestPromiseJsonMock.mockResolvedValue(promiseResponse); + const response = await editPassword(username, newPassword); + expect(response).toBeTruthy(); + }); + + it("It should return false if a password is not provided", async () => { + const invalidPassword = ""; + + const response = await editPassword(username, invalidPassword); + expect(response).toBeFalsy(); + }); + + it("It should return false if a 404 is returned from the server", async () => { + promiseResponse = [404, JSON.parse("{}")]; + requestPromiseJsonMock.mockResolvedValue(promiseResponse); + const response = await editPassword(username, newPassword); + expect(response).toBeFalsy(); + }); + + it("It should return false if request returns an error code", async () => { + promiseResponse = [500, JSON.parse("{}")]; + requestPromiseJsonMock.mockResolvedValue(promiseResponse); + + const response = await editPassword(username, newPassword); + expect(response).toBeFalsy(); + }); + + it("It should return false if request call fails", async () => { + requestPromiseJsonMock.mockRejectedValue(new Error("Async error")); + + const response = await editPassword(username, newPassword); + expect(response).toBeFalsy(); + }); + + afterAll(() => { + jest.clearAllMocks(); + cleanup(); + }); +}); \ No newline at end of file diff --git a/src/api/http/users.ts b/src/api/http/users.ts index 8a6de3b..2cab72d 100644 --- a/src/api/http/users.ts +++ b/src/api/http/users.ts @@ -105,4 +105,29 @@ async function patchUserRolesAndPermissions(user: string, role: string): Promise } } -export { getAllUsers, getUser, addNewUser, deleteUser, patchUserRolesAndPermissions }; +function editPassword(username: string, newPassword: string): Promise { + const url = "/api/change-password/" + username; + const authManager = new AuthManager(); + const headers = authManager.authHeader(); + return new Promise((resolve: (object: boolean) => void) => { + + if (username == "" || username == undefined || newPassword == "" || newPassword == undefined) { + resolve(false); + return; + } + + const formData = new FormData(); + formData.append("password", newPassword); + + requestPromiseJson("POST", url, formData, headers).then(([status]) => { + if (status === 204) + resolve(true); + resolve(false); + + }).catch(() => { + resolve(false); + }); + }); +} + +export { getAllUsers, getUser, addNewUser, deleteUser, patchUserRolesAndPermissions, editPassword }; diff --git a/src/pages/users/UserProfileEdits/ChangePassword.test.tsx b/src/pages/users/UserProfileEdits/ChangePassword.test.tsx index 9efe36b..5cf3e26 100644 --- a/src/pages/users/UserProfileEdits/ChangePassword.test.tsx +++ b/src/pages/users/UserProfileEdits/ChangePassword.test.tsx @@ -1,10 +1,12 @@ import React from "react"; -import { render, cleanup } from "@testing-library/react"; +import { render, screen, cleanup } from "@testing-library/react"; import "@testing-library/jest-dom"; -import { MemoryRouter, useParams } from "react-router-dom"; +import { MemoryRouter, Route, Routes, useParams } from "react-router-dom"; import userEvent from "@testing-library/user-event"; import { act } from "react-dom/test-utils"; import ChangePassword from "./ChangePassword"; +import UserProfile from "./UserProfile"; +import { editPassword } from "../../../api/http/users"; jest.mock("react-router-dom", () => ({ // eslint-disable-next-line @typescript-eslint/ban-ts-comment @@ -21,12 +23,12 @@ jest.mock("blaise-login-react/blaise-login-react-client", () => ({ })) })); -global.fetch = jest.fn(() => - Promise.resolve({ - status: 204, - json: () => Promise.resolve({ message: "Password changed successfully" }) - }) -) as jest.Mock; +jest.mock("../../../api/http/users", () => ({ + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error + ...jest.requireActual("../../../api/http/users"), + editPassword: jest.fn() +})); const mockUserDetails = { name: "testUser" @@ -38,7 +40,7 @@ const mockState = { }; beforeEach(() => { - (fetch as jest.Mock).mockClear(); + (editPassword as jest.Mock).mockClear(); (useParams as jest.Mock).mockReturnValue({ user: mockUserDetails.name }); }); @@ -98,7 +100,7 @@ describe("ChangePassword Component", () => { expect(await findByText(/Passwords do not match/i)).toBeVisible(); }); - it("calls fetch with correct parameters upon form submission with matching passwords that remove any trailing whitespaces", async () => { + it("calls editPassword function with correct parameters upon form submission with correct username and password without any trailing whitespaces", async () => { const { getByLabelText, getByText } = render( @@ -116,15 +118,10 @@ describe("ChangePassword Component", () => { userEvent.click(saveButton); }); - expect(fetch).toHaveBeenCalledWith("/api/change-password/testUser", { - headers: { - Authorization: process.env.MOCK_AUTH_TOKEN, - password: "password123" - } - }); + expect(editPassword).toHaveBeenCalledWith("testUser", "password123"); }); - it("calls fetch with correct parameters upon form submission with matching passwords", async () => { + it("calls editPassword function with correct parameters upon form submission with correct username and password", async () => { const { getByLabelText, getByText, findByText } = render( @@ -142,11 +139,85 @@ describe("ChangePassword Component", () => { userEvent.click(saveButton); }); - expect(fetch).toHaveBeenCalledWith("/api/change-password/testUser", { - headers: { - Authorization: process.env.MOCK_AUTH_TOKEN, - password: "password123" - } + expect(editPassword).toHaveBeenCalledWith("testUser", "password123"); + }); + + it("displays error message if the function returns false", async () => { + const { getByLabelText, getByText, findByText } = render( + + + + ); + + const newPasswordInput = getByLabelText("New password"); + const confirmPasswordInput = getByLabelText("Confirm password"); + const saveButton = getByText("Save"); + + (editPassword as jest.Mock).mockResolvedValue(false); + act(() => { + userEvent.type(newPasswordInput, "password123"); + userEvent.type(confirmPasswordInput, "password123"); + userEvent.click(saveButton); + }); + + expect(editPassword).toHaveBeenCalledWith("testUser", "password123"); + expect(await findByText(/Set password failed/i)).toBeVisible(); + }); + + it("displays success message if the function returns true", async () => { + + const initalPath = `/users/${mockUserDetails.name}/change-password`; + const destinationPath = `/users/${mockUserDetails.name}`; + + const { getByLabelText, getByText, findByText } = render( + + + } + /> + + } + /> + + + ); + + const newPasswordInput = getByLabelText("New password"); + const confirmPasswordInput = getByLabelText("Confirm password"); + const saveButton = getByText("Save"); + + (editPassword as jest.Mock).mockResolvedValue(true); + act(() => { + userEvent.type(newPasswordInput, "password123"); + userEvent.type(confirmPasswordInput, "password123"); + userEvent.click(saveButton); }); + expect(await findByText(/Loading/i)).toBeVisible(); + expect(editPassword).toHaveBeenCalledWith("testUser", "password123"); + expect(screen.getByText("Password successfully changed for user called testUser")).toBeInTheDocument(); }); + + it("renders UserSignInErrorPanel when currentUser is null", () => { + const invalidState = { + pathname: `/users/${mockUserDetails.name}/change-password`, + state: { currentUser: null } + }; + render( + + + + ); + + expect(screen.getByText("Sorry, there is a problem")).toBeInTheDocument(); + expect( + screen.getByText( + /User details cannot be found\.\s*Please try again and ensure you are signed in\./i + ) + ).toBeInTheDocument(); + }); + }); \ No newline at end of file diff --git a/src/pages/users/UserProfileEdits/ChangePassword.tsx b/src/pages/users/UserProfileEdits/ChangePassword.tsx index 1a4a4b7..69f05d6 100644 --- a/src/pages/users/UserProfileEdits/ChangePassword.tsx +++ b/src/pages/users/UserProfileEdits/ChangePassword.tsx @@ -6,6 +6,7 @@ import { AuthManager } from "blaise-login-react/blaise-login-react-client"; import { UserRouteParams } from "../../../Interfaces/usersPage"; import Breadcrumbs from "../../../Components/Breadcrumbs"; import UserSignInErrorPanel from "../../../Components/UserSignInErrorPanel"; +import { editPassword } from "../../../api/http/users"; export default function ChangePassword(): ReactElement { const { user: viewedUsername }: UserRouteParams = useParams() as unknown as UserRouteParams; @@ -17,7 +18,7 @@ export default function ChangePassword(): ReactElement { const [message, setMessage] = useState(""); const [redirect, setRedirect] = useState(false); - const changePassword = () => { + const changePassword = async () => { const sanitisedPassword = password.trim(); const sanitisedConfirmPassword = confirmPassword.trim(); @@ -31,26 +32,16 @@ export default function ChangePassword(): ReactElement { } setButtonLoading(true); - const authManager = new AuthManager(); - fetch("/api/change-password/" + viewedUsername, - { - "headers": Object.assign({}, { - "password": sanitisedPassword - }, authManager.authHeader()) - }) - .then((r: Response) => { - if (r.status === 204) { - setButtonLoading(false); - setRedirect(true); - } else { - setMessage("Set password failed"); - setButtonLoading(false); - } - }).catch(() => { - setMessage("Set password failed"); - setButtonLoading(false); - }); + const updated = await editPassword(viewedUsername, sanitisedPassword); + + if (!updated) { + setMessage("Set password failed"); + setButtonLoading(false); + } + + setButtonLoading(false); + setRedirect(true); }; const breadcrumbList: BreadcrumbItem[] = [ @@ -60,7 +51,7 @@ export default function ChangePassword(): ReactElement { ]; if (!currentUser) { - return (); + return (); } return (