Skip to content
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

Verification Page #194

Merged
merged 19 commits into from
Dec 3, 2023
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
23 changes: 21 additions & 2 deletions backend/app/rest/auth_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from ..middlewares.auth import (
require_authorization_by_user_id,
require_authorization_by_email,
get_access_token,
)
from ..middlewares.validate import validate_request
from ..resources.create_user_dto import CreateUserDTO
Expand Down Expand Up @@ -73,6 +74,7 @@ def login():
"last_name": auth_dto.last_name,
"email": auth_dto.email,
"role": auth_dto.role,
"verified": auth_service.is_authorized_by_token(auth_dto.access_token),
}

sign_in_logs_service.create_sign_in_log(auth_dto.id)
Expand Down Expand Up @@ -128,6 +130,9 @@ def two_fa():
auth_dto = auth_service.generate_token(
request.json["email"], request.json["password"]
)

auth_service.send_email_verification_link(request.json["email"])

response = jsonify(
{
"access_token": auth_dto.access_token,
Expand All @@ -136,6 +141,7 @@ def two_fa():
"last_name": auth_dto.last_name,
"email": auth_dto.email,
"role": auth_dto.role,
"verified": auth_service.is_authorized_by_token(auth_dto.access_token),
}
)
response.set_cookie(
Expand Down Expand Up @@ -165,13 +171,13 @@ def register():
request.json["email"], request.json["password"]
)

auth_service.send_email_verification_link(request.json["email"])

response = {"requires_two_fa": False, "auth_user": None}

if os.getenv("TWILIO_ENABLED") == "True" and auth_dto.role == "Relief Staff":
response["requires_two_fa"] = True
return jsonify(response), 200

auth_service.send_email_verification_link(request.json["email"])

response["auth_user"] = {
"access_token": auth_dto.access_token,
Expand All @@ -180,6 +186,7 @@ def register():
"last_name": auth_dto.last_name,
"email": auth_dto.email,
"role": auth_dto.role,
"verified": auth_service.is_authorized_by_token(auth_dto.access_token),
}

response = jsonify(response)
Expand Down Expand Up @@ -243,3 +250,15 @@ def reset_password(email):
except Exception as e:
error_message = getattr(e, "message", None)
return jsonify({"error": (error_message if error_message else str(e))}), 500

@blueprint.route("/verify", methods=["GET"], strict_slashes=False)
def is_verified():
"""
Checks if a user with a specified email is verified.
"""
try:
access_token = get_access_token(request)
return jsonify({"verified": auth_service.is_authorized_by_token(access_token)}), 200
except Exception as e:
error_message = getattr(e, "message", None)
return jsonify({"error": (error_message if error_message else str(e))}), 500
11 changes: 11 additions & 0 deletions backend/app/services/implementations/auth_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,3 +219,14 @@ def is_authorized_by_email(self, access_token, requested_email):
)
except:
return False

def is_authorized_by_token(self, access_token):
try:
decoded_id_token = firebase_admin.auth.verify_id_token(
access_token, check_revoked=True
)
firebase_user = firebase_admin.auth.get_user(decoded_id_token["uid"])
return firebase_user.email_verified
except Exception as e:
print(e)
return False
17 changes: 17 additions & 0 deletions frontend/src/APIClients/AuthAPIClient.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import {
FetchResult,

Check warning on line 2 in frontend/src/APIClients/AuthAPIClient.ts

View workflow job for this annotation

GitHub Actions / run-lint

'FetchResult' is defined but never used
MutationFunctionOptions,

Check warning on line 3 in frontend/src/APIClients/AuthAPIClient.ts

View workflow job for this annotation

GitHub Actions / run-lint

'MutationFunctionOptions' is defined but never used
OperationVariables,

Check warning on line 4 in frontend/src/APIClients/AuthAPIClient.ts

View workflow job for this annotation

GitHub Actions / run-lint

'OperationVariables' is defined but never used
} from "@apollo/client";
import { AxiosError } from "axios";
import {

Check warning on line 7 in frontend/src/APIClients/AuthAPIClient.ts

View workflow job for this annotation

GitHub Actions / run-lint

Replace `⏎··getAuthErrMessage⏎}·⏎` with `getAuthErrMessage·}·`
getAuthErrMessage
}
from "../helper/authError";
import AUTHENTICATED_USER_KEY from "../constants/AuthConstants";
import {

Check warning on line 12 in frontend/src/APIClients/AuthAPIClient.ts

View workflow job for this annotation

GitHub Actions / run-lint

Replace `⏎··AuthenticatedUser,⏎··AuthTokenResponse,⏎` with `·AuthenticatedUser,·AuthTokenResponse·`
AuthenticatedUser,
AuthTokenResponse,
ErrorResponse,
} from "../types/AuthTypes";

