Skip to content

Commit

Permalink
delete users on admin page is working. Had to add a new collection in…
Browse files Browse the repository at this point in the history
… firebase database
  • Loading branch information
Ole994 committed Oct 29, 2024
1 parent 23c18f6 commit f90884f
Show file tree
Hide file tree
Showing 8 changed files with 151 additions and 23 deletions.
6 changes: 5 additions & 1 deletion src/AppRouter.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,21 @@ const AppRouter = () => {
path="/administration"
element={
<ProtectedRoute>
{console.log("Attempting to access /administration")}
<Administration />
</ProtectedRoute>
}
/>

<Route path="*" element={<ErrorPage />} />
<Route path="/signup" element={<SignUp />} />
<Route path="/deleteAccount" element={<DeleteAccount />} />

{/* Catch-all route for unknown paths */}
<Route path="*" element={<ErrorPage />} />
</Routes>
</Suspense>
);
};

export default AppRouter;

5 changes: 5 additions & 0 deletions src/component/ProtectedRoute/ProtectedRoute.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,16 @@ import PropTypes from 'prop-types';
const ProtectedRoute = ({ children }) => {
const { user } = useAuth();

// Log brukertilstanden for feilsøking
console.log("ProtectedRoute: Current user =", user);

if (!user) {
console.log("ProtectedRoute: User not authenticated, redirecting to login.");
// Hvis brukeren ikke er logget inn, send dem til login-siden
return <Navigate to="/login" replace />;
}

console.log("ProtectedRoute: User authenticated, rendering children.");
// Hvis brukeren er logget inn, returner komponentene (children)
return children;
};
Expand Down
42 changes: 28 additions & 14 deletions src/component/login/Login.jsx
Original file line number Diff line number Diff line change
@@ -1,43 +1,53 @@
// src/pages/login/Login.jsx
import { useState, useContext } from 'react';
import { useState, useContext, useEffect } from 'react';
import { AuthContext } from '../../context/AuthContext';
import { useNavigate } from 'react-router-dom';
import { auth } from '../../firebaseConfig';
import { signInWithEmailAndPassword } from 'firebase/auth';
import '../../component/login/login.css';

