Skip to content

Commit

Permalink
Merge pull request #24 from tarunkumar2005/main
Browse files Browse the repository at this point in the history
Created Signup, login, logout, and verifyToken Routes in Backend
  • Loading branch information
dhairyagothi authored Oct 2, 2024
2 parents 34f1aff + ff6e089 commit baab1ee
Show file tree
Hide file tree
Showing 10 changed files with 1,379 additions and 7 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
node_modules/
node_modules
.env
11 changes: 11 additions & 0 deletions backend/config/config.js
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;
14 changes: 14 additions & 0 deletions backend/config/dbConnection.js
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;
111 changes: 111 additions & 0 deletions backend/controllers/authController.js
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' });
}
};
34 changes: 34 additions & 0 deletions backend/index.js
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}`);
});
32 changes: 32 additions & 0 deletions backend/models/User.js
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;
Loading

0 comments on commit baab1ee

Please sign in to comment.