updated app.jsx to include a login workflow

This commit is contained in:
MattLeo 2025-12-02 10:20:49 -06:00
parent 3daac43d76
commit 69c3059ef0
5 changed files with 160 additions and 42 deletions

View File

@ -47,3 +47,30 @@
.create-new-button:hover { .create-new-button:hover {
background-color: #229954; background-color: #229954;
} }
.user-info {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
background-color: #34495e;
color: white;
}
.user-info span {
font-size: 1rem;
}
.logout-button {
background-color: #e74c3c;
color: white;
padding: 0.5rem 1rem;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 0.9rem;
}
.logout-button:hover {
background-color: #c0392b;
}

View File

@ -32,24 +32,72 @@ function App() {
if (isLoggedIn && token) { if (isLoggedIn && token) {
fetchArticles(); fetchArticles();
} }
}, []); }, [isLoggedIn, token]);
const handleLoginSuccess = (user, authToken) => {
setCurrentUser(user);
setToken(authToken);
setIsLoggedIn(true);
localStorage.setItem('token', authToken);
localStorage.setItem('user', JSON.stringify(user));
};
const handleRegistrationSuccess = (user, authToken) => {
handleLoginSuccess(user, authToken);
};
const handleLogout = () => {
setIsLoggedIn(false);
setCurrentUser(null);
setToken(null);
setArticles([]);
setCurrentView('list');
setSelectedArticle(null);
localStorage.removeItem('token');
localStorage.removeItem('user');
};
const fetchArticles = () => { const fetchArticles = () => {
fetch('http://localhost:9000/api/articles') fetch('http://localhost:9000/api/articles', {
.then(response => response.json()) headers: {
.then(data => setArticles(data)) 'Authorization': `Bearer ${token}`
.catch(error => console.error('Error fetching articles:', error)) },
})
.then(response => {
if (response.status === 401 || response.status === 403) {
handleLogout();
return;
}
return response.json();
})
.then(data => {
if (data) setArticles(data);
})
.catch(error => console.error('Error fetching articles:', error));
}; };
const handleSearch = (query) => { const handleSearch = (query) => {
if (!query) { if (!query) {
fetch('http://localhost:9000/api/articles') fetchArticles();
.then(response => response.json())
.then(data => setArticles(data));
} else { } else {
fetch(`http://localhost:9000/api/search?q=${encodeURIComponent(query)}`) fetch('http://localhost:9000/api/articles', {
.then(response => response.json()) headers: {
.then(data => setArticles(data)); 'Authorization': `Bearer ${token}`
}
})
.then(response => {
if (response.status === 401 || response.status === 403) {
handleLogout();
return;
}
return response.json();
})
.then(data => {
if (data) setArticles(data);
})
.catch(error => console.error('Error searching articles:', error));
} }
}; };
@ -73,25 +121,35 @@ function App() {
if (isNew) { if (isNew) {
fetch('http://localhost:9000/api/articles', { fetch('http://localhost:9000/api/articles', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(updatedArticle) body: JSON.stringify(updatedArticle)
}) })
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
setSelectedArticle(data); setSelectedArticle(data);
setCurrentView('detail'); setCurrentView('detail');
}); fetchArticles();
})
.catch(error => console.error('Error creating article:', error));
} else { } else {
fetch(`http://localhost:9000/api/articles/${updatedArticle.ka_number}`, { fetch(`http://localhost:9000/api/articles/${updatedArticle.ka_number}`, {
method: 'PUT', method: 'PUT',
headers: { 'Content-Type': 'application/json' }, headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(updatedArticle) body: JSON.stringify(updatedArticle)
}) })
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
setSelectedArticle(data); setSelectedArticle(data);
setCurrentView('detail'); setCurrentView('detail');
}); fetchArticles();
})
.catch(error => console.error('Error updating article:', error));
} }
}; };
@ -117,40 +175,73 @@ function App() {
const handleDelete = () => { const handleDelete = () => {
if (confirm('Are you sure you want to delete this article?')) { if (confirm('Are you sure you want to delete this article?')) {
fetch(`http://localhost:9000/api/articles/${selectedArticle.ka_number}`, { fetch(`http://localhost:9000/api/articles/${selectedArticle.ka_number}`, {
method: 'DELETE' method: 'DELETE',
headers: {'Authorization': `Bearer ${token}`}
}) })
.then(() => { .then(response => {
return fetch('http://localhost:9000/api/articles'); if (response.status === 401 || response.status === 403) {
handleLogout();
return response.json();
}
}) })
.then(response => response.json()) .then(() => {
.then(data => { fetchArticles();
setArticles(data);
setCurrentView('list'); setCurrentView('list');
setSelectedArticle(null); setSelectedArticle(null);
}) })
.catch(error => console.error('Error deleting article:', error)); .catch(error => console.error('Error deleting article:', error));
} }
}; };
const handleSwitchToLogin = () => {
setAuthView('login');
};
const handleSwitchToRegister = () => {
setAuthView('register');
};
return ( return (
<div className="app"> <div className="app">
<Header /> <Header />
{currentView === 'list' ? ( {/* Show Login/Registration if not logged in */}
{!isLoggedIn ? (
authView === 'login' ? (
<Login
onLoginSuccess={handleLoginSuccess}
onSwitchToRegister={handleSwitchToRegister}
/>
) : (
<Registration
onRegistrationSuccess={handleRegistrationSuccess}
onSwitchToLogin={handleSwitchToLogin}
/>
)
) : (
<> <>
<SearchBar onSearch={handleSearch} /> <div className="user-info">
<button className='create-new-button' onClick={handleCreateNew}> <span>Welcome, {currentUser?.display_name || currentUser?.username}!</span>
+ Create New Article <button className="logout-button" onClick={handleLogout}>Logout</button>
</button> </div>
<ArticleList articles={articles} onArticleClick={handleArticleClick} />
{currentView === 'list' ? (
<>
<SearchBar onSearch={handleSearch} />
<button className='create-new-button' onClick={handleCreateNew}>
+ Create New Article
</button>
<ArticleList articles={articles} onArticleClick={handleArticleClick} />
</>
) : currentView === 'detail' ? (
<ArticleDetail article={selectedArticle} onBack={handleBack} onEdit={handleEdit} onDelete={handleDelete} />
) : (
<ArticleEditor article={selectedArticle} onSave={handleSave} onCancel={handleCancelEdit} />
)}
</> </>
) : currentView === 'detail' ? (
<ArticleDetail article={selectedArticle} onBack={handleBack} onEdit={handleEdit} onDelete={handleDelete} />
) : (
<ArticleEditor article={selectedArticle} onSave={handleSave} onCancel={handleCancelEdit} />
)} )}
</div> </div>
); );
} }
export default App export default App;

