5_8
This commit is contained in:
parent
268f6d269f
commit
493d7579b1
@ -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": [
|
||||
{
|
||||
"id": 1,
|
||||
|
343
Lab5/Bookfill/package-lock.json
generated
343
Lab5/Bookfill/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -16,6 +16,7 @@
|
||||
"bootstrap": "^5.3.2",
|
||||
"fa": "^1.0.1",
|
||||
"install": "^0.13.0",
|
||||
"json-server-auth": "^2.1.0",
|
||||
"prop-types": "^15.8.1",
|
||||
"react": "^18.2.0",
|
||||
"react-bootstrap": "^2.9.1",
|
||||
|
@ -38,3 +38,15 @@ export const ApiClient = axios.create({
|
||||
});
|
||||
|
||||
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;
|
||||
});
|
||||
|
@ -1,14 +1,27 @@
|
||||
import { ApiClient } from './ApiClient';
|
||||
import ApiService from './ApiService';
|
||||
|
||||
class AuthService {
|
||||
static async login(credentials) {
|
||||
return ApiClient.post('/login', credentials);
|
||||
class AuthService extends ApiService {
|
||||
constructor() {
|
||||
super('http://localhost:8081/users'); // Указываем базовый URL для аутентификации
|
||||
}
|
||||
|
||||
// Если у вас есть метод регистрации, то он тоже здесь.
|
||||
static async register(userInfo) {
|
||||
return ApiClient.post('/register', userInfo);
|
||||
async registerUser(userInfo) {
|
||||
return this.create(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();
|
||||
|
@ -5,57 +5,103 @@ import AuthService from '../../api/AuthService';
|
||||
import { AuthContext } from '../context/AuthContex.jsx';
|
||||
|
||||
const LoginForm = () => {
|
||||
const [credentials, setCredentials] = useState({ email: '', password: '' });
|
||||
const { dispatch } = useContext(AuthContext);
|
||||
const [credentials, setCredentials] = useState({ email: '', password: '', name: '' });
|
||||
const { state, dispatch } = useContext(AuthContext);
|
||||
|
||||
const handleChange = (e) => {
|
||||
const { name, value } = e.target; // Важно использовать name, а не id.
|
||||
const { name, value } = e.target;
|
||||
setCredentials({ ...credentials, [name]: value });
|
||||
};
|
||||
|
||||
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();
|
||||
try {
|
||||
const user = await AuthService.login(credentials);
|
||||
dispatch({ type: 'LOGIN', payload: user });
|
||||
const { user, token } = await AuthService.registerUser({ ...credentials, role: 'user' });
|
||||
localStorage.setItem('auth_token', token);
|
||||
dispatch({
|
||||
type: 'REGISTER',
|
||||
payload: { user, token }, // Предполагается, что payload содержит объект с user и token
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Login error', error);
|
||||
// Обработать ошибки логина
|
||||
console.error('Register error', error);
|
||||
// Обработать ошибки регистрации
|
||||
}
|
||||
};
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('auth_token');
|
||||
dispatch({ type: 'LOGOUT' });
|
||||
};
|
||||
|
||||
return (
|
||||
<Form className="col-md-6 mx-auto mt-3 pt-5" onSubmit={handleSubmit}>
|
||||
<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
|
||||
{state.user ? (
|
||||
<>
|
||||
<p>Welcome, {state.user.name}</p>
|
||||
{state.user.role === 'admin' && (
|
||||
<Button variant="primary" as={Link} to='/admin' className="w-50">
|
||||
Admin
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="primary" onClick={handleLogout} className="w-50">
|
||||
Logout
|
||||
</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>
|
||||
);
|
||||
};
|
||||
|
Loading…
Reference in New Issue
Block a user