0% found this document useful (0 votes)
7 views4 pages

060525

The document contains code for an authentication context and a password change component in a React application. The AuthContext manages user state and token storage, while the ChangePassword component allows users to update their password, handling form submission and loading states. The App component sets up routing for various pages, including authentication and password management features.

Uploaded by

JOSHUA OSOGO
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views4 pages

060525

The document contains code for an authentication context and a password change component in a React application. The AuthContext manages user state and token storage, while the ChangePassword component allows users to update their password, handling form submission and loading states. The App component sets up routing for various pages, including authentication and password management features.

Uploaded by

JOSHUA OSOGO
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

any changes needed?

//authcontext.js:
import { createContext, useContext, useState, useEffect } from "react";

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {


const [user, setUser] = useState(null);
const [token, setToken] = useState(null);

useEffect(() => {
const storedUser = localStorage.getItem('user');
const storedToken = localStorage.getItem('token');
if (storedUser && storedToken) {
setUser(JSON.parse(storedUser));
setToken(storedToken);
}
}, []);

const login = (userData, token) => {


localStorage.setItem('user', JSON.stringify(userData));
localStorage.setItem('token', token);
setUser(userData);
setToken(token);
};

const logout = () => {


setUser(null);
setToken(null);
localStorage.removeItem('user');
localStorage.removeItem('token');
};

const updateUser = (updatedUser) => {


setUser(updatedUser);
localStorage.setItem('user', JSON.stringify(updatedUser));
};

return (
<AuthContext.Provider value={{ user, token, login, logout, updateUser }}>
{children}
</AuthContext.Provider>
);
};

//changepassword.jsx:
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "react-hot-toast";
import axios from "axios";
import { useAuth } from "../contexts/AuthContext";
import { Loader2 } from "lucide-react";
const ChangePassword = () => {
const { user, logout } = useAuth();
const navigate = useNavigate();
const [formData, setFormData] = useState({
currentPassword: "",
newPassword: "",
});
const [loading, setLoading] = useState(false);

const handleChange = (e) => {


const { name, value } = e.target;
setFormData((prev) => ({ ...prev, [name]: value }));
};

const handleSubmit = async (e) => {


e.preventDefault();
setLoading(true);

try {
await axios.post(
"http://localhost:5000/api/auth/change-password",
{
currentPassword: formData.currentPassword,
newPassword: formData.newPassword,
},
{
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
);

toast.success("Password changed successfully. Please login again.");


logout();
navigate("/");
} catch (err) {
toast.error(err.response?.data?.message || "Failed to change password.");
} finally {
setLoading(false);
}
};

return (
<div className="min-h-screen flex items-center justify-center bg-gray-100 p-4">
<div className="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
<h2 className="text-2xl font-bold mb-6 text-center text-red-600">
Change Your Password
</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<input
type="password"
name="currentPassword"
placeholder="Current Password"
value={formData.currentPassword}
onChange={handleChange}
className="w-full p-2 border rounded"
required
/>
<input
type="password"
name="newPassword"
placeholder="New Password"
value={formData.newPassword}
onChange={handleChange}
className="w-full p-2 border rounded"
required
/>
<button
type="submit"
disabled={loading}
className={`w-full py-2 rounded text-white flex justify-center items-
center gap-2 ${
loading ? "bg-blue-400" : "bg-blue-600 hover:bg-blue-700"
}`}
>
{loading ? (
<>
<Loader2 className="animate-spin w-5 h-5" />
Updating...
</>
) : (
"Update Password"
)}
</button>
</form>
</div>
</div>
);
};

export default ChangePassword;

//app.jsx:
import UserManagement from "./pages/Admin/UserManagement";
import { Routes, Route } from 'react-router-dom';
import Auth from './pages/Auth';
import Dashboard from './pages/Dashboard';
import Department from './pages/Department';
import Inventory from "./pages/modules/Inventory";
import Purchase from './pages/modules/Purchase';
import Updates from './pages/modules/Updates';
import Tickets from './pages/modules/Tickets';
import ResetPassword from './pages/ResetPassword'; // 🆕 Add this
import { AuthProvider } from './contexts/AuthContext';
import ChangePassword from './pages/ChangePassword';

function App() {
return (
<AuthProvider>
<Routes>
{/* Auth and Reset Password */}
<Route path="/" element={<Auth />} />
<Route path="/reset-password/:token" element={<ResetPassword />} /> {/* 🆕
Password Reset Route */}
<Route path="/change-password" element={<ChangePassword />} />

{/* Main Pages */}


<Route path="/dashboard" element={<Dashboard />} />
<Route path="/department/:name" element={<Department />} />
<Route path="/admin/user-management" element={<UserManagement />} />

{/* IT Department Modules */}


<Route path="/department/it/inventory" element={<Inventory />} />
<Route path="/department/it/purchase" element={<Purchase />} />
<Route path="/department/it/updates" element={<Updates />} />
<Route path="/department/it/tickets" element={<Tickets />} />
</Routes>
</AuthProvider>
);
}

export default App;

export const useAuth = () => useContext(AuthContext);

You might also like