Files
stock-scanner/src/components/Login.js
2026-08-05 22:00:49 +05:30

71 lines
2.7 KiB
JavaScript

import React, { useState } from "react";
import axios from "axios";
import { useNavigate, Link } from "react-router-dom";
import forge from "node-forge";
function Login() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const handleLogin = async (e) => {
e.preventDefault();
setLoading(true);
setError("");
try {
const resKey = await axios.get("http://127.0.0.1:8000/api/auth/public-key");
const publicKeyPem = resKey.data.public_key;
const publicKey = forge.pki.publicKeyFromPem(publicKeyPem);
const encrypted = publicKey.encrypt(password, 'RSA-OAEP');
const encryptedBase64 = forge.util.encode64(encrypted);
const res = await axios.post("http://127.0.0.1:8000/api/auth/login", {
username,
password: encryptedBase64
});
localStorage.setItem("token", res.data.access_token);
navigate("/");
} catch (err) {
setError(err.response?.data?.detail || "Login failed");
} finally {
setLoading(false);
}
};
return (
<div className="app-container" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<div className="glass-card" style={{ width: '400px', textAlign: 'center' }}>
<h2 className="text-blue">📈 Login</h2>
<form onSubmit={handleLogin} style={{ display: 'flex', flexDirection: 'column', gap: '15px' }}>
<input
type="text"
placeholder="Username"
value={username}
onChange={e => setUsername(e.target.value)}
style={{ padding: '10px', borderRadius: '5px', border: '1px solid var(--border-color)', background: 'var(--bg-tertiary)', color: 'white' }}
required
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={e => setPassword(e.target.value)}
style={{ padding: '10px', borderRadius: '5px', border: '1px solid var(--border-color)', background: 'var(--bg-tertiary)', color: 'white' }}
required
/>
{error && <p className="text-red">{error}</p>}
<button type="submit" className="nav-btn active" style={{ justifyContent: 'center' }} disabled={loading}>
{loading ? "Logging in..." : "Login"}
</button>
</form>
<p style={{ marginTop: '20px' }}>Don't have an account? <Link to="/signup" className="text-blue">Sign up</Link></p>
</div>
</div>
);
}
export default Login;