Check warning on line 16 in frontend/src/APIClients/AuthAPIClient.ts

View workflow job for this annotation

GitHub Actions / run-lint

Insert `;`
import baseAPIClient from "./BaseAPIClient";
import {
getLocalStorageObjProperty,
Expand All @@ -32,11 +32,11 @@
);
return data;
} catch (error) {
const axiosErr = (error as any) as AxiosError;

Check warning on line 35 in frontend/src/APIClients/AuthAPIClient.ts

View workflow job for this annotation

GitHub Actions / run-lint

Unexpected any. Specify a different type
if (axiosErr.response && axiosErr.response.status === 401) {
return {
errCode: axiosErr.response.status,
errMessage: getAuthErrMessage(axiosErr.response, 'LOGIN'),

Check warning on line 39 in frontend/src/APIClients/AuthAPIClient.ts

View workflow job for this annotation

GitHub Actions / run-lint

Replace `'LOGIN'` with `"LOGIN"`
};
}
return {
Expand Down Expand Up @@ -111,11 +111,11 @@
);
return data;
} catch (error) {
const axiosErr = (error as any) as AxiosError;

Check warning on line 114 in frontend/src/APIClients/AuthAPIClient.ts

View workflow job for this annotation

GitHub Actions / run-lint

Unexpected any. Specify a different type
if (axiosErr.response && axiosErr.response.status === 409) {
return {
errCode: axiosErr.response.status,
errMessage: getAuthErrMessage(axiosErr.response, 'SIGNUP'),

Check warning on line 118 in frontend/src/APIClients/AuthAPIClient.ts

View workflow job for this annotation

GitHub Actions / run-lint

Replace `'SIGNUP'` with `"SIGNUP"`
};
}
return null;
Expand All @@ -139,6 +139,22 @@
}
};

const isVerified = async (): Promise<boolean> => {
const bearerToken = `Bearer ${getLocalStorageObjProperty(
AUTHENTICATED_USER_KEY,
"accessToken",
)}`;
try {
const { data } = await baseAPIClient.get(
`/auth/verify`,
{ headers: { Authorization: bearerToken } },
);
return data.verified === true;
} catch (error) {
return false;
}
};

