Skip to content

Commit

Permalink
EmailSignUp token creation done, refined routes
Browse files Browse the repository at this point in the history
  • Loading branch information
Winston-Hsiao committed Aug 10, 2024
1 parent a15db8d commit 441b636
Show file tree
Hide file tree
Showing 8 changed files with 54 additions and 49 deletions.
2 changes: 1 addition & 1 deletion frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const App = () => {
<Route path="/profile" element={<Profile />} />
<Route path="/login" element={<Login />} />
<Route path="/logout" element={<Logout />} />
<Route path="/register/:token" element={<Register />} />
<Route path="/register/:id" element={<Register />} />
<Route path="/create" element={<Create />} />
<Route path="/browse/:page?" element={<Browse />} />
<Route path="/item/:id" element={<ListingDetails />} />
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/auth/SignupWithEmail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ const SignupWithEmail = () => {
});

const onSubmit = async ({ email }: EmailSignupType) => {
console.log(`email: ${email}`);
const { data, error } = await auth.client.POST("/email-signup/create/", {
body: {
email,
Expand All @@ -38,7 +37,8 @@ const SignupWithEmail = () => {
} else {
const responseData = data as EmailSignUpResponse;
const successMessage =
responseData?.message || "Sign-up email sent! Check your inbox.";
responseData?.message ||
"Sign up email sent! Follow the link sent to you to continue registration.";
addAlert(successMessage, "success");
}
};
Expand Down
16 changes: 8 additions & 8 deletions frontend/src/gen/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -379,15 +379,15 @@ export interface paths {
patch?: never;
trace?: never;
};
"/email-signup/get/{token}": {
"/email-signup/get/{id}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/** Get Signup Token */
get: operations["get_signup_token_email_signup_get__token__get"];
get: operations["get_signup_token_email_signup_get__id__get"];
put?: never;
post?: never;
delete?: never;
Expand All @@ -396,7 +396,7 @@ export interface paths {
patch?: never;
trace?: never;
};
"/email-signup/delete/{token}": {
"/email-signup/delete/{id}": {
parameters: {
query?: never;
header?: never;
Expand All @@ -407,7 +407,7 @@ export interface paths {
put?: never;
post?: never;
/** Delete Signup Token */
delete: operations["delete_signup_token_email_signup_delete__token__delete"];
delete: operations["delete_signup_token_email_signup_delete__id__delete"];
options?: never;
head?: never;
patch?: never;
Expand Down Expand Up @@ -1272,12 +1272,12 @@ export interface operations {
};
};
};
get_signup_token_email_signup_get__token__get: {
get_signup_token_email_signup_get__id__get: {
parameters: {
query?: never;
header?: never;
path: {
token: string;
id: string;
};
cookie?: never;
};
Expand All @@ -1303,12 +1303,12 @@ export interface operations {
};
};
};
delete_signup_token_email_signup_delete__token__delete: {
delete_signup_token_email_signup_delete__id__delete: {
parameters: {
query?: never;
header?: never;
path: {
token: string;
id: string;
};
cookie?: never;
};
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/pages/ListingDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const RenderListing = (props: RenderListingProps) => {
const { listing } = props;

return (
<div className="container mx-auto max-w-4xl shadow-md rounded-lg bg-white dark:bg-gray-800 dark:text-white border bg-card text-card-foreground shadow relative">
<div className="container mx-auto max-w-4xl shadow-md rounded-lg bg-white dark:bg-gray-800 dark:text-white border bg-card text-card-foreground relative">
<ListingHeader
listingId={listing.id}
title={listing.name}
Expand Down
23 changes: 12 additions & 11 deletions frontend/src/pages/Register.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,44 +9,45 @@ import SignupForm from "components/auth/SignupForm";
import { Button } from "components/ui/Button/Button";

type EmailSignUpResponse =
paths["/email-signup/get/{token}"]["get"]["responses"][200]["content"]["application/json"];
paths["/email-signup/get/{id}"]["get"]["responses"][200]["content"]["application/json"];

const Register = () => {
const { addErrorAlert } = useAlertQueue();
const { token } = useParams();
const [emailToken, setEmailToken] = useState<EmailSignUpResponse | null>(
const { id } = useParams();
const [signUpToken, setSignUpToken] = useState<EmailSignUpResponse | null>(
null,
);
const auth = useAuthentication();

useEffect(() => {
const fetchListing = async () => {
if (token === undefined) {
const fetchSignUpToken = async () => {
console.log(`id in useEffect: ${id}`);
if (id === undefined) {
return;
}

try {
const { data, error } = await auth.client.GET(
"/email-signup/get/{token}",
"/email-signup/get/{id}",
{
params: {
path: { token },
path: { id },
},
},
);
if (error) {
addErrorAlert(error);
} else {
setEmailToken(data);
setSignUpToken(data);
}
} catch (err) {
addErrorAlert(err);
}
};
fetchListing();
}, [token]);
fetchSignUpToken();
}, [id]);

if (!emailToken) {
if (!signUpToken) {
return (
<div>
<h1>Invalid Sign Up Link</h1>
Expand Down
22 changes: 11 additions & 11 deletions store/app/crud/email_signup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,20 @@

class EmailSignUpCrud(BaseCrud):
async def create_email_signup_token(self, email: str) -> EmailSignUpToken:
token = EmailSignUpToken.create(email=email)
await self._add_item(token)
return token
signup_token = EmailSignUpToken.create(email=email)
await self._add_item(signup_token)
return signup_token

async def get_email_signup_token(self, token: str) -> EmailSignUpToken | None:
return await self._get_item(token, EmailSignUpToken, throw_if_missing=False)
async def get_email_signup_token(self, id: str) -> EmailSignUpToken | None:

async def delete_email_signup_token(self, token: str) -> None:
await self._delete_item(token)
return await self._get_item(id, EmailSignUpToken, throw_if_missing=False)

async def delete_email_signup_token(self, id: str) -> None:
await self._delete_item(id)


async def test_adhoc() -> None:
async with EmailSignUpCrud() as crud:
token = await crud.create_email_signup_token(email="[email protected]")
retrieved_token = await crud.get_email_signup_token(token.token)
print(f"Retrieved Token: {retrieved_token}")
await crud.delete_email_signup_token(token.token)
signup_token = await crud.create_email_signup_token(email="[email protected]")
await crud.get_email_signup_token(signup_token.id)
await crud.delete_email_signup_token(signup_token.id)
3 changes: 1 addition & 2 deletions store/app/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,10 @@ class EmailSignUpToken(RobolistBaseModel):
"""

email: EmailStr
token: str

@classmethod
def create(cls, email: str) -> Self:
return cls(email=email, token=new_uuid())
return cls(id=new_uuid(), email=email)


class OAuthKey(RobolistBaseModel):
Expand Down
31 changes: 18 additions & 13 deletions store/app/routers/email_signup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, EmailStr

from store.app.crud.users import UserCrud
from store.app.crud.email_signup import EmailSignUpCrud
from store.app.utils.email import send_register_email

email_signup_router = APIRouter()

Expand All @@ -29,27 +30,31 @@ class DeleteTokenResponse(BaseModel):

# POST: Create Signup Token
@email_signup_router.post("/create/", response_model=EmailSignUpResponse)
async def create_signup_token(data: EmailSignUpRequest, crud: UserCrud = Depends()) -> EmailSignUpResponse:
try:
await crud.create_email_signup_token(data.email)
return {"message": "Sign-up token created successfully."}
except Exception as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
async def create_signup_token(data: EmailSignUpRequest) -> EmailSignUpResponse:
async with EmailSignUpCrud() as crud:
try:
signup_token = await crud.create_email_signup_token(data.email)
await send_register_email(email=data.email, token=signup_token.id)

return {"message": "Sign up email sent! Follow the link sent to you to continue registration."}
except Exception as e:
print(f"Error creating signup token: {e}")
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))


# GET: Retrieve Signup Token
@email_signup_router.get("/get/{token}", response_model=GetTokenResponse)
async def get_signup_token(token: str, crud: UserCrud = Depends()) -> GetTokenResponse:
signup_token = await crud.get_email_signup_token(token)
@email_signup_router.get("/get/{id}", response_model=GetTokenResponse)
async def get_signup_token(id: str, crud: EmailSignUpCrud = Depends()) -> GetTokenResponse:
signup_token = await crud.get_email_signup_token(id)
if not signup_token:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Token not found.")
return signup_token


# DELETE: Delete Signup Token
@email_signup_router.delete("/delete/{token}", response_model=DeleteTokenResponse)
async def delete_signup_token(token: str, crud: UserCrud = Depends()) -> DeleteTokenResponse:
deleted = await crud.delete_email_signup_token(token)
@email_signup_router.delete("/delete/{id}", response_model=DeleteTokenResponse)
async def delete_signup_token(id: str, crud: EmailSignUpCrud = Depends()) -> DeleteTokenResponse:
deleted = await crud.delete_email_signup_token(id)
if not deleted:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Token not found.")
return {"message": "Token deleted successfully."}

0 comments on commit 441b636

Please sign in to comment.