const Login = () => {
const { login } = useContext(AuthContext);
const { user, login } = useContext(AuthContext);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState(null);
const [success, setSuccess] = useState(null);
const [loading, setLoading] = useState(false);
const navigate = useNavigate();

const handleSubmit = (e) => {
e.preventDefault();
const userData = { email, name: 'Test User' };
login(userData);
navigate('/');
};
// Hvis brukeren allerede er logget inn, send dem til hjemmesiden
useEffect(() => {
if (user) {
navigate('/');
}
}, [user, navigate]);

const handleFirebaseLogin = async (e) => {
e.preventDefault();
setError(null);
setSuccess(null);
setLoading(true);

try {
const userCredential = await signInWithEmailAndPassword(auth, email, password);
const user = userCredential.user;
login({ email: user.email, name: user.displayName || 'Firebase User' });
setSuccess("Innlogging var vellykket!");
setTimeout(() => navigate('/'), 2000);
navigate('/'); // Naviger umiddelbart
} catch (err) {
console.error('Error logging in with Firebase:', err.message);
setError("Kunne ikke logge inn. Vennligst sjekk e-post og passord og prøv igjen.");
} finally {
setLoading(false);
}
};

const handleTestLogin = (e) => {
e.preventDefault();
const userData = { email, name: 'Test User' };
login(userData);
navigate('/');
};

return (
<div className="login-wrapper">
<div className="login-box">
Expand All @@ -55,6 +65,7 @@ const Login = () => {
value={email}
onChange={(e) => setEmail(e.target.value)}
required
disabled={loading} // Deaktivert under innlasting
/>
</div>
<div className="input-group">
Expand All @@ -65,16 +76,19 @@ const Login = () => {
value={password}
onChange={(e) => setPassword(e.target.value)}
required
disabled={loading} // Deaktivert under innlasting
/>
</div>
<button type="submit" className="primary-button">Logg inn</button>
<button type="submit" className="primary-button" disabled={loading}>
{loading ? "Logger inn..." : "Logg inn"}
</button>
</form>

<div className="separator">eller</div>

<form onSubmit={handleSubmit} className="login-form">
<button type="submit" className="secondary-button">Logg inn med testbruker</button>
</form>
<button onClick={handleTestLogin} className="secondary-button">
Logg inn med testbruker
</button>
</div>
</div>
);
Expand Down
26 changes: 25 additions & 1 deletion src/context/AuthContext.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,11 @@
// får alle komponenter under App tilgang til user, login, og logout.
// src/context/AuthContext.jsx
// src/context/AuthContext.jsx
import { createContext, useState, useContext } from 'react';
// src/context/AuthContext.jsx
import { createContext, useState, useContext, useEffect } from 'react';
import PropTypes from 'prop-types'; // Importer PropTypes
import { auth } from '../firebaseConfig'; // Importer Firebase-authentisering
import { onAuthStateChanged, setPersistence, browserLocalPersistence } from 'firebase/auth';

export const AuthContext = createContext();

Expand All @@ -46,6 +49,27 @@ export const AuthProvider = ({ children }) => {
setUser(null);
};

// Sett opp vedvarende pålogging og lyt etter endringer i autentiseringstilstand
useEffect(() => {
// Sett vedvarende sesjon til localStorage
setPersistence(auth, browserLocalPersistence)
.then(() => {
// Overvåk autentiseringstilstanden
onAuthStateChanged(auth, (firebaseUser) => {
if (firebaseUser) {
// Bruker er innlogget, sett brukerdata
setUser({ email: firebaseUser.email, name: firebaseUser.displayName || 'Firebase User' });
} else {
// Ingen bruker er innlogget
setUser(null);
}
});
})
.catch((error) => {
console.error('Error setting persistence:', error);
});
}, []);

return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
Expand Down
1 change: 1 addition & 0 deletions src/css/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@
margin: 0;
padding: 0;
box-sizing: border-box;
color: black;
}
60 changes: 54 additions & 6 deletions src/pages/administration/Administration.jsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,63 @@
// Code: src/pages/administration/Administration.jsx
// src/pages/administration/Administration.jsx

import { useEffect, useState } from 'react';
import { firestore } from '../../firebaseConfig';
import { collection, getDocs, deleteDoc, doc } from 'firebase/firestore';

const Administration = () => {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);

useEffect(() => {
const fetchUsers = async () => {
try {
const querySnapshot = await getDocs(collection(firestore, 'users'));
const userList = querySnapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
setUsers(userList);
} catch (error) {
console.error('Error fetching users:', error);
} finally {
setLoading(false);
}
};

fetchUsers();
}, []);

const handleDelete = async (userId) => {
try {
await deleteDoc(doc(firestore, 'users', userId));
setUsers(users.filter((user) => user.id !== userId));
alert("User deleted successfully.");
} catch (error) {
console.error('Error deleting user:', error);
alert("Failed to delete user.");
}
};

if (loading) {
return <div>Loading...</div>;
}

return (
<div>
<h2>Administration Page</h2>
<p>Welcome to the administration area. You are successfully logged in!</p>
{/* Her kan du legge til annet innhold for administrasjon */}
<h2>User Management</h2>
{users.length > 0 ? (
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name} - {user.email}
<button onClick={() => handleDelete(user.id)}>Delete</button>
</li>
))}
</ul>
) : (
<p>No users found.</p>
)}
</div>
);
};

export default Administration;

32 changes: 32 additions & 0 deletions src/pages/administration/administration.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
.admin-page {
padding: 20px;
}

table {
width: 100%;
border-collapse: collapse;
}

th, td {
padding: 10px;
text-align: left;
border: 1px solid #ddd;
}

th {
background-color: #f4f4f4;
}

.delete-button {
background-color: #ff4d4f;
color: white;
border: none;
padding: 5px 10px;
cursor: pointer;
border-radius: 3px;
}

.delete-button:hover {
background-color: #d9534f;
}

2 changes: 1 addition & 1 deletion src/pages/home/Home.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const Home = () => {
return (
<div>Home</div>
<div>Homenjnjk</div>
)
}

Expand Down

0 comments on commit f90884f

Please sign in to comment.