// for testing only, refresh does not need to be exposed in the client
const refresh = async (): Promise<boolean> => {
try {
Expand All @@ -165,5 +181,6 @@
twoFaWithGoogle,
register,
resetPassword,
isVerified,
refresh,
};
11 changes: 6 additions & 5 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,9 @@ import { ChakraProvider } from "@chakra-ui/react";
import LoginPage from "./components/pages/LoginPage";
import SignupPage from "./components/pages/SignupPage";
import PrivateRoute from "./components/auth/PrivateRoute";
import CreatePage from "./components/pages/CreatePage";
import DisplayPage from "./components/pages/DisplayPage";
import Verification from "./components/auth/Verification";
import HomePage from "./components/pages/HomePage/HomePage";
import NotFound from "./components/pages/NotFound";
import UpdatePage from "./components/pages/UpdatePage";
import * as Routes from "./constants/Routes";
import AUTHENTICATED_USER_KEY from "./constants/AuthConstants";
import AuthContext from "./contexts/AuthContext";
Expand All @@ -21,8 +19,6 @@ import SampleContext, {
} from "./contexts/SampleContext";
import sampleContextReducer from "./reducers/SampleContextReducer";
import SampleContextDispatcherContext from "./contexts/SampleContextDispatcherContext";
import EditTeamInfoPage from "./components/pages/EditTeamPage";
import HooksDemo from "./components/pages/HooksDemo";
import ResidentDirectory from "./components/pages/ResidentDirectory/ResidentDirectory";

import { AuthenticatedUser } from "./types/AuthTypes";
Expand Down Expand Up @@ -61,6 +57,11 @@ const App = (): React.ReactElement => {
<Switch>
<Route exact path={Routes.LOGIN_PAGE} component={LoginPage} />
<Route exact path={Routes.SIGNUP_PAGE} component={SignupPage} />
<PrivateRoute
exact
path={Routes.VERIFICATION_PAGE}
component={Verification}
/>
<PrivateRoute
exact
path={Routes.HOME_PAGE}
Expand Down
29 changes: 21 additions & 8 deletions frontend/src/components/auth/PrivateRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import React, { useContext } from "react";
import { Route, Redirect } from "react-router-dom";

import React, { useContext, useState, useEffect } from "react";
import { Route, Redirect, useLocation } from "react-router-dom";
import AuthContext from "../../contexts/AuthContext";
import { LOGIN_PAGE } from "../../constants/Routes";
import { LOGIN_PAGE, VERIFICATION_PAGE } from "../../constants/Routes";

type PrivateRouteProps = {
component: React.FC;
Expand All @@ -16,12 +15,26 @@ const PrivateRoute: React.FC<PrivateRouteProps> = ({
path,
}: PrivateRouteProps) => {
const { authenticatedUser } = useContext(AuthContext);
const location = useLocation();
const currentPath = location.pathname;

if (!authenticatedUser) {
return (
<Redirect to={LOGIN_PAGE} />
)
}

if (authenticatedUser.verified === false) {
if (!currentPath.endsWith("/verification")) {
return (
<Redirect to={VERIFICATION_PAGE} />
)
}
}

return authenticatedUser ? (
return (
<Route path={path} exact={exact} component={component} />
) : (
<Redirect to={LOGIN_PAGE} />
);
)
};

export default PrivateRoute;
61 changes: 61 additions & 0 deletions frontend/src/components/auth/Verification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import React, { useState, useContext } from "react";
import { useHistory } from "react-router-dom";
import {
Box,
Button,
Flex,
Text,
VStack
} from "@chakra-ui/react";
import authAPIClient from "../../APIClients/AuthAPIClient";
import CreateToast from "../common/Toasts";
import AuthContext from "../../contexts/AuthContext";
import { HOME_PAGE } from "../../constants/Routes";

const Verification = (): React.ReactElement => {
const newToast = CreateToast();
const history = useHistory();
const { authenticatedUser, setAuthenticatedUser } = useContext(AuthContext);

const handleVerification = async () => {
if (authenticatedUser) {
const authUser = authenticatedUser;
authUser.verified = await authAPIClient.isVerified();
setAuthenticatedUser(authUser);

if (authenticatedUser.verified === false) {
newToast("Not Verified", "Please check your email for the verification email.", "error");
} else {
history.push(HOME_PAGE);
}
}
};

return (
<>
<Box bg="teal.400" height="100vh">
<Flex bg="white" height="100vh" width="47%" justifyContent="center" alignItems="center">
<VStack width="75%" align="flex-start" gap="3vh">
<Text variant="login">Verification</Text>
<Text variant="loginSecondary">In order to start using your SHOW account, you need to confirm your email address.</Text>
<Button
variant="login"
onClick={handleVerification}
_hover={
{
background: "teal.500",
transition:
"transition: background-color 0.5s ease !important",
}
}
>
Verify Email Address
</Button>
</VStack>
</Flex>
</Box>
</>
);
};

export default Verification;
18 changes: 7 additions & 11 deletions frontend/src/components/forms/Login.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useContext, useState } from "react";
import React, { useContext, useState, useEffect } from "react";
import {
Box,
Button,
Expand All @@ -11,7 +11,7 @@ import {
import { Redirect, useHistory } from "react-router-dom";
import authAPIClient from "../../APIClients/AuthAPIClient";
import AUTHENTICATED_USER_KEY from "../../constants/AuthConstants";
import { HOME_PAGE, SIGNUP_PAGE } from "../../constants/Routes";
import { HOME_PAGE, SIGNUP_PAGE, VERIFICATION_PAGE } from "../../constants/Routes";
import AuthContext from "../../contexts/AuthContext";
import { ErrorResponse, AuthTokenResponse } from "../../types/AuthTypes";
import commonApiClient from "../../APIClients/CommonAPIClient";
Expand All @@ -36,7 +36,7 @@ const Login = ({
toggle,
setToggle,
}: CredentialsProps): React.ReactElement => {
const { authenticatedUser, setAuthenticatedUser } = useContext(AuthContext);
const { setAuthenticatedUser } = useContext(AuthContext);
const history = useHistory();
const [emailError, setEmailError] = useState<boolean>(false);
const [passwordError, setPasswordError] = useState<boolean>(false);
Expand Down Expand Up @@ -98,10 +98,6 @@ const Login = ({
history.push(SIGNUP_PAGE);
};

if (authenticatedUser) {
return <Redirect to={HOME_PAGE} />;
}

if (toggle) {
return (
<Flex>
Expand Down Expand Up @@ -141,10 +137,10 @@ const Login = ({
_hover={
email && password
? {
background: "teal.500",
transition:
"transition: background-color 0.5s ease !important",
}
background: "teal.500",
transition:
"transition: background-color 0.5s ease !important",
}
: {}
}
onClick={onLogInClick}
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/constants/Routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ export const LOGIN_PAGE = "/login";

export const SIGNUP_PAGE = "/signup";

export const VERIFICATION_PAGE = "/verification";

export const RESIDENT_DIRECTORY_PAGE = "/resident-directory";

export const EMPLOYEE_DIRECTORY_PAGE = "/employee-directory";
1 change: 1 addition & 0 deletions frontend/src/types/AuthTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export type AuthenticatedUser = {
email: string;
role: UserRole;
accessToken: string;
verified: boolean;
};

export type DecodedJWT =
Expand Down
Loading