Files
KeyNest/keynest/src/components/AuthModal.js
2025-04-29 00:40:35 +03:00

128 lines
3.2 KiB
JavaScript

import React, { useState } from 'react';
import Modal from 'react-modal';
import { useAuth } from './AuthContext';
Modal.setAppElement('#root');
const AuthModal = ({ isOpen, onRequestClose }) => {
const [isLogin, setIsLogin] = useState(true);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const { login, register } = useAuth();
const [error, setError] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
setError('');
try {
if (isLogin) {
await login({ username, password });
} else {
await register({ username, password });
}
onRequestClose();
} catch (err) {
setError(err.message);
}
};
const toggleAuthMode = () => {
setIsLogin(!isLogin);
setUsername('');
setPassword('');
setError('');
};
const modalStyles = {
overlay: {
backgroundColor: 'rgba(0, 0, 0, 0.5)'
},
content: {
top: '50%',
left: '50%',
right: 'auto',
bottom: 'auto',
marginRight: '-50%',
transform: 'translate(-50%, -50%)',
padding: '20px',
width: '300px',
borderRadius: '8px',
boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
border: 'none'
}
};
const formStyles = {
display: 'flex',
flexDirection: 'column',
gap: '15px'
};
const inputStyles = {
padding: '10px',
borderRadius: '4px',
border: '1px solid #ccc',
fontSize: '16px'
};
const buttonStyles = {
padding: '12px',
borderRadius: '4px',
border: 'none',
backgroundColor: '#242323',
color: 'white',
fontSize: '16px',
cursor: 'pointer',
':hover': {
backgroundColor: '#0056b3'
}
};
const toggleButtonStyles = {
background: 'none',
border: 'none',
color: '#007bff',
cursor: 'pointer',
fontSize: '14px',
textDecoration: 'underline'
};
return (
<Modal
isOpen={isOpen}
onRequestClose={onRequestClose}
style={modalStyles}
>
<h2 style={{ textAlign: 'center', marginBottom: '20px' }}>{isLogin ? 'Login' : 'Register'}</h2>
{error && <p style={{ color: 'red', textAlign: 'center' }}>{error}</p>}
<form onSubmit={handleSubmit} style={formStyles}>
<div>
<label htmlFor="username" style={{ marginBottom: '5px', display: 'block' }}>Username:</label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
style={inputStyles}
/>
</div>
<div>
<label htmlFor="password" style={{ marginBottom: '5px', display: 'block' }}>Password:</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
style={inputStyles}
/>
</div>
<button type="submit" style={buttonStyles}>{isLogin ? 'Log In' : 'Register'}</button>
</form>
<button onClick={toggleAuthMode} style={toggleButtonStyles}>
{isLogin ? 'Need an account? Register' : 'Already have an account? Login'}
</button>
</Modal>
);
};
export default AuthModal;