updated app.jsx to include a login workflow
This commit is contained in:
parent
3daac43d76
commit
69c3059ef0
@ -47,3 +47,30 @@
|
||||
.create-new-button:hover {
|
||||
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;
|
||||
}
|
||||
|
||||
@ -32,24 +32,72 @@ function App() {
|
||||
if (isLoggedIn && token) {
|
||||
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 = () => {
|
||||
fetch('http://localhost:9000/api/articles')
|
||||
.then(response => response.json())
|
||||
.then(data => setArticles(data))
|
||||
.catch(error => console.error('Error fetching articles:', error))
|
||||
fetch('http://localhost:9000/api/articles', {
|
||||
headers: {
|
||||
'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 fetching articles:', error));
|
||||
};
|
||||
|
||||
const handleSearch = (query) => {
|
||||
if (!query) {
|
||||
fetch('http://localhost:9000/api/articles')
|
||||
.then(response => response.json())
|
||||
.then(data => setArticles(data));
|
||||
fetchArticles();
|
||||
} else {
|
||||
fetch(`http://localhost:9000/api/search?q=${encodeURIComponent(query)}`)
|
||||
.then(response => response.json())
|
||||
.then(data => setArticles(data));
|
||||
fetch('http://localhost:9000/api/articles', {
|
||||
headers: {
|
||||
'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) {
|
||||
fetch('http://localhost:9000/api/articles', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify(updatedArticle)
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
setSelectedArticle(data);
|
||||
setCurrentView('detail');
|
||||
});
|
||||
fetchArticles();
|
||||
})
|
||||
.catch(error => console.error('Error creating article:', error));
|
||||
} else {
|
||||
fetch(`http://localhost:9000/api/articles/${updatedArticle.ka_number}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify(updatedArticle)
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
setSelectedArticle(data);
|
||||
setCurrentView('detail');
|
||||
});
|
||||
fetchArticles();
|
||||
})
|
||||
.catch(error => console.error('Error updating article:', error));
|
||||
}
|
||||
};
|
||||
|
||||
@ -117,40 +175,73 @@ function App() {
|
||||
const handleDelete = () => {
|
||||
if (confirm('Are you sure you want to delete this article?')) {
|
||||
fetch(`http://localhost:9000/api/articles/${selectedArticle.ka_number}`, {
|
||||
method: 'DELETE'
|
||||
method: 'DELETE',
|
||||
headers: {'Authorization': `Bearer ${token}`}
|
||||
})
|
||||
.then(() => {
|
||||
return fetch('http://localhost:9000/api/articles');
|
||||
.then(response => {
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
handleLogout();
|
||||
return response.json();
|
||||
}
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
setArticles(data);
|
||||
.then(() => {
|
||||
fetchArticles();
|
||||
setCurrentView('list');
|
||||
setSelectedArticle(null);
|
||||
})
|
||||
.catch(error => console.error('Error deleting article:', error));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const handleSwitchToLogin = () => {
|
||||
setAuthView('login');
|
||||
};
|
||||
|
||||
const handleSwitchToRegister = () => {
|
||||
setAuthView('register');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
<Header />
|
||||
|
||||
{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} />
|
||||
{/* Show Login/Registration if not logged in */}
|
||||
{!isLoggedIn ? (
|
||||
authView === 'login' ? (
|
||||
<Login
|
||||
onLoginSuccess={handleLoginSuccess}
|
||||
onSwitchToRegister={handleSwitchToRegister}
|
||||
/>
|
||||
) : (
|
||||
<Registration
|
||||
onRegistrationSuccess={handleRegistrationSuccess}
|
||||
onSwitchToLogin={handleSwitchToLogin}
|
||||
/>
|
||||
)
|
||||
) : (
|
||||
<ArticleEditor article={selectedArticle} onSave={handleSave} onCancel={handleCancelEdit} />
|
||||
<>
|
||||
<div className="user-info">
|
||||
<span>Welcome, {currentUser?.display_name || currentUser?.username}!</span>
|
||||
<button className="logout-button" onClick={handleLogout}>Logout</button>
|
||||
</div>
|
||||
|
||||
{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} />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App
|
||||
export default App;
|
||||
@ -61,7 +61,7 @@ function Registration({ onRegistrationSuccess, onSwitchToLogin }) {
|
||||
<h2>Create Account</h2>
|
||||
{error && <div className='error-message'>{error}</div>}
|
||||
|
||||
<form onSubmit={{handleSubmit}}>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className='form-group'>
|
||||
<label htmlFor="username">Username:</label>
|
||||
<input
|
||||
@ -77,7 +77,7 @@ function Registration({ onRegistrationSuccess, onSwitchToLogin }) {
|
||||
<div className='form-group'>
|
||||
<label htmlFor='email'>Email:</label>
|
||||
<input
|
||||
type='text'
|
||||
type='email'
|
||||
id='email'
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
@ -141,4 +141,4 @@ function Registration({ onRegistrationSuccess, onSwitchToLogin }) {
|
||||
);
|
||||
}
|
||||
|
||||
export default Reguistration
|
||||
export default Registration
|
||||
@ -208,14 +208,14 @@ function searchArticles(query) {
|
||||
* @param {string} username - The username 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} 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} 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
|
||||
*/
|
||||
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 (?, ?, ?, ?, ?, ?)",
|
||||
[username, email, passHash, displayName, authProvider, entraId]
|
||||
[username, email, passHash, display_name, authProvider, entraId]
|
||||
)
|
||||
|
||||
// Saving DB with newly created record
|
||||
|
||||
@ -118,9 +118,9 @@ initDb().then(() => {
|
||||
|
||||
app.post('/api/auth/register', async (req, res) => {
|
||||
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'});
|
||||
}
|
||||
|
||||
@ -135,7 +135,7 @@ initDb().then(() => {
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
return res.status(201).json({
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user