usama7365 / developer-community

community site soon❤️
25 stars 0 forks source link

I need some suggestion what to use instead of local storage #15

Closed Zainali005 closed 3 months ago

Zainali005 commented 3 months ago

"use client"; import { useState, useEffect } from "react"; import Image from "next/image"; import LogoDark from "@/assets/logodark.png"; import { useForm } from "react-hook-form"; import { TextField } from "@mui/material"; import Link from "next/link"; import Button from "@mui/material/Button"; import { getUser } from "./actions"; import { useSession } from "next-auth/react"; import { useRouter } from "next/navigation"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import { useAuthStore } from "@/zustand/slice/authSlice";

export default function Page() { const [loading, setLoading] = useState(false); const [redirecting, setRedirecting] = useState(false); const router = useRouter(); const { setUser } = useAuthStore();

const { register, handleSubmit, formState: { errors }, } = useForm(); const { data: session } = useSession(); useEffect(() => { if (redirecting) { const role = sessionStorage.getItem("role"); if (role === "admin") { router.push("/AdminDashboard/home"); } else { router.push("/dashboard"); } toast.success("Signin Successfully", { autoClose: 1000 }); setLoading(false); } }, [redirecting, router]);

const onSubmit = async (data: any, e: any) => { e.preventDefault(); setLoading(true);

try {
  const userData = await getUser(data);
  console.log(userData);

  setLoading(false);
  if (userData && userData.token) {
    setUser(userData);
    localStorage.setItem("userId", userData.userId);
    localStorage.setItem("token", userData.token);
    sessionStorage.setItem("role", userData.role);
    document.cookie = `token=${userData.token}`;
    document.cookie = `userId=${userData.userId}`;
    document.cookie = `role=${userData.role}`;
    setRedirecting(true);
  } else {
    toast.error("Invalid email or password", { autoClose: 1000 });
  }
} catch (error) {
  setLoading(false);
  toast.error("An error occurred. Please try again.", { autoClose: 1000 });
}

}; useEffect(() => { const role = localStorage.getItem("role"); if (role) { if (role === "admin") { router.push("/AdminDashboard"); } else { router.push("/dashboard"); } } }, [router]);

if (!session?.user?.email) { return ( <>

Don't have an account yet?{" "} sign-up

forgot your password

By clicking 'Sign In' you agree to our Term and have read and acknowledged our Privacy Statement.

  </>
);

} }

this is the code i have use local storage in local storage i have changed the role to admin its accessing the admin which is not the secure what to use instead of session or local storage ..

usama7365 commented 3 months ago

Hi @Zainali005 !

It looks like you're working on a sign-in page and are concerned about the security of storing user roles in local storage. You’re right that local storage isn't the most secure place for sensitive information like user roles, as it can be accessed easily by JavaScript running in the browser.

Here’s a better approach you can use:

1. Use Cookies with HttpOnly Flag:

2. Use Server-Side Sessions:

3. Implement Secure Token Handling:

Here's an updated version of your onSubmit function with the server-side session approach:

const onSubmit = async (data: any, e: any) => {
  e.preventDefault();
  setLoading(true);

  try {
    const response = await fetch('/api/login', {  // Replace with your server endpoint
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });

    const userData = await response.json();
    console.log(userData);

    setLoading(false);

    if (response.ok && userData && userData.token) {
      // Redirect based on user role
      const role = userData.role;
      if (role === 'admin') {
        router.push('/AdminDashboard/home');
      } else {
        router.push('/dashboard');
      }
      toast.success('Signin Successfully', { autoClose: 1000 });
    } else {
      toast.error('Invalid email or password', { autoClose: 1000 });
    }
  } catch (error) {
    setLoading(false);
    toast.error('An error occurred. Please try again.', { autoClose: 1000 });
  }
};

Make sure to update your server-side logic to set the HttpOnly cookies properly and manage user sessions securely.

Let me know if you have any more questions or need further assistance!

Best, Feline Predator