0% found this document useful (0 votes)
5 views10 pages

Ehs 7

The document outlines a web application consisting of a backend built with Express and MySQL for user authentication and registration, along with frontend components for login, registration, and a homepage. The backend handles user login and registration requests, while the frontend provides forms for user input and feedback submission. The application runs on localhost at port 8080 and includes error handling and password visibility toggling features.

Uploaded by

rajjm397
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views10 pages

Ehs 7

The document outlines a web application consisting of a backend built with Express and MySQL for user authentication and registration, along with frontend components for login, registration, and a homepage. The backend handles user login and registration requests, while the frontend provides forms for user input and feedback submission. The application runs on localhost at port 8080 and includes error handling and password visibility toggling features.

Uploaded by

rajjm397
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Experiment No.

➢ Program Code:

i) Backend:
const express = require('express'); const
app = express(); const mysql =
require('mysql'); const cors =
require('cors') const { createHash } =
require("crypto");
const bodyParser = require("body-parser");

app.use(express.json()) app.use(cors())
app.use(express.urlencoded({ extended: true })); app.use(bodyParser.json());

const conn = mysql.createConnection({


host:"localhost",
user:"root",
password:'1234',
database:"CSS"
});

conn.connect((err) => { if(err){throw err;} console.log("Connection Established");});

function makeHash(str) {
return str;
}

function generateSQL(username, pass){


return `select * from users where username="${username}" and
password="${pass}";`;
}

function insertSQL(username,pass){
return `insert into users(username,password) value("${username}", "${pass}");`
}
function alreadySQL(username){
return `select count(id) from users where username="${username}";` }

app.get("/", (req,res) => {

res.send({"status":"welcome to CSS"});
});

app.post('/login', (req,res) => {


const {user, pass} = req.body;
console.log(generateSQL(user,pass))
conn.query(generateSQL(user,makeHash(pass)), function(err, result, f){
if(err) console.log(err);
if(result && result.length>0) res.send({ "status":true});
else res.send({"status":false})
}
);
});

app.post('/register', (req,res) => {


const {user, pass} = req.body;

conn.query(insertSQL(user,makeHash(pass)), function(err, result, f){


if(err) console.log(err);

if(result && result.affectedRows>0) res.send({ "status":true});


else res.send({"status":false})
}
);
});

app.listen(8080, () => {
console.log(`Server running at http://localhost:8080`);
});

ii) Login Page:


import { useState } from "react"; import
"./login.css"; import { Link } from
"react-router-dom";
import { useNavigate } from "react-router-dom";

export default function LoginPage() {


const navigate = useNavigate();
const [formData, setFormData] = useState({ user: "", pass: "" });
const [loading, setLoading] = useState(false); const [error,
setError] = useState(null); const [type,setType] = useState(true);
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const reveal = (e) => {
setType(!type);
}
const handleSubmit = async (e) =>
{ e.preventDefault();
setLoading(true); setError(null);

try {
const response = await fetch("http://localhost:8080/login/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(formData),
});

const result = await response.json();


if (!response.ok) throw new Error(result.message || "Login failed");
if(result.status){
alert("Login successful"); // Handle successful login
navigate("/home");
}
else{
alert("Login unsuccessful"); // Handle successful login

}
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};

return (
<div className="login-container">
<div className="login-box">
<h2 className="login-title">Login</h2>
{error && <p className="login-error">{error}</p>}
<form onSubmit={handleSubmit}>
<div className="input-group">
<label htmlFor="user">Username</label>
<input
id="username"
name="user"
type="text"
value={formData.username}
onChange={handleChange}
required
/>
</div>
<div className="input-group">
<label htmlFor="pass">Password</label>
<input id="password"
name="pass"
type={type?"password":"text"}
value={formData.password}
onChange={handleChange}
required
/>

<button style={{"display":"inline-block"}} type="button"


onClick={reveal}>Show Password</button>
</div>
<button type="submit" disabled={loading} className="login-button">
{loading ? "Logging in..." : "Login"}
</button>
</form>
<Link to="/register" className="login-link">Not Registered? Register
Here</Link>

</div>
</div>
);
}

iii) Register Page:


import { useRef, useState } from "react"; import
"./register.css"; import { Link } from "react-
router-dom"; import { useNavigate } from
"react-router-dom";

export default function RegisterPage() {


const navigate = useNavigate();
const [formData, setFormData] = useState({ user: "", pass: "" });
const [loading, setLoading] = useState(false); const [confirm,
setConfirm] = useState(false); const [error, setError] =
useState(null); const password = useRef(); const
confirmPassword = useRef();

const handleChange = (e) => {


setFormData({ ...formData, [e.target.name]: e.target.value });
};

const confirmCheck = (e) => {


if(password.current.value!=confirmPassword.current.value) setConfirm(true);
else setConfirm(false);
}

const handleSubmit = async (e) => {


e.preventDefault(); setLoading(true);
setError(null);
try {
const response = await fetch("http://localhost:8080/register/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(formData),
});

const result = await response.json();


if (!response.ok) throw new Error(result.message || "Register failed");
if(result.status){
alert("Register successful"); // Handle successful login
navigate("/");
}
else{
alert("Register unsuccessful"); // Handle successful login

}
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};

return (
<div className="login-container">
<div className="login-box">
<h2 className="login-title">Register</h2>
{error && <p className="login-error">{error}</p>}
<form onSubmit={handleSubmit}>
<div className="input-group">
<label htmlFor="user">Username</label>
<input
id="username"
name="user"
type="text"
value={formData.username}
onChange={handleChange}
required
/>
</div>
<div className="input-group">
<label htmlFor="pass">Password</label>
<input
id="password" name="pass"
type="password"
value={formData.password}
onChange={handleChange}
ref={password}
required
/>
</div>
<div className="input-group">
<label htmlFor="pass">Confirm Password</label>
<input
id="password"
name="pass_1"
type="password"
value={formData.password}
onChange={confirmCheck}
ref={confirmPassword}
required
/>
</div>
<p className="error">{confirm && "Passwords do not match"}</p>
<button type="submit" disabled={(confirm||loading)}
className="loginbutton">
{loading ? "Registering in..." : "Register"}
</button>
</form>

<Link to="/" className="login-link">Already Registered? Sign in</Link>

</div>
</div>
);
}
iv) HomePage:
import { useRef, useState } from "react"; import
"./home.css";

export default function HomePage() {


const [feed, setFeed] = useState("");
const feedBack = useRef();

const handleSubmit = (e) => {


e.preventDefault();
setFeed(feedBack.current.value);
}
return (
<div className="home-container">
<header className="header">
<h1>Welcome to HomePage</h1>
</header>
<main className="main-content">
<p>This is the homepage.</p>
<div className="feedback">
<form onSubmit={handleSubmit}>
<textarea name="feed" ref={feedBack} />
<button type="submit">Submit Feedback</button>
</form>

{feed && <div className="feed"


dangerouslySetInnerHTML={{__html:`Feedback: ${feed}`}}></div>}
</div>
</main>

</div>
);
}
Output:

You might also like