Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 17 additions & 14 deletions frontend/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React, { useEffect, useState } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import './i18n';
import LanguagePicker from './components/LanguagePicker';
import { AuthProvider } from './contexts/AuthContext';

// Import pages
import Home from './pages/Home';
Expand Down Expand Up @@ -33,20 +34,22 @@ function App() {
return (
<>
{showPicker && <LanguagePicker onSelect={handleSelectLang} />}
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/auth/login" element={<Login />} />
<Route path="/auth/signup" element={<Signup />} />
<Route path="/auth/forgot-password" element={<ForgotPassword />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings/account" element={<Account />} />
<Route path="/modules/heart-risk" element={<HeartRisk />} />
<Route path="/modules/prescription" element={<Prescription />} />
<Route path="/modules/tba" element={<TBA />} />
<Route path="*" element={<NotFound />} />
</Routes>
</Router>
<AuthProvider>
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/auth/login" element={<Login />} />
<Route path="/auth/signup" element={<Signup />} />
<Route path="/auth/forgot-password" element={<ForgotPassword />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings/account" element={<Account />} />
<Route path="/modules/heart-risk" element={<HeartRisk />} />
<Route path="/modules/prescription" element={<Prescription />} />
<Route path="/modules/tba" element={<TBA />} />
<Route path="*" element={<NotFound />} />
</Routes>
</Router>
</AuthProvider>
</>
);
}
Expand Down
64 changes: 64 additions & 0 deletions frontend/src/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
const API_BASE = 'http://localhost:8000/api/v1';

const apiCall = async (url, options = {}) => {
const headers = {
'Content-Type': 'application/json',
...options.headers,
};

const accessToken = localStorage.getItem('accessToken');
if (accessToken) {
headers.Authorization = `Bearer ${accessToken}`;
}

const response = await fetch(`${API_BASE}${url}`, {
...options,
headers,
});

if (response.status === 401) {
const refreshToken = localStorage.getItem('refreshToken');
if (refreshToken) {
try {
const refreshResponse = await fetch(`${API_BASE}/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh_token: refreshToken }),
});

if (refreshResponse.ok) {
const data = await refreshResponse.json();
const newAccessToken = data.data.access_token;
localStorage.setItem('accessToken', newAccessToken);

// Retry the original request once with new token
const retryHeaders = { ...headers, Authorization: `Bearer ${newAccessToken}` };
const retryResponse = await fetch(`${API_BASE}${url}`, {
...options,
headers: retryHeaders,
});
return retryResponse;
}
} catch (error) {
console.error('Refresh failed:', error);
}
}

// Refresh failed or no refresh token, logout
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
window.location.href = '/auth/login';
throw new Error('Unauthorized');
}

return response;
};

const api = {
get: (url) => apiCall(url, { method: 'GET' }),
post: (url, data) => apiCall(url, { method: 'POST', body: JSON.stringify(data) }),
patch: (url, data) => apiCall(url, { method: 'PATCH', body: JSON.stringify(data) }),
delete: (url) => apiCall(url, { method: 'DELETE' }),
};

export default api;
1 change: 0 additions & 1 deletion frontend/src/components/LanguagePicker.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React from 'react';
import i18n from '../i18n';

const LANGS = [
{ code: 'en', label: 'English' },
Expand Down
55 changes: 55 additions & 0 deletions frontend/src/contexts/AuthContext.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import React, { createContext, useContext, useState, useEffect } from 'react';
import api from '../api';

const AuthContext = createContext();

// eslint-disable-next-line react-refresh/only-export-components
export const useAuth = () => useContext(AuthContext);

export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
const token = localStorage.getItem('accessToken');
if (token) {
// Optionally verify token or fetch user profile
// For now, assume valid and set dummy user
setUser({}); // TODO: fetch user data
}
setLoading(false);
}, []);

const login = async (username, password) => {
try {
const response = await api.post('/auth/login', { username, password });
if (response.ok) {
const data = await response.json();
localStorage.setItem('accessToken', data.data.tokens.access_token);
localStorage.setItem('refreshToken', data.data.tokens.refresh_token);
setUser(data.data.user);
return true;
} else {
const errorData = await response.json();
console.error('Login failed:', errorData);
return false;
}
} catch (error) {
console.error('Login error:', error);
return false;
}
};

const logout = () => {
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
setUser(null);
window.location.href = '/auth/login';
};

return (
<AuthContext.Provider value={{ user, login, logout, loading }}>
{children}
</AuthContext.Provider>
);
};
4 changes: 0 additions & 4 deletions frontend/src/pages/NotFound.jsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import React from 'react';

import { useTranslation } from 'react-i18next';

import { Link } from 'react-router-dom';
import PageShell from '../components/PageShell';

const NotFound = () => {

const { t } = useTranslation(['common']);

return (
<PageShell title="Page Not Found">
<div className="text-center">
Expand Down
26 changes: 19 additions & 7 deletions frontend/src/pages/auth/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,44 @@
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import PageShell from '../../components/PageShell';
import { useAuth } from '../../contexts/AuthContext';

const Login = () => {
const { t } = useTranslation(['auth', 'common']);
const [form, setForm] = useState({ name: '', password: '' });
const { login } = useAuth();
const [form, setForm] = useState({ username: '', password: '' });
const [error, setError] = useState('');

const onChange = (e) => setForm({ ...form, [e.target.name]: e.target.value });

const onSubmit = (e) => {
const onSubmit = async (e) => {
e.preventDefault();
// TODO: call your login API here
setError('');
const success = await login(form.username, form.password);
if (success) {
window.location.href = '/dashboard';
} else {
setError('Invalid credentials');
}
};

return (
<PageShell title="auth:login">
<div className="max-w-md mx-auto">
<div className="bg-white p-8 rounded-lg shadow-md">
{error && <div className="text-red-500 mb-4">{error}</div>}
<form className="space-y-6" onSubmit={onSubmit}>
<div>
<label className="block text-sm font-medium mb-1">
{t('auth:name')}
{t('auth:username')}
</label>
<input
className="w-full border rounded px-3 py-2"
name="name"
value={form.name}
name="username"
value={form.username}
onChange={onChange}
placeholder={t('auth:name')}
placeholder={t('auth:username')}
required
/>
</div>

Expand All @@ -43,6 +54,7 @@ const Login = () => {
value={form.password}
onChange={onChange}
placeholder={t('auth:password')}
required
/>
</div>

Expand Down