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

fix: optimize end to end workflow of verification #275

Merged
merged 4 commits into from
May 10, 2024
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
20 changes: 5 additions & 15 deletions src/backend/auth.api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"use client";
import { verificationResponseType } from "@/types/auth";
import { account, db, ID, palettegramDB, usersCollection, Query } from "./appwrite.config";
import { generateAvatar } from "@/helper/avatarGenerator";

Expand All @@ -8,7 +7,6 @@ import { generateAvatar } from "@/helper/avatarGenerator";
* @param {Object} userData
* @returns authResponse
*/

const register = async (userData: {
email: string;
fullName: string;
Expand Down Expand Up @@ -56,7 +54,7 @@ const register = async (userData: {
throw new Error("Error sending verification email");
}

return authResp;
return dbData;
} catch (error: any) {
console.log(error, "Message");
throw new Error(error.message);
Expand All @@ -71,10 +69,6 @@ const register = async (userData: {
*/

const verifyUser = async (accountId: string, secret: string) => {
let response: verificationResponseType = {
status: false,
data: null,
};
try {
console.log("data:", accountId, secret);

Expand All @@ -83,8 +77,6 @@ const verifyUser = async (accountId: string, secret: string) => {
if (!verifyResponse) {
throw new Error("User not verified");
}
console.log("verifyResponse:", verifyResponse);

const currentUser = await db.listDocuments(palettegramDB, usersCollection, [
Query.equal("accountId", verifyResponse.userId),
]);
Expand All @@ -101,16 +93,15 @@ const verifyUser = async (accountId: string, secret: string) => {
throw new Error("Error in verifying user");
}

response = {
status: true,
data: null,
return {
userId: currentUser.documents[0].$id,
accountId: verifyResponse.userId,
isVerified: true,
};
} catch (error: any) {
console.log(error);
throw new Error(error.message);
}

return response;
};

/**
Expand Down Expand Up @@ -257,7 +248,6 @@ const saveDataToDatabase = async (session: any) => {
if (!resp) {
throw new Error("Database not working");
}
console.log(resp);

return resp;
} catch (error: any) {
Expand Down
1 change: 0 additions & 1 deletion src/backend/posts.api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ const getSinglePost = async (id: string) => {
*/
const getAllUserPosts = async (userId: string) => {
try {

const allPosts = await db.listDocuments(palettegramDB, postsCollection, [
Query.equal("userId", userId),
Query.orderDesc("$createdAt"),
Expand Down
5 changes: 1 addition & 4 deletions src/components/pages/auth/login/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,7 @@ export default function LoginComponent() {

setCookie(null, "accountId", payload?.accountId);
setCookie(null, "isVerified", String(payload?.isVerified));

if (payload?.$id) {
setCookie(null, "userId", payload?.$id);
}
setCookie(null, "userId", payload?.$id);

dispatch(saveUserToStore(payload));
toastify("Login Successful", "success");
Expand Down
18 changes: 8 additions & 10 deletions src/components/pages/auth/register/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { register } from "@/backend/auth.api";
import { ArrowLeftCircle, Loader, Eye, EyeOff } from "lucide-react";
import { userCollectionDB } from "@/types/auth";
import { setCookie } from "nookies";
import { Models } from "appwrite";

const nameRegex: RegExp = /^[\sa-zA-Z]+$/;
const passwordRegex: RegExp = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[@_])[A-Za-z\d@_]{6,16}$/;
Expand Down Expand Up @@ -63,25 +64,22 @@ export default function RegisterComponent() {
throw new Error("password format not matched");
}

const resp = await register(data);
const resp: Models.Document = await register(data);

const payload: userCollectionDB = {
$id: null!,
accountId: resp.$id,
$id: resp.$id,
accountId: resp.accountId,
email: resp.email,
fullName: resp.name,
username: resp.prefs.username,
isVerified: resp.emailVerification,
fullName: resp.fullName,
username: resp.username,
isVerified: resp.isVerified,
$createdAt: resp.$createdAt,
$updatedAt: resp.$updatedAt,
};

setCookie(null, "accountId", payload?.accountId);
setCookie(null, "isVerified", String(payload?.isVerified));

if (payload?.$id) {
setCookie(null, "userId", payload?.$id);
}
setCookie(null, "userId", payload?.$id);

dispatch(saveUserToStore(payload));

Expand Down
17 changes: 11 additions & 6 deletions src/components/pages/auth/verification/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { useWindowSize } from "react-use";
import Confetti from "react-confetti";

import Image from "next/image";
import { verificationResponseType } from "@/types/auth";
import Loader from "@/app/loading";

interface Verification {
Expand All @@ -34,20 +33,26 @@ export default function VerificationComponent({ accountId, secret }: Verificatio
};

useEffect(() => {
setVerified("LOAD");
verifyUser(accountId, secret)
.then((resp: verificationResponseType) => {
if (resp.status) {
confetti();
.then((resp: { userId: string; accountId: string; isVerified: boolean }) => {
if (resp.userId && resp.accountId && resp.isVerified) {
// confetti();
setCookie(null, "accountId", resp.accountId);
setCookie(null, "isVerified", String(resp.isVerified));
setCookie(null, "userId", resp.userId);
setshowConfetti(true);
setVerified("TRUE");
setCookie(null, "isVerified", String(resp.status));
}
})
.catch((err) => {
setVerified("FALSE");
console.log(err.message);
toastify(err.message, "error");
});
}, [secret, accountId]);

return () => setVerified("LOAD");
}, [accountId, secret]);

return (
<>
Expand Down
2 changes: 0 additions & 2 deletions src/components/pages/user/imageUpload.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,6 @@ export default function ImageUpload({ imgSize, setHovered }: propsType) {

const resp = await updateImageURL(currenUserId, imageUrl, imgSize?.isbannerImage);

console.log("Image:", resp);

if (!resp) {
throw new Error("Problem with uploading the image");
}
Expand Down
2 changes: 0 additions & 2 deletions src/components/pages/user/updateCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@ export default function UpdateCard({
setIsLoading(true);

try {
console.log("some use detail", userDetail);

const resp = await updateUserDetail(currenUserId, {
fullName: userDetail && userDetail?.fullName ? userDetail?.fullName : "",
about: userDetail && userDetail?.about ? userDetail?.about : "",
Expand Down
42 changes: 25 additions & 17 deletions src/components/pages/user/userPosts/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"use client";
import Loader from "@/app/loading";
import parse from "html-react-parser";
import { toastify } from "@/helper/toastify";
import Image from "next/image";
import Link from "next/link";
import { Suspense, useEffect, useState } from "react";
import { Suspense, useEffect, useState, useCallback, useMemo } from "react";
import { parseCookies } from "nookies";
import { postDisplayTimeFormatter } from "@/helper/postDisplayTimeFormatter";
import { getAllUserPosts } from "@/backend/posts.api";
Expand All @@ -13,21 +13,25 @@ import { PostInstanceType } from "@/types";
import { useSelector } from "react-redux";

export default function UserPosts({ userId }: { userId: string }) {
const [userPosts, setUserPosts] = useState<PostInstanceType[]>([]);
const postState = useSelector((state: any) => state.posts.posts);
const [userPosts, setUserPosts] = useState<Models.Document[] | PostInstanceType[]>([]);

useEffect(() => {
fetchUserPosts();
return () => {
console.log("cleanup");
};
}, []);
const memoizedUserPosts = useMemo(
() => async () => {
try {
const allPosts: Models.Document[] | undefined = await getAllUserPosts(userId);

useEffect(() => {
fetchUserPosts();
}, [postState]);
if (allPosts && allPosts.length > 0) {
setUserPosts(allPosts);
}
} catch (error: any) {
console.log(error);
toastify("error fetching posts", "error");
}
},
[userId],
);

const fetchUserPosts = () => {
useEffect(() => {
getAllUserPosts(userId)
.then((allPosts: any | undefined) => {
console.log("posts inside api", allPosts);
Expand All @@ -39,7 +43,11 @@ export default function UserPosts({ userId }: { userId: string }) {
console.log(err);
toastify("error fetching posts", "error");
});
};

return () => {
console.log("cleanup");
};
}, [userId]);

console.log("all user posts:", userPosts);

Expand All @@ -49,8 +57,8 @@ export default function UserPosts({ userId }: { userId: string }) {
<Suspense fallback={<Loader />}>
<div className="mt-6">
<div className="grid grid-cols-1 gap-1">
{userPosts
? userPosts?.map((post: PostInstanceType, index: number) => (
{userPosts && userPosts.length > 0
? userPosts?.map((post: any, index: number) => (
<div key={index}>
{post.isActive && <SinglePost singlePost={post} profileSection />}
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL("/", request.nextUrl));
}

if (isPrivateRoutes && isUserVerified === "false") {
if (isPrivateRoutes && isUserVerified.toLowerCase() === "false") {
return NextResponse.redirect(new URL("/login", request.nextUrl));
}

Expand Down
5 changes: 0 additions & 5 deletions src/types/auth.d.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
export type verificationResponseType = {
status: boolean;
data: any;
};

export type userCollectionDB = {
$id: string;
accountId: string;
Expand Down
Loading