23 Commits

Author SHA1 Message Date
Chief Bube 07a40ee808 Added profile data but clears after refresh 2023-10-24 01:25:12 -07:00
Chief Bube e0fb79f2c9 Called Head 2023-10-23 04:54:38 -07:00
Chief Bube 5502bcd1ae added context provider for user profile 2023-10-23 04:24:38 -07:00
Chief Bube de57daf98a Added Logout Option and prefetch for the dashboard 2023-10-23 00:45:13 -07:00
Chief Bube c3dea8ae95 changed index 2023-10-22 23:20:34 -07:00
Chief Bube 1ebb8d61f1 fixed redirection bug 2023-10-22 23:08:34 -07:00
ameye f67d33396e Merge branch 'adding-login' of Controls/CMS-Client into master 2023-10-22 16:50:47 +00:00
Chief Bube 5e3e17e7c2 Fixed Logging In Issue 2023-10-22 07:08:04 -07:00
ameye 1f4cabe8b9 Merge branch 'adding-login' of Controls/CMS-Client into master 2023-10-22 11:30:52 +00:00
Chief Bube eceb3178fd fixed server issue on document 2023-10-21 22:39:08 -07:00
ameye 5f65d45c9c Merge branch 'adding-login' of Controls/CMS-Client into master 2023-10-21 10:32:27 +00:00
Chief Bube c48c959749 added authentication 2023-10-21 03:06:58 -07:00
Chief Bube ed2ebe41e6 completed middleware 2023-10-20 17:18:36 -07:00
Chief Bube 07337a6cfc changed route name to login 2023-10-20 17:09:46 -07:00
ameye c185b6536e Merge branch 'auth-wallpaper' of Controls/CMS-Client into master 2023-10-20 13:57:53 +00:00
Chief Bube b132670152 Changed admin 2023-10-20 06:51:21 -07:00
ameye 42e21d3123 Merge branch 'auth-wallpaper' of Controls/CMS-Client into master 2023-10-20 13:47:29 +00:00
Chief Bube 39fe9eaaa2 made changes to the auth layout 2023-10-20 06:45:34 -07:00
ameye 33eefd5013 Merge branch 'auth-wallpaper' of Controls/CMS-Client into master 2023-10-19 11:51:45 +00:00
Chief Bube 5d4cbc7a1c Added wallpaper to the Authentication Page 2023-10-19 04:44:38 -07:00
tokslaw defc3411bb Merge branch 'master' of https://gitlab.chiefsoft.net/Controls/CMS-Client 2023-10-18 12:13:57 -04:00
tokslaw 8bf86c8d35 bootstrap npm package 2023-10-18 12:09:23 -04:00
ameye a84cdcb886 Merge branch 'Logo-addition' of Controls/CMS-Client into master 2023-10-18 10:44:32 +00:00
24 changed files with 653 additions and 181 deletions
+1
View File
@@ -0,0 +1 @@
AUX_ENDPOINT="http://localhost:50016/api"
@@ -104,7 +104,7 @@ const ForgotPasswordForm = () => {
<Box as="div" textAlign="center" mt="20px">
<Link
href="/auth/sign-in/"
href="/auth/login/"
className="primaryColor text-decoration-none"
>
<i className="ri-arrow-left-s-line"></i> Back to Sign in
+246 -82
View File
@@ -1,28 +1,157 @@
import React from "react";
import Link from "next/link";
import React, { useEffect, useState } from "react";
import { useRouter } from "next/router";
import { setCookie } from "cookies-next";
import { useSnackbar } from "notistack";
import Grid from "@mui/material/Grid";
import LoadingButton from "@mui/lab/LoadingButton";
import IconButton from "@mui/material/IconButton";
import { Typography } from "@mui/material";
import { Box } from "@mui/system";
import TextField from "@mui/material/TextField";
import InputAdornment from "@mui/material/InputAdornment";
import Button from "@mui/material/Button";
import FormControlLabel from "@mui/material/FormControlLabel";
import Checkbox from "@mui/material/Checkbox";
import styles from "@/components/Authentication/Authentication.module.css";
import WrenchBoardLogo from "@/public/images/logos/wrenchboard-logo.png";
import Visibility from "@mui/icons-material/Visibility";
import VisibilityOff from "@mui/icons-material/VisibilityOff";
import styles from "./signinform.module.css";
import Fetcher from "services/Fetcher";
import { useUserProfile } from "contexts/userProfileContext";
const SignInForm = () => {
const handleSubmit = (event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
console.log({
email: data.get("email"),
password: data.get("password"),
});
const { state, dispatch } = useUserProfile();
// Define and initialize state variables
const [formValues, setFormValues] = useState({
email: "",
password: "",
});
const [errorHandlers, setErrorHandlers] = useState({
email: false,
password: false,
});
const [loading, setLoading] = useState(false);
const [errMsg, setErrMsg] = useState("");
// Create instances of external services
const api = new Fetcher();
const router = useRouter();
// Access the Snackbar notification function
const { enqueueSnackbar } = useSnackbar();
// Handle changes in the input fields
const handleChange = (event) => {
setFormValues({ ...formValues, [event.target.name]: event.target.value });
};
// Handle form submission
const handleSubmit = async (event) => {
event.preventDefault();
const { email, password } = formValues;
// Validate the form fields
if (email === "" && password === "") {
setErrorHandlers({ ...errorHandlers, email: true, password: true });
setErrMsg("all fields are required");
setTimeout(() => {
setErrorHandlers({ ...errorHandlers, email: false, password: false });
setErrMsg("");
}, 2000);
return;
} else if (email === "") {
setErrorHandlers({ ...errorHandlers, email: true });
setErrMsg("email field is required");
setTimeout(() => {
setErrorHandlers({ ...errorHandlers, email: false });
setErrMsg("");
}, 2000);
return;
} else if (password === "") {
setErrorHandlers({ ...errorHandlers, password: true });
setErrMsg("password field is required");
setTimeout(() => {
setErrorHandlers({ ...errorHandlers, password: false });
setErrMsg("");
}, 2000);
return;
}
// Initiate the login process
setLoading(true);
try {
// Prepare the login request data
const data = {
username: email,
password,
};
// Send the login request to the server
const res = await api.login(data);
if (res.status === 204 || res.length === 0) {
// Handle login failure
enqueueSnackbar("Wrong Credentials", {
variant: "error",
});
setLoading(false);
return;
}
// Store the token in cookies
// Calculate the expiration time in 24 hours
const expirationDate = new Date();
expirationDate.setTime(expirationDate.getTime() + 24 * 60 * 60 * 1000); // 24 hours in milliseconds
const cookieOptions = {
expires: expirationDate,
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);
const userProfileData = res.profile;
localStorage.setItem("cmc-profile", JSON.stringify(userProfileData));
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("/");
console.log(res);
} catch (error) {
// Handle any errors that occur during login
setLoading(false);
console.log(error);
} finally {
// Ensure that the loading indicator is cleared after a short delay
setTimeout(() => {
setLoading(false);
}, 5000);
}
};
// Define and initialize the state variable for toggling password visibility
const [showPassword, setShowPassword] = useState(false);
// Toggle password visibility
const handleTogglePassword = () => {
setShowPassword(!showPassword);
};
useEffect(() => {
// Prefetch the dashboard page to optimize navigation
router.prefetch("/");
});
return (
<>
<div className="authenticationBox">
<div className={styles.authenticationBox}>
<Box
component="main"
sx={{
@@ -30,6 +159,9 @@ const SignInForm = () => {
ml: "auto",
mr: "auto",
padding: "50px 0 100px",
paddingInline: { sm: "10px", lg: "0" },
zIndex: "999",
position: "relative",
}}
>
<Grid item xs={12} md={12} lg={12} xl={12}>
@@ -38,17 +170,14 @@ const SignInForm = () => {
display="flex"
alignItems="center"
justifyContent="center"
mb="60px"
mb="70px"
>
<img
src="/images/logos/wrenchboard-logo.png"
src="/images/logos/android-chrome-512x512.png"
alt="logo"
className={styles.favicon}
/>
</Box>
<Typography as="h1" fontSize="28px" fontWeight="700" mb="5px">
Sign In{" "}
</Typography>
<Box component="form" noValidate onSubmit={handleSubmit}>
<Box
@@ -62,96 +191,95 @@ const SignInForm = () => {
>
<Grid container alignItems="center" spacing={2}>
<Grid item xs={12}>
<Typography
component="label"
sx={{
fontWeight: "500",
fontSize: "14px",
mb: "10px",
display: "block",
}}
>
Email
</Typography>
<TextField
required
fullWidth
id="email"
label="Email Address"
label={
errorHandlers.email && errMsg !== ""
? errMsg
: "Email Address"
}
value={formValues.email}
onChange={handleChange}
name="email"
autoComplete="email"
InputProps={{
style: { borderRadius: 8 },
}}
sx={textFieldStyles}
error={errorHandlers.email}
/>
</Grid>
<Grid item xs={12}>
<Typography
component="label"
sx={{
fontWeight: "500",
fontSize: "14px",
mb: "10px",
display: "block",
}}
>
Password
</Typography>
<TextField
required
fullWidth
name="password"
label="Password"
type="password"
label={
errorHandlers.password && errMsg !== ""
? errMsg
: "Password"
}
value={formValues.password}
type={showPassword ? "text" : "password"}
id="password"
autoComplete="new-password"
onChange={handleChange}
error={errorHandlers.password}
InputProps={{
style: { borderRadius: 8 },
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={handleTogglePassword}
sx={{
color: "#4687BA",
"&:hover": {
color: "#4687BA",
},
}}
>
{showPassword ? (
<VisibilityOff />
) : (
<Visibility />
)}
</IconButton>
</InputAdornment>
),
}}
sx={textFieldStyles}
/>
</Grid>
</Grid>
</Box>
<Grid container alignItems="center" spacing={2}>
<Grid item xs={6} sm={6}>
<FormControlLabel
control={
<Checkbox value="allowExtraEmails" color="primary" />
}
label="Remember me."
/>
</Grid>
<Grid item xs={6} sm={6} textAlign="end">
<Link
href="/auth/forgot-password"
className="primaryColor text-decoration-none"
>
Forgot your password?
</Link>
</Grid>
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
sx={{
mt: 2,
textTransform: "capitalize",
borderRadius: "8px",
fontWeight: "500",
fontSize: "16px",
padding: "12px 10px",
color: "#fff !important",
}}
>
Sign In
</Button>
<Box sx={{ backgroundColor: "#4687BA" }}>
<LoadingButton
type="submit"
fullWidth
variant="contained"
loading={loading}
disabled={loading}
loadingIndicator="Signing in…"
sx={{
backgroundColor: "#4687BA",
textTransform: "capitalize",
borderRadius: "8px",
fontWeight: "500",
fontSize: "16px",
padding: "12px 10px",
color: "#fff !important",
"&:hover": {
backgroundColor: "rgba(70, 135, 186, 0.8)",
},
}}
>
<span>{loading ? "Signing in…" : "Sign In"}</span>
</LoadingButton>
</Box>
</Box>
</Box>
</Grid>
@@ -162,3 +290,39 @@ const SignInForm = () => {
};
export default SignInForm;
// Custom styles for text fields in sign up
const textFieldStyles = {
"& .MuiOutlinedInput-root": {
"& fieldset": {
borderColor: "#4687BA",
"&:hover": {
borderColor: "#4687BA",
},
},
"&.Mui-focused fieldset": {
borderColor: "#4687BA",
},
},
"& .MuiInputAdornment-positionEnd": {
cursor: "pointer",
},
"& .MuiFormLabel-root": {
color: "#4687BA",
},
"&:hover .MuiFormLabel-root": {
color: "#4687BA",
},
"&.Mui-focused .MuiFormLabel-root": {
color: "#4687BA",
},
"& .MuiInputBase-input": {
color: "#4687BA",
},
"&:hover .MuiInputBase-input": {
color: "#4687BA",
},
"&.Mui-focused .MuiInputBase-input": {
color: "#4687BA",
},
};
+2 -2
View File
@@ -45,7 +45,7 @@ const SignUpForm = () => {
<Typography fontSize="15px" mb="30px">
Already have an account?{" "}
<Link
href="/auth/sign-in/"
href="/auth/login/"
className="primaryColor text-decoration-none"
>
Sign in
@@ -215,7 +215,7 @@ const SignUpForm = () => {
<Button
type="submit"
fullWidth
variant="contained"
// variant="contained"
sx={{
mt: 2,
textTransform: "capitalize",
@@ -0,0 +1,38 @@
.favicon {
position: relative;
top: 5px;
max-width: 250px;
max-height: 250px;
width: 100%;
height: 100%;
}
.authenticationBox {
width: 100%;
min-height: 100vh;
position: relative;
padding: 1rem;
/* Image */
background-image: url("../../public//images/auth/cms_home.jpg");
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
background-attachment: fixed;
}
.authenticationBox::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
}
@media (min-width: 600px) {
.authenticationBox {
padding: 1rem;
}
}
+15 -8
View File
@@ -6,7 +6,6 @@ import TopNavbar from "@/components/_App/TopNavbar";
import Footer from "@/components/_App/Footer";
import ScrollToTop from "./ScrollToTop";
import ControlPanelModal from "./ControlPanelModal";
import AuthRoute from "middlewares/AuthRoute";
const Layout = ({ children }) => {
const router = useRouter();
@@ -20,20 +19,18 @@ const Layout = ({ children }) => {
useEffect(() => {
const authenticationPages = [
"/auth",
"/auth/sign-in",
"/auth/login",
"/auth/sign-up",
"/auth/forgot-password",
"/auth/lock-screen",
"/auth/confirm-mail",
"/auth/logout",
];
setIsAuthenticationPage(authenticationPages.includes(router.pathname));
}, [router.pathname]);
// Debugging: Log the value of isAuthenticationPage
console.log("isAuthenticationPage:", isAuthenticationPage, router.pathname);
// console.log("isAuthenticationPage:", isAuthenticationPage, router.pathname);
const title = isAuthenticationPage ? "CMC - auth" : "CMC - dashboard";
@@ -44,7 +41,11 @@ const Layout = ({ children }) => {
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
</Head>
<div className={`main-wrapper-content ${active ? "active" : ""}`}>
<div
className={`main-wrapper-content ${active ? "active" : ""} ${
isAuthenticationPage ? "authBox" : ""
}`}
>
{!isAuthenticationPage && (
<>
<TopNavbar toggleActive={toggleActive} />
@@ -52,9 +53,15 @@ const Layout = ({ children }) => {
</>
)}
<div className="main-content">{children}</div>
<div
className={`main-content ${isAuthenticationPage ? "authBox" : ""}`}
>
{children}
</div>
{!isAuthenticationPage && <Footer />}
{!isAuthenticationPage && router.pathname !== "/auth/logout" && (
<Footer />
)}
</div>
<ScrollToTop />
+7 -1
View File
@@ -6,6 +6,7 @@ import LayersIcon from "@mui/icons-material/Layers";
import CheckBoxOutlineBlankIcon from "@mui/icons-material/CheckBoxOutlineBlank";
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
import LockIcon from "@mui/icons-material/Lock";
import LogoutIcon from "@mui/icons-material/Logout";
import SettingsIcon from "@mui/icons-material/Settings";
import PostAddIcon from "@mui/icons-material/PostAdd";
import MailOutlineIcon from "@mui/icons-material/MailOutline";
@@ -450,7 +451,7 @@ export const SidebarData = [
},
{
title: "Authentication",
path: "/auth/sign-in/",
path: "/auth/",
icon: <LockIcon />,
iconClosed: <KeyboardArrowRightIcon />,
iconOpened: <KeyboardArrowDownIcon />,
@@ -513,4 +514,9 @@ export const SidebarData = [
},
],
},
{
title: "Logout",
path: "/auth/logout",
icon: <LogoutIcon />,
},
];
+41 -41
View File
@@ -1,69 +1,69 @@
import React from 'react';
import {
Box
} from "@mui/material";
import React from "react";
import { Box } from "@mui/material";
import { styled } from "@mui/material/styles";
import { SidebarData } from './SidebarData';
import SubMenu from './SubMenu';
import Link from 'next/link';
import ClearIcon from '@mui/icons-material/Clear';
import IconButton from '@mui/material/IconButton';
import { SidebarData } from "./SidebarData";
import SubMenu from "./SubMenu";
import Link from "next/link";
import ClearIcon from "@mui/icons-material/Clear";
import IconButton from "@mui/material/IconButton";
const SidebarNav = styled("nav")(({ theme }) => ({
background: '#fff',
background: "#fff",
boxShadow: "0px 4px 20px rgba(47, 143, 232, 0.07)",
width: '300px',
padding: '30px 10px',
height: '100vh',
display: 'flex',
justifyContent: 'center',
position: 'fixed',
width: "300px",
padding: "30px 10px",
height: "100vh",
display: "flex",
justifyContent: "center",
position: "fixed",
top: 0,
left: 0,
transition: '350ms',
zIndex: '10',
overflowY: 'auto'
transition: "350ms",
zIndex: "10",
overflowY: "auto",
}));
const SidebarWrap = styled("div")(({ theme }) => ({
width: '100%'
width: "100%",
}));
const Sidebar = ({ toggleActive }) => {
return (
<>
<div className='leftSidebarDark'>
<div className="leftSidebarDark">
<SidebarNav className="LeftSidebarNav">
<SidebarWrap>
<Box
sx={{
mb: '20px',
px: '20px',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between'
<Box
sx={{
mb: "20px",
px: "20px",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
>
<Link href='/'>
<img
src="/images/logos/wrenchboard-logo.png" alt="Logo"
className='black-logo'
<Link href="/">
<img
src="/images/logos/wrenchboard-logo.png"
alt="Logo"
className="black-logo"
/>
{/* For Dark Variation */}
<img
src="/images/logos/wrenchboard-logo.png" alt="Logo"
className='white-logo'
<img
src="/images/logos/wrenchboard-logo.png"
alt="Logo"
className="white-logo"
/>
</Link>
<IconButton
onClick={toggleActive}
<IconButton
onClick={toggleActive}
size="small"
sx={{
background: 'rgb(253, 237, 237)',
display: { lg: 'none' },
marginLeft: "1rem"
background: "rgb(253, 237, 237)",
display: { lg: "none" },
marginLeft: "1rem",
}}
>
<ClearIcon />
+7 -1
View File
@@ -17,8 +17,14 @@ import MailOutlineIcon from "@mui/icons-material/MailOutline";
import ChatBubbleOutlineIcon from "@mui/icons-material/ChatBubbleOutline";
import AttachMoneyIcon from "@mui/icons-material/AttachMoney";
import Logout from "@mui/icons-material/Logout";
import { useUserProfile } from "contexts/userProfileContext";
const Profile = () => {
const { state } = useUserProfile();
const userProfile = state.userProfile;
console.log(userProfile)
const [anchorEl, setAnchorEl] = React.useState(null);
const open = Boolean(anchorEl);
const handleClick = (event) => {
@@ -98,7 +104,7 @@ const Profile = () => {
fontWeight: "500",
}}
>
Adison Jeck
{`${userProfile?.firstname} ${userProfile?.lastname}`}
</Typography>
</Box>
</MenuItem>
+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>
);
};
+49
View File
@@ -0,0 +1,49 @@
import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { getCookie, hasCookie } from "cookies-next";
export async function middleware(req, next) {
const token = getCookie("cmc-token", { req }); // Access the token from cookies
const headers = new Headers(req.headers);
headers.set("X-XSS-Protection", "1; mode=block");
headers.set("X-Frame-Options", "SAMEORIGIN");
headers.set("Content-Security-Policy", "frame-ancestors 'same';");
const { origin, pathname } = req.nextUrl;
try {
// console.log("Test path", pathname, origin);
if (token) {
// Redirect to the home page if already authenticated
NextResponse.redirect(new URL(pathname, origin), { status: 302 });
// Continue with the request if authenticated
return NextResponse.next();
}
if (
!authenticationPages.includes(pathname) ||
(authenticationPages.includes(pathname) && !token)
) {
// Redirect to the login page if not authenticated
return NextResponse.redirect(new URL("/auth/login", origin), {
status: 307,
});
}
} catch (error) {
console.error("Error during authentication check:", error);
return NextResponse.error();
}
}
export const config = {
matcher: "/",
};
const authenticationPages = [
"/auth/login",
"/auth/sign-up",
"/auth/logout",
];
+24 -11
View File
@@ -1,24 +1,37 @@
"use client";
"use client"
import { useEffect } from "react";
import { useRouter } from "next/router";
/**
* This function is used to protect routes in a web application.
* It checks if the user is authenticated and redirects them to the sign-in page if they are not.
*/
const AuthRoute = ({ children }) => {
const router = useRouter();
const token = req.cookies["cmc-token"]; // Access the token from cookies
useEffect(() => {
const isAuthenticated = true; // In a real application, this would be determined based on the user's authentication status.
if (!isAuthenticated) {
router.push("/auth/");
}
}, [router]);
const isAuthenticated = token ? true : false;
// if (router.pathname === "/auth/login" && isAuthenticated) {
// router.push("/");
// }
// if (!authenticationPages.includes(router.pathname) && !isAuthenticated) {
// router.push("/auth/login");
// }
}, []);
return <>{children}</>;
};
export default AuthRoute;
const authenticationPages = [
// "/",
"/auth",
"/auth/login",
"/auth/sign-up",
"/auth/forgot-password",
"/auth/lock-screen",
"/auth/confirm-mail",
"/auth/logout",
];
+5 -1
View File
@@ -25,6 +25,7 @@
"@mui/x-date-pickers": "^5.0.12",
"@ramonak/react-progress-bar": "^5.0.3",
"apexcharts": "^3.36.3",
"bootstrap": "^5.3.2",
"chart.js": "^4.3.0",
"dayjs": "^1.11.7",
"eslint": "8.28.0",
@@ -40,7 +41,10 @@
"react-simple-maps": "^3.0.0",
"react-tabs": "^6.0.0",
"recharts": "^2.2.0",
"swiper": "^8.4.5"
"swiper": "^8.4.5",
"axios": "^0.24.0",
"cookies-next": "4.0.0"
},
"devDependencies": {
"sass": "^1.57.1"
+40 -8
View File
@@ -1,4 +1,5 @@
import React from "react";
import React, { useEffect } from "react";
import Head from "next/head";
import "../styles/remixicon.css";
import "react-tabs/style/react-tabs.css";
import "swiper/css";
@@ -13,21 +14,52 @@ import "../styles/rtl.css";
import "../styles/dark.css";
// Theme Styles
import theme from "../styles/theme";
import { SnackbarProvider } from "notistack";
import { ThemeProvider, CssBaseline } from "@mui/material";
import Layout from "@/components/_App/Layout";
import AuthRoute from "middlewares/AuthRoute";
import { UserProfileProvider } from "contexts/userProfileContext";
import { useRouter } from "next/router";
import { hasCookie } from "cookies-next";
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");
}
};
useEffect(() => {
// Attach the event handler when the component mounts
window.onpopstate = handlePopState;
// Clean up the event handler when the component unmounts
return () => {
window.onpopstate = null;
};
}, []);
return (
<>
<Head>
<title>{!hasCookie("cmc-token") && "CMC - auth"}</title>
</Head>
<ThemeProvider theme={theme}>
<CssBaseline />
<AuthRoute>
<Layout>
<Component {...pageProps} />
</Layout>
</AuthRoute>
<UserProfileProvider>
<SnackbarProvider
maxSnack={3}
autoHideDuration={2000}
preventDuplicate
>
<Layout>
<Component {...pageProps} />
</Layout>
</SnackbarProvider>
</UserProfileProvider>
</ThemeProvider>
</>
);
+1 -1
View File
@@ -1,5 +1,5 @@
import SignInForm from "@/components/Authentication/SignInForm";
export default function Index() {
export default function Login() {
return <SignInForm />;
}
+33 -18
View File
@@ -1,8 +1,23 @@
import { useRouter } from "next/router";
import { Typography } from "@mui/material";
import { Box } from "@mui/system";
import Button from "@mui/material/Button";
import LogoutIcon from "@mui/icons-material/Logout";
import { deleteCookie } from "cookies-next";
export default function Logout() {
const router = useRouter();
const handleLogout = () => {
// Remove the cookie and local storage
deleteCookie("cmc-token");
localStorage.removeItem("cmc-profile");
// 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 (
<>
<div className="authenticationBox">
@@ -20,51 +35,51 @@ export default function Logout() {
maxWidth: "510px",
ml: "auto",
mr: "auto",
textAlign: "center"
textAlign: "center",
}}
className="bg-black"
>
<Box>
<img
src="/images/logo.png"
alt="Black logo"
className="black-logo"
<img
src="/images/logos/wrenchboard-logo.png"
alt="Logo"
className="black-logo"
/>
<img
src="/images/logo-white.png"
alt="White logo"
className="white-logo"
<img
src="/images/logos/wrenchboard-logo.png"
alt="Logo"
className="white-logo"
/>
</Box>
<Box mt={4} mb={4}>
<img src="/images/coffee.png" alt="Coffee" />
<LogoutIcon />
</Box>
<Typography as="h1" fontSize="20px" fontWeight="500" mb={1}>
You are Logged Out
</Typography>
<Typography>
Thank you for using Admash admin template
Would you like to sign out?
</Typography>
<Button
href="/auth/sign-in/"
onClick={handleLogout}
fullWidth
variant="contained"
sx={{
mt: 3,
backgroundColor: "#4687BA",
textTransform: "capitalize",
borderRadius: "8px",
fontWeight: "500",
fontSize: "16px",
padding: "12px 10px",
color: "#fff !important"
color: "#fff !important",
"&:hover": {
backgroundColor: "rgba(70, 135, 186, 0.8)",
},
}}
>
Sign In
Sign Out
</Button>
</Box>
</Box>
-5
View File
@@ -1,5 +0,0 @@
import SignInForm from "@/components/Authentication/SignInForm";
export default function SignIn() {
return <SignInForm />;
}
+1 -1
View File
@@ -16,7 +16,7 @@ import TeamMembersList from "@/components/Dashboard/eCommerce/TeamMembersList";
import BestSellingProducts from "@/components/Dashboard/eCommerce/BestSellingProducts";
import LiveVisitsOnOurSite from "@/components/Dashboard/eCommerce/LiveVisitsOnOurSite";
export default function eCommerce() {
export default function ECommerce() {
return (
<>
{/* Page title */}
+5
View File
@@ -9,8 +9,13 @@ import ProfileContent from '@/components/Pages/Profile/ProfileContent';
import ImpressionGoalConversions from "@/components/Dashboard/Analytics/ImpressionGoalConversions";
import Link from 'next/link';
import styles from '@/styles/PageTitle.module.css';
import { useUserProfile } from 'contexts/userProfileContext';
export default function Profile() {
const { state } = useUserProfile();
const userProfile = state.userProfile;
console.log(userProfile)
return (
<>
{/* Page title */}
Binary file not shown.

After

Width:  |  Height:  |  Size: 443 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

+62
View File
@@ -0,0 +1,62 @@
import Axios from "axios";
class Fetcher {
constructor(url) {
// this.url = url;
// console.log("first request!!!");
// return new Response("Working!!!" + url)
}
// Endpoints Here
// GET /api/
// POST /api/
login(values) {
return this.postAuxEnd("/auth/login", values);
}
//---------------------------------------- -----
// Unified call below
//---------------------------------------- -----
async getAuxEnd(uri, reqData) {
const endPoint =
(process.env.AUX_ENDPOINT || "http://localhost:50016/api") + uri;
console.log("Checking endpoint get request", endPoint);
try {
const response = await Axios.get(endPoint);
console.log(response.data); // Log the response data if needed.
return response.data;
} catch (error) {
this.handleAxiosError(error);
}
}
async postAuxEnd(uri, reqData) {
const endPoint =
(process.env.AUX_ENDPOINT || "http://localhost:50016/api") + uri;
console.log("Checking endpoint post request", endPoint);
try {
const response = await Axios.post(endPoint, reqData);
console.log(response.data); // Log the response data if needed.
return response.data;
} catch (error) {
this.handleAxiosError(error);
}
}
handleAxiosError(error) {
if (error.response) {
// Response status is an error code.
console.log(error.response.status);
} else if (error.request) {
// Response not received though the request was sent.
console.log(error.request);
} else {
// An error occurred when setting up the request.
console.log(error.message);
}
}
}
export default Fetcher;
+10
View File
@@ -13,6 +13,7 @@
--fontSize: 15px;
--transition: all ease .5s;
--box-shadow: 0 0 20px 3px rgba(0, 0, 0, 0.05);
--mobile-auth-padding: 0;
}
html, body {
@@ -803,6 +804,10 @@ img {
position: relative;
transition: all 0.5s ease-out;
}
.main-wrapper-content.authBox{
padding-left: 0;
}
.main-wrapper-content.active {
padding-left: 0;
}
@@ -817,12 +822,17 @@ img {
padding-right: 30px;
}
.main-wrapper-content .main-content.authBox{
padding: 0px !important;
}
@media only screen and (max-width: 767px) {
.main-wrapper-content .main-content {
padding-left: 15px !important;
padding-right: 15px !important;
}
}
@media only screen and (max-width: 1199px) {
.main-wrapper-content {
padding: 0;
+27
View File
@@ -0,0 +1,27 @@
// utils/localStorageHandler.js
import { getCookie, deleteCookie } from "cookies-next";
const handleLocalStorageChanges = () => {
const storedUserProfile = localStorage.getItem('cmc-profile');
const storedToken = getCookie('cmc-token');
window.onstorage = (e) => {
if (e.key === 'userProfile' && e.newValue !== storedUserProfile) {
// User profile data in 'localStorage' has changed
// Delete the 'userProfile' from 'localStorage'
localStorage.removeItem("cmc-profile");
// Delete the 'cmc-token' cookie
deleteCookie('cmc-token');
// Redirect to the login page
window.location.href = '/auth/login';
// Reload the page
window.location.reload();
}
};
};
export default handleLocalStorageChanges;