Skip to content
Open
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
31 changes: 29 additions & 2 deletions middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,41 @@ export const authenticateToken = async (req, res, next) => {
try {
// TODO: Implement the authentication middleware
// 1. Get the token from the request header
const token = req.headers["authorization"]?.split(" ")[1]


// 2. Verify the token
if (!token) {
return res.status(401).json({
success: false,
message: "Access token required"
})
}
// 3. Get the user from the database
const decoded = jwt.verify(
token,
process.env.JWT_SECRET || "secretkey"
)
// 4. If the user doesn't exist, throw an error
const user = await prisma.user.findUnique({
where: { id: decoded.userId},
select: {
id: true,
name: true,
email: true
}
})
if (!user) {
return res.status(401).json({
success: false,
message: "Invalid token - user not found",
});
}
// 5. Attach the user to the request object
req.user = user
// 6. Call the next middleware
next()



} catch (error) {
if (error.name === "JsonWebTokenError") {
return res.status(401).json({
Expand Down
4 changes: 2 additions & 2 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ generator client {

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
url = "postgresql://postgres.rxsshdaugggkxtxpxjsc:0nGTVhlZIGhwmZ1d@aws-1-eu-west-1.pooler.supabase.com:5432/postgres"
}

//url = env("DATABASE_URL")
model User {
id String @id @default(cuid())
email String @unique
Expand Down
94 changes: 93 additions & 1 deletion routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,62 @@ const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key";
router.post("/register", async (req, res) => {
try {
// TODO: Implement the registration logic
const { email, password, name } = req.body

// 1. Validate the input
if (!name || !email || !password) {
return res.status(400).json({
status: 'failed',
message: 'You are missing required field, all fields are required'
})
}

// 2. Check if the user already exists
const existsUser = await prisma.user.findUnique({
where: { email: email}
})

if (existsUser) {
return res.status(400).json({
status: "failed",
"message": "This user already exists in the database"
})
}

// 3. Hash the password
const hashPassword = await bcrypt.hash(password, 10)

// 4. Create the user
const newUser = await prisma.user.create({
data: {
name,
email,
password: hashPassword,


},
select: {
id: true,
name: true,
email: true

}
})

// 5. Generate a JWT token
const token = jwt.sign(
{ userId: newUser.id, email: newUser.email },
process.env.JWT_SECRET || "secretkey",
{ expiresIn: "24h" }
);

// 6. Return the user data and token

res.status(201).json({
status: "success",
message: "User registered successfully",
user: newUser,
token})



} catch (error) {
Expand All @@ -34,11 +83,54 @@ router.post("/register", async (req, res) => {
router.post("/login", async (req, res) => {
try {
// TODO: Implement the login logic
const { email, password} = req.body

// 1. Validate the input
if (!email || !password) {
return res.status(400).json({
status: 'failed',
message: 'You are missing required field, all fields are required'
})
}
// 2. Check if the user exists
const user = await prisma.user.findUnique({
where: { email: email }
})

if (!user) {
return res.status(400).json({
status: "failed",
"message": "This email does not exists in the database"
})
}
// 3. Compare the password
const iscomparePassword = await bcrypt.compare(password, user.password)

if (iscomparePassword == false) {
return res.status(401).json({
success: false,
message: "Invalid email or password"
})
}

// 4. Generate a JWT token
const token = jwt.sign(
{ userId: user.id, email: user.email },
process.env.JWT_SECRET || "secretkey",
{ expiresIn: "24h" }
);

const {password: _, ...userInfo } = user

// 5. Return the user data and token
res.status(201).json({
status: "success",
message: "User logged in successfully",
data: {
user: userInfo,
token
}
})


} catch (error) {
Expand Down