Skip to content

Commit

Permalink
Implement create password functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
DanZfsd committed Nov 29, 2024
1 parent 9bbdc2e commit c56e80f
Show file tree
Hide file tree
Showing 19 changed files with 542 additions and 3 deletions.
28 changes: 28 additions & 0 deletions backend/typescript/rest/authRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,34 @@ authRouter.post(
},
);

// updates user password and updates status
authRouter.post(
"/setPassword/:email",
isAuthorizedByEmail("email"),
async (req, res) => {
try {
const responseSuccess = await authService.setPassword(
req.params.email,
req.body.newPassword,
);
if (responseSuccess.success) {
const user = await userService.getUserByEmail(req.params.email);
if (user.status === UserStatus.INVITED) {
userService.updateUserById(user.id, {
...user,
status: UserStatus.ACTIVE,
});
}
res.status(200).json(responseSuccess);
} else {
res.status(400).json(responseSuccess);
}
} catch (error) {
res.status(500).json({ error: getErrorMessage(error) });
}
},
);

/* Invite a user */
authRouter.post("/invite-user", inviteUserDtoValidator, async (req, res) => {
try {
Expand Down
25 changes: 24 additions & 1 deletion backend/typescript/services/implementations/authService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import * as firebaseAdmin from "firebase-admin";
import IAuthService from "../interfaces/authService";
import IEmailService from "../interfaces/emailService";
import IUserService from "../interfaces/userService";
import { AuthDTO, Role, Token } from "../../types";
import { AuthDTO, Role, Token, ResponseSuccessDTO } from "../../types";
import { getErrorMessage } from "../../utilities/errorUtils";
import FirebaseRestClient from "../../utilities/firebaseRestClient";
import logger from "../../utilities/logger";
Expand Down Expand Up @@ -286,6 +286,29 @@ class AuthService implements IAuthService {
return false;
}
}

async setPassword(
email: string,
newPassword: string,
): Promise<ResponseSuccessDTO> {
let errorMessage = "An unknown error occured. Please try again later.";
try {
const uid = await (await firebaseAdmin.auth().getUserByEmail(email)).uid;
await firebaseAdmin.auth().updateUser(uid, {
password: newPassword,
});
return { success: true } as ResponseSuccessDTO;
} catch (error: any) {

Check warning on line 301 in backend/typescript/services/implementations/authService.ts

View workflow job for this annotation

GitHub Actions / run-lint

Unexpected any. Specify a different type
Logger.error(`Failed to update password. Error: ${error}`);
if (error.code === "auth/invalid-password") {
errorMessage =
"Password is too weak! Make sure it matches the password policy in Firebase.";
} else if (error.code === "auth/user-not-found") {
errorMessage = "No user found with the provided email!";
}
return { success: false, errorMessage };
}
}
}

export default AuthService;
10 changes: 9 additions & 1 deletion backend/typescript/services/interfaces/authService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AuthDTO, Role, Token } from "../../types";
import { AuthDTO, Role, Token, ResponseSuccessDTO } from "../../types";

interface IAuthService {
/**
Expand Down Expand Up @@ -98,6 +98,14 @@ interface IAuthService {
accessToken: string,
requestedEmail: string,
): Promise<boolean>;

/**
* Set password for the specified email.
* @param accessToken user's access token
* @param requestedEmail email address of requested user
* @returns success (boolean) and errorMessage (string)
*/
setPassword(email: string, newPassword: string): Promise<ResponseSuccessDTO>;
}

export default IAuthService;
5 changes: 5 additions & 0 deletions backend/typescript/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ export type RegisterUserDTO = Omit<CreateUserDTO, "role">;

export type AuthDTO = Token & UserDTO;

export type ResponseSuccessDTO = {
success: boolean;
errorMessage?: string;
};

export type Letters = "A" | "B" | "C" | "D";

