Skip to content

Commit

Permalink
Merge pull request #62 from Build-Squad/GEN-101-Redux-Setup
Browse files Browse the repository at this point in the history
Gen 101 redux setup
  • Loading branch information
muditmahajan authored Jan 3, 2024
2 parents f97f463 + 14252aa commit 0a371fd
Show file tree
Hide file tree
Showing 8 changed files with 97 additions and 97 deletions.
2 changes: 1 addition & 1 deletion src/api/marketplace/accounts/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -887,7 +887,7 @@ def post(self, request):
'jwt', token, max_age=86400, path="/", secure=True, httponly=True, samesite="None")
response.data = {
"isSuccess": True,
"data": None,
"data": UserSerializer(user).data,
"message": "Logged in successfully",
}
response.status_code = status.HTTP_200_OK
Expand Down
6 changes: 6 additions & 0 deletions src/api/marketplace/marketplace/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.shortcuts import redirect, render
from accounts.serializers import UserSerializer
from tweepy import Client, OAuth2UserHandler
from django.http import (
JsonResponse,
Expand Down Expand Up @@ -187,6 +188,11 @@ def createJWT(userData, access_token):
response = JWTOperations.setJwtToken(
response, cookie_name="jwt", payload=payload
)
response.data = {
"isSuccess": True,
"data": UserSerializer(current_user).data,
"message": "Logged in successfully",
}
logger.info("JWT created successfully")
return response
except Exception as e:
Expand Down
85 changes: 63 additions & 22 deletions src/ui/app/components/navbar/index.tsx
Original file line number Diff line number Diff line change
@@ -1,36 +1,77 @@
import React, { useEffect } from "react";
import React, { useEffect, useState } from "react";
import { Toolbar, AppBar, Button, Box } from "@mui/material";
import Image from "next/image";
import { useRouter, usePathname } from "next/navigation";
import { useRouter, usePathname, useSearchParams } from "next/navigation";
import LoginMenu from "../loginMenu";
import useTwitterAuth from "@/src/hooks/useTwitterAuth";
import { LOGIN_STATUS_SUCCESS, LOGIN_STATUS_FAILED } from "@/src/utils/consts";
import { loginStatusType } from "@/app/utils/types";
import { useAppSelector } from "@/src/hooks/useRedux";

type Props = {
authUser: () => {};
logout: () => {};
loginStatus: Boolean;
type NavbarProps = {
setLoginStatus: React.Dispatch<React.SetStateAction<loginStatusType>>;
setEmailOpen: React.Dispatch<React.SetStateAction<boolean>>;
setWalletOpen: React.Dispatch<React.SetStateAction<boolean>>;
setCategoryOpen: React.Dispatch<React.SetStateAction<boolean>>;
emailOpen: boolean;
walletOpen: boolean;
};

export default function Navbar({
authUser,
logout,
loginStatus,
setLoginStatus,
setEmailOpen,
setWalletOpen,
}: Props) {
setCategoryOpen,
emailOpen,
walletOpen,
}: NavbarProps) {
const {
isTwitterUserLoggedIn,
startTwitterAuthentication,
logoutTwitterUser,
checkTwitterUserAuthentication,
isAccountSsetupComplete,
} = useTwitterAuth();
const router = useRouter();
const pathname = usePathname();
const [currentUser, setCurrentUser] = React.useState<UserType | null>(null);
const currentUser = useAppSelector((state) => state.user?.user);
// const [currentUser, setCurrentUser] = React.useState<UserType | null>(null);

const params = useSearchParams();

useEffect(() => {
if (!emailOpen) {
checkTwitterUserAuthentication();
}
}, [emailOpen]);

useEffect(() => {
if (!walletOpen) {
checkTwitterUserAuthentication();
}
}, [walletOpen]);

useEffect(() => {
const status = params.get("authenticationStatus");
if (status) {
setLoginStatus({
status,
message:
status == "success" ? LOGIN_STATUS_SUCCESS : LOGIN_STATUS_FAILED,
});
}
}, [isTwitterUserLoggedIn]);

useEffect(() => {
if (loginStatus) {
const user = localStorage.getItem("user");
if (user) {
setCurrentUser(JSON.parse(user));
}
const status = params.get("authenticationStatus");
if (
isTwitterUserLoggedIn &&
!isAccountSsetupComplete &&
status === "success"
) {
setCategoryOpen(true);
}
}, [loginStatus]);
}, [isTwitterUserLoggedIn, isAccountSsetupComplete]);

return (
<AppBar position="static" sx={{ boxShadow: "none" }}>
Expand All @@ -46,7 +87,7 @@ export default function Navbar({
alt="bgimg"
/>
</Box>
{loginStatus ? null : (
{isTwitterUserLoggedIn ? null : (
<Box
sx={{
display: "flex",
Expand Down Expand Up @@ -102,7 +143,7 @@ export default function Navbar({
<Button color="inherit" sx={{ fontSize: "16px" }}>
About
</Button>
{loginStatus ? (
{isTwitterUserLoggedIn ? (
<>
{pathname.includes("business") ? null : (
<Button
Expand All @@ -128,7 +169,7 @@ export default function Navbar({
},
}}
onClick={() => {
logout();
logoutTwitterUser();
if (pathname.includes("influencer")) {
router.push("/influencer");
} else if (pathname.includes("business")) {
Expand All @@ -153,14 +194,14 @@ export default function Navbar({
border: "1px solid black",
borderRadius: "20px",
}}
onClick={authUser}
onClick={startTwitterAuthentication}
>
Login
</Button>
) : (
<>
<LoginMenu
twitterLogin={authUser}
twitterLogin={startTwitterAuthentication}
setEmailOpen={setEmailOpen}
setWalletOpen={setWalletOpen}
/>
Expand Down
8 changes: 2 additions & 6 deletions src/ui/app/influencer/profile/[id]/_services/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import CheckoutModal from "@/src/components/checkoutModal";
import CreateUpdateService from "@/src/components/profileComponents/createUpdateService";
import { ConfirmDelete } from "@/src/components/shared/confirmDeleteModal";
import { notification } from "@/src/components/shared/notification";
import { useAppSelector } from "@/src/hooks/useRedux";
import { deleteService, getService } from "@/src/services/httpServices";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
Expand All @@ -29,7 +30,7 @@ type ServiceProps = {
};

const Services = ({ currentUser, id }: ServiceProps) => {
const [loggedInUser, setLoggedInUser] = React.useState<UserType | null>(null);
const loggedInUser = useAppSelector((state) => state.user?.user);
const [type, setType] = React.useState<string | null>(null);
const [checkedOutServices, setCheckedOutServices] = React.useState<
ServiceType[]
Expand Down Expand Up @@ -125,11 +126,6 @@ const Services = ({ currentUser, id }: ServiceProps) => {
}
}, [openModal]);

useEffect(() => {
const user = JSON.parse(localStorage.getItem("user") || "{}");
setLoggedInUser(user);
}, []);

return (
<Box
sx={{
Expand Down
8 changes: 2 additions & 6 deletions src/ui/app/influencer/profile/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
} from "@/src/services/httpServices";
import Services from "./_services";
import { notification } from "@/src/components/shared/notification";
import { useAppSelector } from "@/src/hooks/useRedux";

const tabs = [
{
Expand All @@ -48,7 +49,7 @@ const ProfileLayout = ({
id: string;
};
}) => {
const [loggedInUser, setLoggedInUser] = React.useState<UserType | null>(null);
const loggedInUser = useAppSelector((state) => state.user?.user);
const [currentUser, setCurrentUser] = React.useState<UserType | null>(null);
const [categoryOpen, setCategoryOpen] = React.useState<boolean>(false);

Expand Down Expand Up @@ -90,11 +91,6 @@ const ProfileLayout = ({
}
}, [categoryOpen]);

useEffect(() => {
const user = JSON.parse(localStorage.getItem("user") || "{}");
setLoggedInUser(user);
}, []);

return (
<Box
sx={{
Expand Down
74 changes: 15 additions & 59 deletions src/ui/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
"use client";

import "./globals.css";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import ThemeRegistry from "./ThemeRegistry";
import { SnackbarProvider } from "notistack";
import { useEffect, useRef, useState } from "react";
import { loginStatusType } from "./utils/types";
import { useSearchParams } from "next/navigation";
import Navbar from "./components/navbar";
import SnackbarComp from "@/src/components/shared/snackBarComp";
import useTwitterAuth from "@/src/hooks/useTwitterAuth";
import { LOGIN_STATUS_FAILED, LOGIN_STATUS_SUCCESS } from "@/src/utils/consts";
import EmailLoginModal from "@/src/components/emailLoginModal";
import CategorySelectionModal from "@/src/components/categorySelectionModal";
import EmailLoginModal from "@/src/components/emailLoginModal";
import SnackbarComp from "@/src/components/shared/snackBarComp";
import WalletConnectModal from "@/src/components/walletConnectModal";
import { AppStore, makeStore } from "@/src/store";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import { useSearchParams } from "next/navigation";
import { SnackbarProvider } from "notistack";
import { useRef, useState } from "react";
import { Provider } from "react-redux";
import ThemeRegistry from "./ThemeRegistry";
import Navbar from "./components/navbar";
import "./globals.css";
import { loginStatusType } from "./utils/types";

const inter = Inter({ subsets: ["latin"] });

Expand Down Expand Up @@ -46,49 +44,6 @@ export default function RootLayout({
const [categoryOpen, setCategoryOpen] = useState<boolean>(false);
const [walletOpen, setWalletOpen] = useState<boolean>(false);

// Twitter authentication hook
const {
isTwitterUserLoggedIn,
startTwitterAuthentication,
logoutTwitterUser,
checkTwitterUserAuthentication,
isAccountSsetupComplete,
} = useTwitterAuth();

useEffect(() => {
const status = params.get("authenticationStatus");
if (status) {
setLoginStatus({
status,
message:
status == "success" ? LOGIN_STATUS_SUCCESS : LOGIN_STATUS_FAILED,
});
}
}, [isTwitterUserLoggedIn]);

useEffect(() => {
const status = params.get("authenticationStatus");
if (
isTwitterUserLoggedIn &&
!isAccountSsetupComplete &&
status === "success"
) {
setCategoryOpen(true);
}
}, [isTwitterUserLoggedIn, isAccountSsetupComplete]);

useEffect(() => {
if (!emailOpen) {
checkTwitterUserAuthentication();
}
}, [emailOpen]);

useEffect(() => {
if (!walletOpen) {
checkTwitterUserAuthentication();
}
}, [walletOpen]);

return (
<html lang="en">
<body className={inter.className}>
Expand All @@ -104,11 +59,12 @@ export default function RootLayout({
<Provider store={storeRef.current}>
<ThemeRegistry options={{ key: "mui-theme" }}>
<Navbar
authUser={startTwitterAuthentication}
logout={logoutTwitterUser}
loginStatus={isTwitterUserLoggedIn}
setEmailOpen={setEmailOpen}
setCategoryOpen={setCategoryOpen}
setWalletOpen={setWalletOpen}
setLoginStatus={setLoginStatus}
emailOpen={emailOpen}
walletOpen={walletOpen}
/>
{children}
{loginStatus.status ? (
Expand Down
10 changes: 8 additions & 2 deletions src/ui/src/hooks/useTwitterAuth.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
"use client";

import axios from "axios";
import { useState, useEffect } from "react";
import { getServicewithCredentials } from "../services/httpServices";
import { notification } from "../components/shared/notification";
import { useAppDispatch } from "./useRedux";
import { loginReducer, logoutReducer } from "../reducers/userSlice";

const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL;

// Hook for handling user login/signup via Twitter
export default function useTwitterAuth() {
const dispatch = useAppDispatch();
// State to track whether the user is logged in via Twitter
const [isTwitterUserLoggedIn, setTwitterUserLoggedIn] = useState(false);
const [isAccountSsetupComplete, setIsAccountSetupComplete] = useState(true);
Expand Down Expand Up @@ -37,7 +42,7 @@ export default function useTwitterAuth() {
await axios.get(`${BACKEND_URL}logout/`, { withCredentials: true });
notification("Logged out successfully");
setTwitterUserLoggedIn(false);
localStorage.clear();
dispatch(logoutReducer());
} catch (error) {
console.error("Error during logout:", error);
}
Expand All @@ -50,10 +55,11 @@ export default function useTwitterAuth() {
if (isSuccess) {
setUserDetails(data?.data);
setTwitterUserLoggedIn(true);
localStorage.setItem("user", JSON.stringify(data?.data));
dispatch(loginReducer(data?.data));
} else {
setUserDetails(null);
setTwitterUserLoggedIn(false);
dispatch(logoutReducer());
localStorage.clear();
}
} catch (error) {
Expand Down
1 change: 0 additions & 1 deletion src/ui/src/reducers/userSlice.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// A slice that will keep track of the login status of the user and the user's information

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { RootState } from "../store";

type UserState = {
loggedIn: boolean;
Expand Down

0 comments on commit 0a371fd

Please sign in to comment.