-
Notifications
You must be signed in to change notification settings - Fork 119
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #24 from tarunkumar2005/main
Created Signup, login, logout, and verifyToken Routes in Backend
- Loading branch information
Showing
10 changed files
with
1,379 additions
and
7 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,2 @@ | ||
node_modules/ | ||
node_modules | ||
.env |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import dotenv from 'dotenv'; | ||
|
||
dotenv.config(); | ||
|
||
const config = { | ||
port: process.env.PORT || 3000, | ||
mongodbUri: process.env.MONGODB_URI, | ||
jwtSecret: process.env.JWT_SECRET, | ||
}; | ||
|
||
export default config; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import mongoose from 'mongoose'; | ||
import config from './config.js'; | ||
|
||
const connectDB = async () => { | ||
try { | ||
await mongoose.connect(config.mongodbUri); | ||
console.log('MongoDB connected successfully'); | ||
} catch (error) { | ||
console.error('MongoDB connection failed:', error.message); | ||
process.exit(1); | ||
} | ||
}; | ||
|
||
export default connectDB; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
import User from '../models/User.js'; | ||
import { hashPassword, comparePassword, generateToken, verifyToken, addCookie, getCookies, removeCookie } from '../utils/authFunctions.js'; | ||
|
||
export const registerUser = async (req, res) => { | ||
try { | ||
const { name, email, phoneNumber, password } = req.body; | ||
|
||
if (!name) { | ||
return res.status(400).json({ error: 'Name is required' }); | ||
} else if (!email) { | ||
return res.status(400).json({ error: 'Email is required' }); | ||
} else if (!phoneNumber) { | ||
return res.status(400).json({ error: 'Phone number is required' }); | ||
} else if (!password) { | ||
return res.status(400).json({ error: 'Password is required' }); | ||
} | ||
|
||
const user = await User.findOne({ email }); | ||
|
||
if (user) { | ||
return res.status(400).json({ error: 'User already exists' }); | ||
} | ||
|
||
const hashedPassword = await hashPassword(password); | ||
|
||
const newUser = new User({ | ||
name, | ||
email, | ||
phoneNumber, | ||
password: hashedPassword | ||
}); | ||
|
||
await newUser.save(); | ||
|
||
const token = await generateToken(newUser._id); | ||
|
||
addCookie(res, 'token', token); | ||
|
||
res.status(201).json({ message: 'User registered successfully', userId: newUser._id }); | ||
} catch (error) { | ||
res.status(500).json({ error: error | 'Internal Server Error' }); | ||
} | ||
}; | ||
|
||
export const loginUser = async (req, res) => { | ||
try { | ||
const { email, password } = req.body; | ||
|
||
if (!email) { | ||
return res.status(400).json({ error: 'Email is required' }); | ||
} else if (!password) { | ||
return res.status(400).json({ error: 'Password is required' }); | ||
} | ||
|
||
const user = await User.findOne({ email }); | ||
|
||
if (!user) { | ||
return res.status(400).json({ error: 'User does not exist' }); | ||
} | ||
|
||
const isPasswordValid = await comparePassword(password, user.password); | ||
|
||
if (!isPasswordValid) { | ||
return res.status(400).json({ error: 'Invalid password' }); | ||
} | ||
|
||
const token = await generateToken(user._id); | ||
|
||
addCookie(res, 'token', token); | ||
|
||
res.status(200).json({ message: 'User logged in successfully', userId: user._id }); | ||
} catch (error) { | ||
res.status(500).json({ error: error | 'Internal Server Error' }); | ||
} | ||
}; | ||
|
||
export const logoutUser = async (req, res) => { | ||
try { | ||
removeCookie(res, 'token'); | ||
|
||
res.status(200).json({ message: 'User logged out successfully' }); | ||
} catch (error) { | ||
res.status(500).json({ error: error | 'Internal Server Error' }); | ||
} | ||
} | ||
|
||
export const verifyUser = async (req, res) => { | ||
try { | ||
const token = getCookies(req, 'token'); | ||
|
||
if (!token) { | ||
return res.status(400).json({ error: 'Invalid token' }); | ||
} | ||
|
||
const decoded = await verifyToken(token); | ||
|
||
if (!decoded) { | ||
return res.status(400).json({ error: 'Invalid token' }); | ||
} | ||
|
||
const user = await User.findById(decoded.id).select('-password'); | ||
|
||
if (!user) { | ||
return res.status(400).json({ error: 'User does not exist' }); | ||
} | ||
|
||
res.status(200).json({ message: 'User verified successfully', userId: user._id }); | ||
} catch (error) { | ||
res.status(500).json({ error: error | 'Internal Server Error' }); | ||
} | ||
}; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import express from 'express'; | ||
import cors from 'cors'; | ||
import connectDB from './config/dbConnection.js'; | ||
import cookieParser from 'cookie-parser'; | ||
|
||
const app = express(); | ||
|
||
const port = process.env.PORT || 3000; | ||
|
||
app.use(cors({ | ||
origin: 'http://localhost:5173', | ||
methods: ['GET', 'POST'], | ||
allowedHeaders: ['Content-Type'], | ||
credentials: true | ||
})); // Enable CORS | ||
|
||
app.use(cookieParser()); // Parse cookies | ||
app.use(express.json()); // Parse incoming request bodies in a middleware before your handlers | ||
app.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies | ||
|
||
// Connect to MongoDB | ||
connectDB(); | ||
|
||
// Routes | ||
import authRoutes from './routes/authRoutes.js'; | ||
app.use('/auth', authRoutes); | ||
|
||
app.get('/', (req, res) => { | ||
res.send('Working...'); | ||
}); | ||
// Start the server | ||
app.listen(port, () => { | ||
console.log(`Server is running on http://localhost:${port}`); | ||
}); |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import mongoose from 'mongoose'; | ||
|
||
const Schema = mongoose.Schema; | ||
|
||
const userSchema = new Schema({ | ||
name: { | ||
type: String, | ||
required: true, | ||
trim: true | ||
}, | ||
email: { | ||
type: String, | ||
required: true, | ||
unique: true, | ||
trim: true | ||
}, | ||
phoneNumber: { | ||
type: String, | ||
required: true, | ||
unique: true, | ||
}, | ||
password: { | ||
type: String, | ||
required: true | ||
} | ||
}, { | ||
timestamps: true | ||
}); | ||
|
||
const User = mongoose.model('User', userSchema); | ||
|
||
export default User; |
Oops, something went wrong.