Skip to content

Commit

Permalink
Merge pull request #1411 from Ansh101112/main
Browse files Browse the repository at this point in the history
Backend API for athentication
  • Loading branch information
arghadipmanna101 authored Jul 18, 2024
2 parents 6c09b51 + 5ab535e commit 315da0e
Show file tree
Hide file tree
Showing 9 changed files with 288 additions and 10 deletions.
70 changes: 70 additions & 0 deletions dashboard/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
height: 100vh;
background-color: #f4f4f4;
}

.container {
display: flex;
width: 100%;
}

.sidebar {
width: 250px;
background-color: #2874f0;
color: white;
padding: 15px;
box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
}

.sidebar h2 {
margin-top: 0;
}

.sidebar ul {
list-style: none;
padding: 0;
}

.sidebar ul li {
margin: 15px 0;
}

.sidebar ul li a {
color: white;
text-decoration: none;
display: block;
}

.sidebar ul li a:hover {
text-decoration: underline;
}

.main-content {
flex: 1;
padding: 20px;
background-color: white;
}

header {
border-bottom: 1px solid #ddd;
padding-bottom: 10px;
margin-bottom: 20px;
}

.orders {
display: flex;
flex-wrap: wrap;
}

.order {
background-color: #f9f9f9;
border: 1px solid #ddd;
padding: 10px;
margin: 10px;
flex: 1 0 30%;
box-sizing: border-box;
}
38 changes: 38 additions & 0 deletions dashboard/userdashboard.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Dashboard</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<div class="sidebar">
<h2>Dashboard</h2>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Profile</a></li>
<li><a href="#">Orders</a></li>
<li><a href="#">Wishlist</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Logout</a></li>
</ul>
</div>
<div class="main-content">
<header>
<h1>Welcome, User</h1>
</header>
<div class="content">
<h2>Recent Orders</h2>
<div class="orders">
<div class="order">Order 1</div>
<div class="order">Order 2</div>
<div class="order">Order 3</div>
</div>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
33 changes: 30 additions & 3 deletions login/login.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@
</head>
<body>
<div class="wrapper">
<form action="">
<form id="login-form">
<h1>Login</h1>
<div class="input-box">
<input type="text" placeholder="Username" required>
<input type="text" id="email" placeholder="Email" required>
<i class='bx bxs-user'></i>
</div>
<div class="input-box">
<input type="password" placeholder="Password" required>
<input type="password" id="password" placeholder="Password" required>
<i class='bx bxs-lock-alt'></i>
</div>
<div class="remember-forgot">
Expand All @@ -34,5 +34,32 @@ <h1>Login</h1>
</div>
</form>
</div>

<script>
document.getElementById('login-form').addEventListener('submit', async function(e) {
e.preventDefault();

const email = document.getElementById('email').value;
const password = document.getElementById('password').value;

const response = await fetch('http://localhost:5000/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username: email, password: password })
});

const data = await response.json();

if (response.ok) {
// Save the token to localStorage or sessionStorage
localStorage.setItem('token', data.token);
window.location.href = 'https://flipkart-clone-seven-azure.vercel.app/';
} else {
alert(data.msg || 'Login failed');
}
});
</script>
</body>
</html>
2 changes: 2 additions & 0 deletions server_backend/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
MONGOURI = mongodb+srv://tanshuman145:Ansh%4012a1@cluster0.a87t2mr.mongodb.net/ecommerce
JWTSECRET = uyteuweuuihu$677773hjkj
20 changes: 20 additions & 0 deletions server_backend/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const mongoose = require('mongoose');
const dotenv = require('dotenv');

dotenv.config();

const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGOURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('MongoDB Connected...');
} catch (err) {
console.error(err.message);
// Exit process with failure
process.exit(1);
}
};

module.exports = connectDB;
32 changes: 25 additions & 7 deletions server_backend/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,29 @@
const express = require('express');
const connectDB = require('./db');
const authRoutes = require('./routes/auth');
const dotenv = require('dotenv');
const cors = require('cors');

dotenv.config();

const app = express();
const port = 3000;

app.get('/', (req, res) => {
res.send('<h1>Server started</h1>');
});
// cors added
app.use(cors());

// Connect Database
connectDB();

// Init Middleware
app.use(express.json({ extended: false }));

// Define Routes
app.use('/api', authRoutes);

app.get('/',()=>{
'<h1>Server Started</h1>'
})

const PORT = process.env.PORT || 5000;

app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
app.listen(PORT, () => console.log(`Server started on port http://localhost:${PORT}`));
8 changes: 8 additions & 0 deletions server_backend/models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const mongoose = require('mongoose');

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

module.exports = mongoose.model('User', UserSchema);
5 changes: 5 additions & 0 deletions server_backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,14 @@
"license": "ISC",
"description": "",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"jsonwebtoken": "^9.0.2",
"mongodb": "^6.8.0",
"mongoose": "^8.5.1",
"nodemon": "^3.1.4"
}
}
90 changes: 90 additions & 0 deletions server_backend/routes/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const dotenv = require('dotenv');

dotenv.config();

// Register route
router.post('/register', async (req, res) => {
const { email, password } = req.body;

try {
let user = await User.findOne({ email });

if (user) {
return res.status(400).json({ msg: 'email already exists' });
}

user = new User({
email,
password,
});

const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);

await user.save();

const payload = {
user: {
id: user.id,
},
};

jwt.sign(
payload,
process.env.JWTSECRET,
{ expiresIn: 3600 }, // Token expires in 1 hour
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});

// Login route
router.post('/login', async (req, res) => {
const { email, password } = req.body;

try {
let user = await User.findOne({ email });

if (!user) {
return res.status(400).json({ msg: 'Invalid Credentials' });
}

const isMatch = await bcrypt.compare(password, user.password);

if (!isMatch) {
return res.status(400).json({ msg: 'Invalid Credentials' });
}

const payload = {
user: {
id: user.id,
},
};

jwt.sign(
payload,
process.env.JWTSECRET,
{ expiresIn: 3600 },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});

module.exports = router;

0 comments on commit 315da0e

Please sign in to comment.