View File

@ -61,7 +61,7 @@ function Registration({ onRegistrationSuccess, onSwitchToLogin }) {
<h2>Create Account</h2> <h2>Create Account</h2>
{error && <div className='error-message'>{error}</div>} {error && <div className='error-message'>{error}</div>}
<form onSubmit={{handleSubmit}}> <form onSubmit={handleSubmit}>
<div className='form-group'> <div className='form-group'>
<label htmlFor="username">Username:</label> <label htmlFor="username">Username:</label>
<input <input
@ -77,7 +77,7 @@ function Registration({ onRegistrationSuccess, onSwitchToLogin }) {
<div className='form-group'> <div className='form-group'>
<label htmlFor='email'>Email:</label> <label htmlFor='email'>Email:</label>
<input <input
type='text' type='email'
id='email' id='email'
value={email} value={email}
onChange={(e) => setEmail(e.target.value)} onChange={(e) => setEmail(e.target.value)}
@ -141,4 +141,4 @@ function Registration({ onRegistrationSuccess, onSwitchToLogin }) {
); );
} }
export default Reguistration export default Registration

View File

@ -208,14 +208,14 @@ function searchArticles(query) {
* @param {string} username - The username for the newly created user * @param {string} username - The username for the newly created user
* @param {string} email - The email address for the newly created user * @param {string} email - The email address for the newly created user
* @param {string} passHash - The hashed password for validation purposes * @param {string} passHash - The hashed password for validation purposes
* @param {string} displayName - The name that will be desplayed when an article is created or updated * @param {string} display_name - The name that will be desplayed when an article is created or updated
* @param {string} authProvider - the source of the authentication: 'local' or 'entra' * @param {string} authProvider - the source of the authentication: 'local' or 'entra'
* @param {string} entraId - The ID number for the associated entra account, can be null if auth provider is local * @param {string} entraId - The ID number for the associated entra account, can be null if auth provider is local
* @returns {Object} - The user object of the newly created user * @returns {Object} - The user object of the newly created user
*/ */
function createUser(username, email, passHash, displayName, authProvider = 'local', entraId = null) { function createUser(username, email, passHash, display_name, authProvider = 'local', entraId = null) {
db.run("INSERT INTO users (username, email, pass_hash, display_name, auth_provider, entra_id) VALUES (?, ?, ?, ?, ?, ?)", db.run("INSERT INTO users (username, email, pass_hash, display_name, auth_provider, entra_id) VALUES (?, ?, ?, ?, ?, ?)",
[username, email, passHash, displayName, authProvider, entraId] [username, email, passHash, display_name, authProvider, entraId]
) )
// Saving DB with newly created record // Saving DB with newly created record

View File

@ -118,9 +118,9 @@ initDb().then(() => {
app.post('/api/auth/register', async (req, res) => { app.post('/api/auth/register', async (req, res) => {
try { try {
const {username, email, password, displayName} = req.body; const {username, email, password, display_name} = req.body;
if (!username || !email || !password || !displayName) { if (!username || !email || !password || !display_name) {
return res.status(400).json({error: 'Username, email, password, and display name are required'}); return res.status(400).json({error: 'Username, email, password, and display name are required'});
} }
@ -135,7 +135,7 @@ initDb().then(() => {
} }
const pass_hash = await argon2.hash(password); const pass_hash = await argon2.hash(password);
const newUser = createUser(username, email, pass_hash, displayName); const newUser = createUser(username, email, pass_hash, display_name);
const token = generateToken(newUser); const token = generateToken(newUser);
return res.status(201).json({ return res.status(201).json({