const sexValues = ["M", "F"] as const;
Expand Down
1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"private": true,
"dependencies": {
"@apollo/client": "^3.3.16",
"@chakra-ui/icons": "^2.2.4",
"@chakra-ui/react": "^2.8.2",
"@emotion/react": "^11.11.4",
"@emotion/styled": "^11.11.5",
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
33 changes: 32 additions & 1 deletion frontend/src/APIClients/AuthAPIClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { signInWithEmailLink } from "firebase/auth";
import { FirebaseError } from "firebase/app";
import auth from "../firebase/firebase";
import AUTHENTICATED_USER_KEY from "../constants/AuthConstants";
import { AuthenticatedUser } from "../types/AuthTypes";
import { AuthenticatedUser, PasswordSetResponse } from "../types/AuthTypes";
import baseAPIClient from "./BaseAPIClient";
import {
getLocalStorageObjProperty,
Expand Down Expand Up @@ -144,6 +144,35 @@ const refresh = async (): Promise<boolean> => {
}
};

const getEmailOfCurrentUser = async (): Promise<string> => {
const email = getLocalStorageObjProperty(AUTHENTICATED_USER_KEY, "email");
if (typeof email === "string") {
return email;
}
throw new Error("Email not found for the current user");
};

const setPassword = async (
newPassword: string,
): Promise<PasswordSetResponse> => {
const bearerToken = `Bearer ${getLocalStorageObjProperty(
AUTHENTICATED_USER_KEY,
"accessToken",
)}`;
try {
const email = await getEmailOfCurrentUser();
// set password
const response = await baseAPIClient.post(
`/auth/setPassword/${email}`,
{ newPassword },
{ headers: { Authorization: bearerToken } },
);
return response.data;
} catch (error) {
return { success: false, errorMessage: "An unknown error occured." };
}
};

export default {
login,
loginWithSignInLink,
Expand All @@ -152,4 +181,6 @@ export default {
register,
resetPassword,
refresh,
setPassword,
getEmailOfCurrentUser,
};
7 changes: 7 additions & 0 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import SimpleEntityDisplayPage from "./components/pages/SimpleEntityDisplayPage"
import NotFound from "./components/pages/NotFound";
import UpdatePage from "./components/pages/UpdatePage";
import SimpleEntityUpdatePage from "./components/pages/SimpleEntityUpdatePage";
import CreatePasswordPage from "./components/pages/CreatePasswordPage";
import * as Routes from "./constants/Routes";
import * as AuthConstants from "./constants/AuthConstants";
import AUTHENTICATED_USER_KEY from "./constants/AuthConstants";
Expand Down Expand Up @@ -62,6 +63,12 @@ const App = (): React.ReactElement => {
<Switch>
<Route exact path={Routes.LOGIN_PAGE} component={Login} />
<Route exact path={Routes.SIGNUP_PAGE} component={Signup} />
<PrivateRoute
exact
path={Routes.CREATE_PASSWORD_PAGE}
component={CreatePasswordPage}
allowedRoles={AuthConstants.ALL_ROLES}
/>
<Route
exact
path={Routes.FORGOT_PASSWORD_PAGE}
Expand Down
Binary file added frontend/src/components/assets/background.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Box, Flex } from "@chakra-ui/react";
import React from "react";

interface ResponsiveAuthContainerProps {
children: React.ReactNode;
}

const ResponsiveAuthContainer = ({
children,
}: ResponsiveAuthContainerProps): React.ReactElement => {
return (
<Flex
padding={{
base: "2.25rem",
md: "2.5rem",
}}
background="var(--gray-100, #EDF2F7)"
borderRadius="0.375rem"
justifyContent="center"
>
<Box
display="inline-flex"
flexDirection="column"
gap={{ base: "1.12rem", md: "1rem" }}
width={{ md: "16rem" }}
justifyContent="center"
>
{children}
</Box>
</Flex>
);
};

export default ResponsiveAuthContainer;
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import React from "react";
import { Center, Image } from "@chakra-ui/react";

const ResponsiveLogo = (): React.ReactElement => {
return (
<Center
height={{ base: "8rem", md: "10.85rem" }}
aspectRatio="27.3/14"
bg="#2C5282"
borderRadius="2.6875rem"
border="1px solid var(--gray-200, #E2E8F0)"
>
<Image
src="/images/humane_society_logo_text.png"
alt="Humane Society Logo"
height={{ base: "6.5rem", md: "9rem" }}
aspectRatio="27.3/14"
objectFit="cover"
/>
</Center>
);
};

export default ResponsiveLogo;
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import React from "react";
import { Center, Flex } from "@chakra-ui/react";

interface ResponsiveModalWindowProps {
children: React.ReactNode; // Define children prop type
}

const ResponsiveModalWindow = ({
children,
}: ResponsiveModalWindowProps): React.ReactElement => {
return (
<Center
top="0"
left="0"
position="absolute"
height="100%"
width="100%"
bg="rgba(26, 32, 44, 0.60)"
>
<Flex
bg="var(--gray-50, #F7FAFC)"
align-items="center"
width={{ base: "90%", sm: "21.375rem", md: "33.625rem" }}
direction="column"
gap={{ base: "1rem", md: "2.8125rem" }}
maxWidth={{ base: "21.375rem", md: "none" }}
padding={{ base: "1.38rem 2.38rem", md: "3.6875rem 10.5rem" }}
borderRadius="0.375rem"
>
{children}
</Flex>
</Center>
);
};

export default ResponsiveModalWindow;
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import React from "react";
import {
IconButton,
Input,
InputGroup,
InputRightElement,
} from "@chakra-ui/react";
import { ViewIcon, ViewOffIcon } from "@chakra-ui/icons";

interface ResponsivePasswordInputProps {
value: string;
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
}

const ResponsivePasswordInput = ({
value,
onChange,
}: ResponsivePasswordInputProps): React.ReactElement => {
const [showPassword, setShowPassword] = React.useState(false);
const handlePasswordClick = () => setShowPassword(!showPassword);

return (
<InputGroup size="md">
<Input
fontSize="14px"
height="2.4rem"
pr="2rem"
type={showPassword ? "text" : "password"}
bg="#FFFFFF"
value={value}
onChange={onChange}
/>
<InputRightElement width="2rem">
{showPassword ? (
<IconButton
variant="unstyled"
isRound
bg="transparent"
onClick={handlePasswordClick}
aria-label="view"
icon={<ViewIcon />}
/>
) : (
<IconButton
variant="unstyled"
isRound
bg="transparent"
onClick={handlePasswordClick}
aria-label="hide"
icon={<ViewOffIcon />}
/>
)}
</InputRightElement>
</InputGroup>
);
};

export default ResponsivePasswordInput;
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// NOT CURRENTLY BEING USED IN PROD
// USED IN CASE YOU NEED TO ROTATE A BACKGROUND IMAGE
import React from "react";
import { Box, Flex } from "@chakra-ui/react";

const ResponsivePawprintBackground = (): React.ReactElement => {
return (
<Flex
position="absolute"
top="0"
left="0"
width="100vw"
height="100%"
overflow="hidden"
pointerEvents="none"
>
<Box
position="absolute"
top="50%"
left="50%"
sx={{
backgroundImage: "url('/images/pawprint_background.png')",
backgroundRepeat: "no-repeat",
backgroundColor: "var(--blue-700, #2C5282)",
backgroundPosition: "center",
zIndex: -1,

"@media (orientation: portrait)": {
transform: "translate(-50%, -50%) rotate(-15deg)",
backgroundSize: "contain",
width: "200vw",
height: "200vh",
},
"@media (orientation: landscape)": {
transform: "translate(-50%, -50%)",
backgroundSize: "130%",
width: "100%",
height: "100%",
},
}}
/>
</Flex>
);
};

export default ResponsivePawprintBackground;
Loading

0 comments on commit c56e80f

Please sign in to comment.