Skip to content

user auth test #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions sigup-login-auth/backend/models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
name: String,
email: {type: String, unique:true},
password: String
});

module.exports = mongoose.model('User', userSchema);
45 changes: 45 additions & 0 deletions sigup-login-auth/backend/routes/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const express = require('express');
const router = express.Router();
const User = require('../models/User');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const JWT_SECRET = process.env.JWT_SECRET;

// Signup
router.post('/signup', async (req, res) => {
const { name, email, password } = req.body;
const hash = await bcrypt.hash(password, 10);
try {
await User.create({ name, email, password: hash });
res.redirect("http://localhost:5500/frontend/login.html");
} catch (err) {
res.status(400).send("Email already exists");
}
});

// Login
router.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) return res.status(400).send("User not found");

const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).send("Invalid password");

const token = jwt.sign({ id: user._id }, JWT_SECRET, { expiresIn: "1h" });
res.json({ token });
});

// Protected route (optional)
router.get('/me', async (req, res) => {
const token = req.headers.authorization?.split(" ")[1];
try {
const decoded = jwt.verify(token, JWT_SECRET);
const user = await User.findById(decoded.id).select("-password");
res.json(user);
} catch {
res.status(401).send("Unauthorized");
}
});

module.exports = router;
21 changes: 21 additions & 0 deletions sigup-login-auth/backend/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const dotenv = require('dotenv');
const authRoutes = require('./routes/auth');

dotenv.config();
const app = express();

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

mongoose.connect(process.env.MONGO_URI)
.then(()=> console.log("Connected to MongoDB..."))
.catch(err => console.log(err));


app.use('/', authRoutes);

app.listen(5000, () => console.log('Server running on http://localhost:5000'));
19 changes: 19 additions & 0 deletions sigup-login-auth/frontend/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SignUp Page</title>
<link rel="stylesheet" href="/frontend/style.css">
</head>
<body>
<h2>SignUp</h2>
<form action="http://localhost:5000/signup" method="POST">
<input type="text" name="name" placeholder="Name" required><br>
<input type="email" name="email" placeholder="Email" required><br>
<input type="password" name="password" placeholder="Password" required><br>
<button type="submit">SignUp</button>
</form>
<p>Already have an account? <a href="/frontend/login.html">Login Here</a></p>
</body>
</html>
17 changes: 17 additions & 0 deletions sigup-login-auth/frontend/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
<link rel="stylesheet" href="/frontend/style.css">
</head>
<body>
<h2>Login</h2>
<form action="httpS://localhost:5000/login" method="POST">
<input type="email" name="email" placeholder="Email" required><br>
<input type="password" name="password" placeholder="Password" required><br>
<button type="submit">Login</button>
</form>
</body>
</html>
26 changes: 26 additions & 0 deletions sigup-login-auth/frontend/profile.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Profile</title>
<link rel="stylesheet" href="/frontend/style.css">
</head>
<body>
<h2>Your Profile</h2>
<div id="profile"></div>

<script>
fetch("http://localhost:5000/profile", {
method: "GET",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
})
.then(res => res.json())
.then(data => {
document.getElementById("profile").innerHTML = `<p>Name: ${data.name}</p><br><p>Email: ${data.email}</p><br>`;
})
</script>
</body>
</html>
10 changes: 10 additions & 0 deletions sigup-login-auth/frontend/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
body{
font-family: Arial;
text-align: center;
margin-top: 50px;
}
input, button{
padding: 10px;
margin: 5px;
width: 200px;
}