This commit is contained in:
GokaPek 2024-01-07 19:32:06 +04:00
parent 268f6d269f
commit 493d7579b1
6 changed files with 324 additions and 202 deletions

View File

@ -1,4 +1,27 @@
{ {
"users": [
{
"id": 1,
"name": "Admin1",
"role": "admin",
"email": "Goka.2004@yandex.ru",
"password": "1111"
},
{
"email": "Test@yandex.ru",
"password": "1111",
"name": "Pek",
"role": "user",
"id": 2
},
{
"email": "Goka.2004@yandex.ru",
"password": "1111",
"name": "Admin1",
"role": "user",
"id": 3
}
],
"types": [ "types": [
{ {
"id": 1, "id": 1,

File diff suppressed because it is too large Load Diff

View File

@ -16,6 +16,7 @@
"bootstrap": "^5.3.2", "bootstrap": "^5.3.2",
"fa": "^1.0.1", "fa": "^1.0.1",
"install": "^0.13.0", "install": "^0.13.0",
"json-server-auth": "^2.1.0",
"prop-types": "^15.8.1", "prop-types": "^15.8.1",
"react": "^18.2.0", "react": "^18.2.0",
"react-bootstrap": "^2.9.1", "react-bootstrap": "^2.9.1",

View File

@ -38,3 +38,15 @@ export const ApiClient = axios.create({
}); });
ApiClient.interceptors.response.use(responseHandler, responseErrorHandler); ApiClient.interceptors.response.use(responseHandler, responseErrorHandler);
ApiClient.interceptors.request.use((config) => {
const token = localStorage.getItem('auth_token');
const newConfig = { ...config };
if (token) {
newConfig.headers = {
...newConfig.headers,
Authorization: `Bearer ${token}`,
};
}
return newConfig;
});

View File

@ -1,14 +1,27 @@
import { ApiClient } from './ApiClient'; import ApiService from './ApiService';
class AuthService { class AuthService extends ApiService {
static async login(credentials) { constructor() {
return ApiClient.post('/login', credentials); super('http://localhost:8081/users'); // Указываем базовый URL для аутентификации
} }
// Если у вас есть метод регистрации, то он тоже здесь. async registerUser(userInfo) {
static async register(userInfo) { return this.create(userInfo);
return ApiClient.post('/register', userInfo); }
async loginUser(credentials) {
const users = await this.getAll(); // Получаем всех пользователей
// eslint-disable-next-line max-len
const user = users.find((u) => u.email === credentials.email && u.password === credentials.password && u.name === credentials.name);
if (!user) {
throw new Error('Invalid email or password');
}
return user;
}
async setRole(userId, role) {
return this.update(userId, { role });
} }
} }
export default AuthService; export default new AuthService();

View File

@ -5,57 +5,103 @@ import AuthService from '../../api/AuthService';
import { AuthContext } from '../context/AuthContex.jsx'; import { AuthContext } from '../context/AuthContex.jsx';
const LoginForm = () => { const LoginForm = () => {
const [credentials, setCredentials] = useState({ email: '', password: '' }); const [credentials, setCredentials] = useState({ email: '', password: '', name: '' });
const { dispatch } = useContext(AuthContext); const { state, dispatch } = useContext(AuthContext);
const handleChange = (e) => { const handleChange = (e) => {
const { name, value } = e.target; // Важно использовать name, а не id. const { name, value } = e.target;
setCredentials({ ...credentials, [name]: value }); setCredentials({ ...credentials, [name]: value });
}; };
const handleSubmit = async (e) => { const handleSubmit = async (e) => {
e.preventDefault();
const { user, token } = await AuthService.loginUser(credentials);
localStorage.setItem('auth_token', token); // Сохраняем токен в localStorage
dispatch({
type: 'LOGIN',
payload: { user, token }, // Предполагается, что payload содержит объект с user и token
});
};
const handleRegister = async (e) => {
e.preventDefault(); e.preventDefault();
try { try {
const user = await AuthService.login(credentials); const { user, token } = await AuthService.registerUser({ ...credentials, role: 'user' });
dispatch({ type: 'LOGIN', payload: user }); localStorage.setItem('auth_token', token);
dispatch({
type: 'REGISTER',
payload: { user, token }, // Предполагается, что payload содержит объект с user и token
});
} catch (error) { } catch (error) {
console.error('Login error', error); console.error('Register error', error);
// Обработать ошибки логина // Обработать ошибки регистрации
} }
}; };
const handleLogout = () => {
localStorage.removeItem('auth_token');
dispatch({ type: 'LOGOUT' });
};
return ( return (
<Form className="col-md-6 mx-auto mt-3 pt-5" onSubmit={handleSubmit}> <Form className="col-md-6 mx-auto mt-3 pt-5" onSubmit={handleSubmit}>
<Form.Group controlId="email"> {state.user ? (
<Form.Control <>
name="email" <p>Welcome, {state.user.name}</p>
type="email" {state.user.role === 'admin' && (
placeholder="mail@example.com" <Button variant="primary" as={Link} to='/admin' className="w-50">
className="mb-3" Admin
onChange={handleChange} </Button>
value={credentials.email} )}
required <Button variant="primary" onClick={handleLogout} className="w-50">
/> Logout
</Form.Group>
<Form.Group controlId="password">
<Form.Control
name="password"
type="password"
placeholder="Password"
className="mb-3"
onChange={handleChange}
value={credentials.password}
required
/>
</Form.Group>
<div className="text-center">
<Button variant="primary" type="submit" className="w-50">
Login
</Button> </Button>
<Button variant="primary" as={Link} to='/admin' className="w-50"> </>
Admin ) : (
</Button> <>
</div> <Form.Group controlId="name">
<Form.Control
name="name"
type="text"
placeholder="Name"
className="mb-3"
onChange={handleChange}
value={credentials.name}
required
/>
</Form.Group>
<Form.Group controlId="email">
<Form.Control
name="email"
type="email"
placeholder="mail@example.com"
className="mb-3"
onChange={handleChange}
value={credentials.email}
required
/>
</Form.Group>
<Form.Group controlId="password">
<Form.Control
name="password"
type="password"
placeholder="Password"
className="mb-3"
onChange={handleChange}
value={credentials.password}
required
/>
</Form.Group>
<div className="text-center">
<Button variant="primary" type="submit" className="w-50">
Login
</Button>
<Button variant="primary" onClick={handleRegister} className="w-50">
Register
</Button>
</div>
</>
)}
</Form> </Form>
); );
}; };