forked from Apollo-Level2-Web-Dev/nextjs-custom-auth-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
110 lines (92 loc) · 2.69 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const bcrypt = require("bcrypt");
const { MongoClient } = require("mongodb");
const jwt = require("jsonwebtoken");
const app = express();
const port = process.env.PORT || 5000;
// Middleware
app.use(cors());
app.use(express.json());
// MongoDB Connection URL
const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function run() {
try {
// Connect to MongoDB
await client.connect();
console.log("Connected to MongoDB");
const db = client.db("authentication");
const collection = db.collection("users");
// User Registration
app.post("/api/v1/register", async (req, res) => {
const { username, email, password } = req.body;
// Check if email already exists
const existingUser = await collection.findOne({ email });
if (existingUser) {
return res.status(400).json({
success: false,
message: "User already exist!!!",
});
}
// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);
// Insert user into the database
await collection.insertOne({
username,
email,
password: hashedPassword,
role: "user",
});
res.status(201).json({
success: true,
message: "User registered successfully!",
});
});
// User Login
app.post("/api/v1/login", async (req, res) => {
const { email, password } = req.body;
// Find user by email
const user = await collection.findOne({ email });
if (!user) {
return res.status(401).json({ message: "Invalid email or password" });
}
// Compare hashed password
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).json({ message: "Invalid email or password" });
}
// Generate JWT token
const token = jwt.sign(
{ id: user._id, name: user.username, email: user.email, role: user.role },
process.env.JWT_SECRET,
{
expiresIn: process.env.EXPIRES_IN,
}
);
res.json({
success: true,
message: "User successfully logged in!",
accessToken: token,
});
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
} finally {
}
}
run().catch(console.dir);
// Test route
app.get("/", (req, res) => {
const serverStatus = {
message: "Server is running smoothly",
timestamp: new Date(),
};
res.json(serverStatus);
});