Last active
April 30, 2024 03:58
-
-
Save QuocCao-dev/31fbe2b699473270a0bbd2353b226dd1 to your computer and use it in GitHub Desktop.
authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express from "express"; | |
import { PrismaClient } from "@prisma/client"; | |
import { hash, compare } from "bcrypt"; | |
import jwt from "jsonwebtoken"; | |
const prisma = new PrismaClient(); | |
const app = express(); | |
app.use(express.json()); | |
app.use(express.urlencoded({ extended: true })); | |
app.post("/register", async (req, res) => { | |
const { name, email, password } = req.body; | |
const user = await prisma.user.findFirst({ where: { email } }); | |
if (user) { | |
throw new Error("Email đã tồn tại"); | |
} | |
const hashed = await hash(password, 10); | |
const newUser = await prisma.user.create({ | |
data: { | |
name, | |
email, | |
password: hashed, | |
}, | |
}); | |
res.json(newUser); | |
}); | |
app.post("/login", async (req, res) => { | |
const { email, password } = req.body; | |
const user = await prisma.user.findFirst({ where: { email } }); | |
if (!user) { | |
throw new Error("Email không tồn tại"); | |
} | |
const isPasswordValid = await compare(password, user.password); | |
if (!isPasswordValid) { | |
throw new Error("Mật khẩu không đúng"); | |
} | |
const jwtToken = jwt.sign( | |
{ | |
id: user.id, | |
}, | |
"secret-key", | |
{ | |
expiresIn: "1d", | |
} | |
); | |
res.json({ | |
jwt: jwtToken, // need to use real jwt token | |
}); | |
}); | |
app.get("/get-me", async (req, res) => { | |
const token = req.headers.authorization; | |
const jwtResponse = jwt.verify(token, "secret-key"); | |
const userId = jwtResponse.id; | |
const exp = jwtResponse.exp; | |
const currentDate = new Date().getTime() / 1000; | |
if (currentDate > exp) { | |
throw new Error("Token hết hạn"); | |
} | |
const user = await prisma.user.findFirst({ | |
where: { | |
id: parseInt(userId), | |
}, | |
}); | |
if (!user) { | |
throw new Error("User không tồn tại"); | |
} | |
res.json(user); | |
// res.json({}); | |
}); | |
app.listen(3000, () => { | |
console.log("Server is running on port 3000"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment