added context provider for user profile

This commit was merged in pull request #11.
This commit is contained in:
2023-10-23 04:24:38 -07:00
parent de57daf98a
commit 5502bcd1ae
9 changed files with 157 additions and 69 deletions
+54 -54
View File
@@ -1,7 +1,7 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { setCookie } from "cookies-next"; import { setCookie } from "cookies-next";
import Link from "next/link"; import { useSnackbar } from "notistack";
import Grid from "@mui/material/Grid"; import Grid from "@mui/material/Grid";
import LoadingButton from "@mui/lab/LoadingButton"; import LoadingButton from "@mui/lab/LoadingButton";
import IconButton from "@mui/material/IconButton"; import IconButton from "@mui/material/IconButton";
@@ -14,8 +14,12 @@ import Visibility from "@mui/icons-material/Visibility";
import VisibilityOff from "@mui/icons-material/VisibilityOff"; import VisibilityOff from "@mui/icons-material/VisibilityOff";
import styles from "./signinform.module.css"; import styles from "./signinform.module.css";
import Fetcher from "services/Fetcher"; import Fetcher from "services/Fetcher";
import { useUserProfile } from "contexts/userProfileContext";
const SignInForm = () => { const SignInForm = () => {
const { state, dispatch } = useUserProfile();
// Define and initialize state variables
const [formValues, setFormValues] = useState({ const [formValues, setFormValues] = useState({
email: "", email: "",
password: "", password: "",
@@ -27,55 +31,70 @@ const SignInForm = () => {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [errMsg, setErrMsg] = useState(""); const [errMsg, setErrMsg] = useState("");
// Create instances of external services
const api = new Fetcher(); const api = new Fetcher();
const router = useRouter(); const router = useRouter();
// Access the Snackbar notification function
const { enqueueSnackbar } = useSnackbar();
// Handle changes in the input fields
const handleChange = (event) => { const handleChange = (event) => {
setFormValues({ ...formValues, [event.target.name]: event.target.value }); setFormValues({ ...formValues, [event.target.name]: event.target.value });
}; };
// "use server" // Handle form submission
const handleSubmit = async (event) => { const handleSubmit = async (event) => {
event.preventDefault(); event.preventDefault();
const { email, password } = formValues; const { email, password } = formValues;
if (email === "" || password === "") { // Validate the form fields
if (email === "" && password === "") {
setErrorHandlers({ ...errorHandlers, email: true, password: true }); setErrorHandlers({ ...errorHandlers, email: true, password: true });
setErrMsg("all fields are required");
setTimeout(() => { setTimeout(() => {
setErrorHandlers({ ...errorHandlers, email: false, password: false }); setErrorHandlers({ ...errorHandlers, email: false, password: false });
}, 1500); setErrMsg("");
}, 2000);
return; return;
} else if (email === "") { } else if (email === "") {
setErrorHandlers({ ...errorHandlers, email: true }); setErrorHandlers({ ...errorHandlers, email: true });
setErrMsg("email field is required");
setTimeout(() => { setTimeout(() => {
setErrorHandlers({ ...errorHandlers, email: false }); setErrorHandlers({ ...errorHandlers, email: false });
}, 1500); setErrMsg("");
}, 2000);
return; return;
} else if (password === "") { } else if (password === "") {
setErrorHandlers({ ...errorHandlers, password: true }); setErrorHandlers({ ...errorHandlers, password: true });
setErrMsg("password field is required");
setTimeout(() => { setTimeout(() => {
setErrorHandlers({ ...errorHandlers, password: false }); setErrorHandlers({ ...errorHandlers, password: false });
}, 1500); setErrMsg("");
}, 2000);
return; return;
} }
// Initiate the login process
setLoading(true); setLoading(true);
try { try {
// Prepare the login request data
const data = { const data = {
username: email, username: email,
password, password,
}; };
// Send the login request to the server
const res = await api.login(data); const res = await api.login(data);
if (res.status === 204 || res.length === 0) { if (res.status === 204 || res.length === 0) {
setErrorHandlers({ ...errorHandlers, email: true, password: true }); // Handle login failure
setErrMsg("Wrong Credentials"); enqueueSnackbar("Wrong Credentials", {
setTimeout(() => { variant: "error",
setErrorHandlers({ ...errorHandlers, email: false, password: false }); });
setLoading(false); setLoading(false);
setErrMsg(""); return;
}, 1500);
} }
// Store the token in cookies // Store the token in cookies
@@ -87,29 +106,45 @@ const SignInForm = () => {
expires: expirationDate, expires: expirationDate,
httpOnly: true, // Make the cookie accessible only via HTTP (recommended for security) httpOnly: true, // Make the cookie accessible only via HTTP (recommended for security)
}; };
// Set the login token in a cookie
await setCookie("cmc-token", res.token); await setCookie("cmc-token", res.token);
const userProfileData = res.profile;
dispatch({ type: 'SET_USER_PROFILE', payload: userProfileData });
enqueueSnackbar("Login Successful", {
variant: "success",
autoHideDuration: 4000,
});
// Redirect the user to a new page after successful login
router.push("/"); router.push("/");
console.log(res); console.log(res);
} catch (error) { } catch (error) {
// Handle any errors that occur during login
setLoading(false); setLoading(false);
console.log(error); console.log(error);
} finally { } finally {
// Ensure that the loading indicator is cleared after a short delay
setTimeout(() => { setTimeout(() => {
setLoading(false); setLoading(false);
}, 5000); }, 5000);
} }
}; };
// Define and initialize the state variable for toggling password visibility
const [showPassword, setShowPassword] = useState(false); const [showPassword, setShowPassword] = useState(false);
// Toggle password visibility
const handleTogglePassword = () => { const handleTogglePassword = () => {
setShowPassword(!showPassword); setShowPassword(!showPassword);
}; };
useEffect(() => { useEffect(() => {
// Prefetch the dashboard // Prefetch the dashboard page to optimize navigation
router.prefetch("/"); router.prefetch("/");
}); });
@@ -142,15 +177,6 @@ const SignInForm = () => {
className={styles.favicon} className={styles.favicon}
/> />
</Box> </Box>
{/* <Typography
as="h1"
fontSize="28px"
fontWeight="700"
mb="5px"
color="#fff"
>
Sign In{" "}
</Typography> */}
<Box component="form" noValidate onSubmit={handleSubmit}> <Box component="form" noValidate onSubmit={handleSubmit}>
<Box <Box
@@ -164,25 +190,13 @@ const SignInForm = () => {
> >
<Grid container alignItems="center" spacing={2}> <Grid container alignItems="center" spacing={2}>
<Grid item xs={12}> <Grid item xs={12}>
{/* <Typography
component="label"
sx={{
fontWeight: "500",
fontSize: "14px",
mb: "10px",
display: "block",
}}
>
Email
</Typography> */}
<TextField <TextField
required required
fullWidth fullWidth
id="email" id="email"
label={ label={
errorHandlers.email errorHandlers.email && errMsg !== ""
? "Incomplete/wrong email" ? errMsg
: "Email Address" : "Email Address"
} }
value={formValues.email} value={formValues.email}
@@ -198,25 +212,13 @@ const SignInForm = () => {
</Grid> </Grid>
<Grid item xs={12}> <Grid item xs={12}>
{/* <Typography
component="label"
sx={{
fontWeight: "500",
fontSize: "14px",
mb: "10px",
display: "block",
}}
>
Password
</Typography> */}
<TextField <TextField
required required
fullWidth fullWidth
name="password" name="password"
label={ label={
errorHandlers.password errorHandlers.password && errMsg !== ""
? "Incomplete/wrong password" ? errMsg
: "Password" : "Password"
} }
value={formValues.password} value={formValues.password}
@@ -274,9 +276,7 @@ const SignInForm = () => {
}, },
}} }}
> >
<span> <span>{loading ? "Signing in…" : "Sign In"}</span>
{loading ? "Signing in…" : errMsg ? errMsg : "Sign In"}
</span>
</LoadingButton> </LoadingButton>
</Box> </Box>
</Box> </Box>
+3 -6
View File
@@ -6,7 +6,6 @@ import TopNavbar from "@/components/_App/TopNavbar";
import Footer from "@/components/_App/Footer"; import Footer from "@/components/_App/Footer";
import ScrollToTop from "./ScrollToTop"; import ScrollToTop from "./ScrollToTop";
import ControlPanelModal from "./ControlPanelModal"; import ControlPanelModal from "./ControlPanelModal";
import AuthRoute from "middlewares/AuthRoute";
const Layout = ({ children }) => { const Layout = ({ children }) => {
const router = useRouter(); const router = useRouter();
@@ -34,9 +33,6 @@ const Layout = ({ children }) => {
// console.log("isAuthenticationPage:", isAuthenticationPage, router.pathname); // console.log("isAuthenticationPage:", isAuthenticationPage, router.pathname);
const title = isAuthenticationPage ? "CMC - auth" : "CMC - dashboard"; const title = isAuthenticationPage ? "CMC - auth" : "CMC - dashboard";
const mainWrapper = {
paddingLeft: typeof window !== "undefined" && isAuthenticationPage && "0",
};
return ( return (
<> <>
@@ -46,8 +42,9 @@ const Layout = ({ children }) => {
</Head> </Head>
<div <div
className={`main-wrapper-content ${active ? "active" : ""}`} className={`main-wrapper-content ${active ? "active" : ""} ${
style={mainWrapper} isAuthenticationPage ? "authBox" : ""
}`}
> >
{!isAuthenticationPage && ( {!isAuthenticationPage && (
<> <>
+4
View File
@@ -17,8 +17,12 @@ import MailOutlineIcon from "@mui/icons-material/MailOutline";
import ChatBubbleOutlineIcon from "@mui/icons-material/ChatBubbleOutline"; import ChatBubbleOutlineIcon from "@mui/icons-material/ChatBubbleOutline";
import AttachMoneyIcon from "@mui/icons-material/AttachMoney"; import AttachMoneyIcon from "@mui/icons-material/AttachMoney";
import Logout from "@mui/icons-material/Logout"; import Logout from "@mui/icons-material/Logout";
import { useUserProfile } from "contexts/userProfileContext";
const Profile = () => { const Profile = () => {
const { state } = useUserProfile();
const userProfile = state.userProfile;
const [anchorEl, setAnchorEl] = React.useState(null); const [anchorEl, setAnchorEl] = React.useState(null);
const open = Boolean(anchorEl); const open = Boolean(anchorEl);
const handleClick = (event) => { const handleClick = (event) => {
+38
View File
@@ -0,0 +1,38 @@
// UserProfileContext.js
import { createContext, useContext, useReducer } from "react";
// Define the initial state
const initialState = {
userProfile: null,
};
// Create the context
const UserProfileContext = createContext();
// Create a custom hook for using the context
export const useUserProfile = () => {
return useContext(UserProfileContext);
};
// Define a reducer function to update the context state
const userProfileReducer = (state, action) => {
switch (action.type) {
case "SET_USER_PROFILE":
return { ...state, userProfile: action.payload };
case "CLEAR_USER_PROFILE":
return { ...state, userProfile: null };
default:
return state;
}
};
// Create the UserProfileProvider component
export const UserProfileProvider = ({ children }) => {
const [state, dispatch] = useReducer(userProfileReducer, initialState);
return (
<UserProfileContext.Provider value={{ state, dispatch }}>
{children}
</UserProfileContext.Provider>
);
};
+38 -5
View File
@@ -1,4 +1,4 @@
import React from "react"; import React, { useEffect } from "react";
import "../styles/remixicon.css"; import "../styles/remixicon.css";
import "react-tabs/style/react-tabs.css"; import "react-tabs/style/react-tabs.css";
import "swiper/css"; import "swiper/css";
@@ -13,18 +13,51 @@ import "../styles/rtl.css";
import "../styles/dark.css"; import "../styles/dark.css";
// Theme Styles // Theme Styles
import theme from "../styles/theme"; import theme from "../styles/theme";
import { SnackbarProvider } from "notistack";
import { ThemeProvider, CssBaseline } from "@mui/material"; import { ThemeProvider, CssBaseline } from "@mui/material";
import Layout from "@/components/_App/Layout"; import Layout from "@/components/_App/Layout";
import { UserProfileProvider } from "contexts/userProfileContext";
import { useRouter } from "next/router";
import { hasCookie } from "cookies-next";
function MyApp({ Component, pageProps }) { function MyApp({ Component, pageProps }) {
const router = useRouter();
const handlePopState = () => {
// Check if the user is logged in or if you need to redirect them after logout
if (!hasCookie("cmc-token")) {
router.push("/auth/login");
}
};
// Attach the event handler when the component mounts
useEffect(() => {
window.onpopstate = handlePopState;
// Clean up the event handler when the component unmounts
return () => {
window.onpopstate = null;
};
}, []);
return ( return (
<> <>
<Head>
<title>{!hasCookie("cmc-token") && "CMC - auth"}</title>
</Head>
<ThemeProvider theme={theme}> <ThemeProvider theme={theme}>
<CssBaseline /> <CssBaseline />
<Layout> <UserProfileProvider>
<Component {...pageProps} /> <SnackbarProvider
</Layout> maxSnack={3}
autoHideDuration={2000}
preventDuplicate
>
<Layout>
<Component {...pageProps} />
</Layout>
</SnackbarProvider>
</UserProfileProvider>
</ThemeProvider> </ThemeProvider>
</> </>
); );
+9 -3
View File
@@ -1,4 +1,4 @@
import { useRouter } from 'next/router' import { useRouter } from "next/router";
import { Typography } from "@mui/material"; import { Typography } from "@mui/material";
import { Box } from "@mui/system"; import { Box } from "@mui/system";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
@@ -6,10 +6,16 @@ import LogoutIcon from "@mui/icons-material/Logout";
import { deleteCookie } from "cookies-next"; import { deleteCookie } from "cookies-next";
export default function Logout() { export default function Logout() {
const router = useRouter() const router = useRouter();
const handleLogout = () => { const handleLogout = () => {
// Remove the cookie
deleteCookie("cmc-token"); deleteCookie("cmc-token");
router.push("/auth/login")
// Use replaceState to replace the current URL with the root URL
window.history.replaceState({}, document.title, window.location.href);
// Redirect to the login page
router.push("/auth/login");
}; };
return ( return (
<> <>
+5
View File
@@ -9,8 +9,13 @@ import ProfileContent from '@/components/Pages/Profile/ProfileContent';
import ImpressionGoalConversions from "@/components/Dashboard/Analytics/ImpressionGoalConversions"; import ImpressionGoalConversions from "@/components/Dashboard/Analytics/ImpressionGoalConversions";
import Link from 'next/link'; import Link from 'next/link';
import styles from '@/styles/PageTitle.module.css'; import styles from '@/styles/PageTitle.module.css';
import { useUserProfile } from 'contexts/userProfileContext';
export default function Profile() { export default function Profile() {
const { state } = useUserProfile();
const userProfile = state.userProfile;
console.log(userProfile)
return ( return (
<> <>
{/* Page title */} {/* Page title */}
+2 -1
View File
@@ -3,7 +3,8 @@ import Axios from "axios";
class Fetcher { class Fetcher {
constructor(url) { constructor(url) {
// this.url = url; // this.url = url;
console.log("first request!!!"); // console.log("first request!!!");
// return new Response("Working!!!" + url)
} }
// Endpoints Here // Endpoints Here
+4
View File
@@ -804,6 +804,10 @@ img {
position: relative; position: relative;
transition: all 0.5s ease-out; transition: all 0.5s ease-out;
} }
.main-wrapper-content.authBox{
padding-left: 0;
}
.main-wrapper-content.active { .main-wrapper-content.active {
padding-left: 0; padding-left: 0;
} }