1 Commits
Author SHA1 Message Date
phoenixandphoenix ef4952b8cb tsk-2: Login (#4)
Closes #2

Reviewed-on: phoenix/textsender#4
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-12-13 22:39:44 +00:00
6 changed files with 321 additions and 7 deletions
+2
View File
@@ -5,6 +5,7 @@ import {
Navigate,
} from 'react-router-dom';
import Register from './components/Register';
import Login from './components/Login';
import './App.css';
function App() {
@@ -13,6 +14,7 @@ function App() {
<Routes>
<Route path="/" element={<Navigate to="/register" replace />} />
<Route path="/register" element={<Register />} />
<Route path="/login" element={<Login />} />
{/* Add other routes as needed */}
<Route
path="/login"
+150
View File
@@ -0,0 +1,150 @@
.login-container {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
}
.login-card {
background: white;
border-radius: 12px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
padding: 40px;
width: 100%;
max-width: 420px;
}
.login-title {
color: #333;
font-size: 28px;
font-weight: 600;
text-align: center;
margin-bottom: 30px;
}
.login-form {
margin-bottom: 25px;
}
.form-group {
margin-bottom: 20px;
}
.form-label {
display: block;
color: #555;
font-size: 14px;
font-weight: 500;
margin-bottom: 6px;
}
.form-input {
width: 100%;
padding: 12px 16px;
border: 2px solid #e1e5e9;
border-radius: 8px;
font-size: 16px;
transition: all 0.3s ease;
box-sizing: border-box;
}
.form-input:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-input.error {
border-color: #ef4444;
}
.form-input:disabled {
background-color: #f9fafb;
cursor: not-allowed;
}
.error-message {
color: #ef4444;
font-size: 13px;
margin-top: 5px;
display: block;
}
.submit-error {
background-color: #fee;
border: 1px solid #fcc;
border-radius: 6px;
padding: 12px;
margin-bottom: 20px;
text-align: center;
}
.form-hint {
display: block;
color: #6b7280;
font-size: 12px;
margin-top: 4px;
}
.submit-btn {
width: 100%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 8px;
padding: 14px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
margin-top: 10px;
}
.submit-btn:hover:not(:disabled) {
transform: translateY(-1px);
box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
}
.submit-btn:active:not(:disabled) {
transform: translateY(0);
}
.submit-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.register-link {
text-align: center;
margin: 20px 0;
padding-top: 20px;
border-top: 1px solid #e5e7eb;
}
.register-link p {
color: #6b7280;
margin: 0;
}
.link {
color: #667eea;
text-decoration: none;
font-weight: 500;
}
.link:hover {
text-decoration: underline;
}
/* Responsive adjustments */
@media (max-width: 480px) {
.login-card {
padding: 30px 20px;
}
.login-title {
font-size: 24px;
}
}
+161
View File
@@ -0,0 +1,161 @@
import { useState } from 'react';
import './Login.css';
import { AUTH_API_BASE_URL } from '../constants/api';
import { DATA_KEY_ACCESS_TOKEN } from '../constants/app';
// function Login() {
const Login = () => {
const [formData, setFormData] = useState({
username: '',
password: '',
});
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const [submitError, setSubmitError] = useState('');
const handleChange = (e) => {
const { name, value } = e.target;
setFormData((prev) => ({
...prev,
[name]: value,
}));
// Clear error for this field when user starts typing
if (errors[name]) {
setErrors((prev) => ({
...prev,
[name]: '',
}));
}
};
const validateForm = () => {
const newErrors = {};
if (!formData.username.trim()) {
newErrors.username = 'Username is required';
}
if (!formData.password) {
newErrors.password = 'Password is required';
} else if (formData.password.length < 6) {
newErrors.password = 'Password must be at least 6 characters';
}
return newErrors;
};
const handleSubmit = async (e) => {
e.preventDefault();
setSubmitError('');
const formErrors = validateForm();
if (Object.keys(formErrors).length > 0) {
setErrors(formErrors);
return;
}
setIsSubmitting(true);
try {
// Simulate API call
await new Promise((resolve) => setTimeout(resolve, 1000));
const reqBod = {
username: formData.username,
password: formData.password,
};
const reponse = await fetch(`${AUTH_API_BASE_URL}/api/v1/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(reqBod),
});
if (reponse.ok) {
const response = await reponse.json();
console.log(`Result: ${response.message}`);
const loginResult = response.data[0];
const token = loginResult.access_token;
console.log(token);
localStorage.setItem(DATA_KEY_ACCESS_TOKEN, token);
alert(`Login successful! Welcome, ${formData.username}`);
} else {
console.error('Error logging in');
}
// Reset form
setFormData({ username: '', password: '' });
setErrors({});
} catch (error) {
setSubmitError('Login failed. Please try again.');
console.error('Login error:', error);
} finally {
setIsSubmitting(false);
}
};
return (
<div className="login-container">
<div className="login-card">
<h1 className="login-title">Login</h1>
{submitError && <div className="submit-error">{submitError}</div>}
<form className="login-form" onSubmit={handleSubmit} noValidate>
<div className="form-group">
<label htmlFor="username" className="form-label">
Username
</label>
<input
type="text"
id="username"
name="username"
value={formData.username}
onChange={handleChange}
className={`form-input ${errors.username ? 'error' : ''}`}
placeholder="Enter your username"
disabled={isSubmitting}
/>
{errors.username && (
<span className="error-message">{errors.username}</span>
)}
</div>
<div className="form-group">
<label htmlFor="password" className="form-label">
Password
</label>
<input
type="password"
id="password"
name="password"
value={formData.password}
onChange={handleChange}
className={`form-input ${errors.password ? 'error' : ''}`}
placeholder="Enter your password"
disabled={isSubmitting}
/>
{errors.password && (
<span className="error-message">{errors.password}</span>
)}
<span className="form-hint">Must be at least 6 characters</span>
</div>
<button type="submit" className="submit-btn" disabled={isSubmitting}>
{isSubmitting ? 'Logging in...' : 'Login'}
</button>
</form>
<div className="register-link">
<p>
Don't have an account?{' '}
<a href="register" className="link">
Register here
</a>
</p>
</div>
</div>
</div>
);
};
export default Login;
+5 -7
View File
@@ -1,6 +1,8 @@
import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import './Register.css';
import { AUTH_API_BASE_URL } from '../constants/api';
import { DATA_KEY_REGISTERED_USER_ID } from '../constants/app';
const Register = () => {
const navigate = useNavigate();
@@ -80,18 +82,13 @@ const Register = () => {
// Prepare data for API call (remove confirmPassword)
const { confirmPassword, ...userData } = formData;
// Simulate API call
console.log('Submitting registration data:', userData);
// Mock API call delay
await new Promise((resolve) => setTimeout(resolve, 1500));
const reqBod = {
phone_number: userData.phoneNumber,
username: userData.username,
password: userData.password,
};
const response = await fetch('http://localhost:9080/api/v1/register', {
const response = await fetch(`${AUTH_API_BASE_URL}/api/v1/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(reqBod),
@@ -100,7 +97,8 @@ const Register = () => {
if (response.ok) {
alert('Registration successful! Redirecting to login...');
const res = await response.json();
console.log(res.message);
console.log(`Result: ${res.message}`);
localStorage.setItem(DATA_KEY_REGISTERED_USER_ID, res.data[0].id);
navigate('/login');
} else {
console.error('Error registering');
+1
View File
@@ -0,0 +1 @@
export const AUTH_API_BASE_URL = 'http://localhost:9080';
+2
View File
@@ -0,0 +1,2 @@
export const DATA_KEY_ACCESS_TOKEN = 'access_token';
export const DATA_KEY_REGISTERED_USER_ID = 'registered_user_id';