Skip to content

Commit

Permalink
setup auth routes, setup mongodb, created signup + login + logout end…
Browse files Browse the repository at this point in the history
…points
  • Loading branch information
mmli1 committed Jan 8, 2025
1 parent ab11cf0 commit 884a998
Show file tree
Hide file tree
Showing 5 changed files with 137 additions and 7 deletions.
6 changes: 5 additions & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
PORT=8000
PORT=5000
MONGO_DB_URI=mongodb+srv://michelleli12315:[email protected]/chat-app-db?retryWrites=true&w=majority&appName=Cluster0
JWT_SECRET=iOnLS5F/ucJ/Ez8HoMVclNLcsRdieR7XPtHhv1lbyME=

NODE_ENV=development
91 changes: 91 additions & 0 deletions backend/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import bcrypt from "bcryptjs";
import User from "../models/user.model.js";
import generateTokenAndSetCookie from "../utils/generateToken.js";

export const signup = async (req, res) => {
try {
const {fullName, username, password, confirmPassword, gender} = req.body;

if (password !== confirmPassword) {
return res.status(400).json({error:"Passwords don't match"});
}

const user = await User.findOne({username});

if (user) {
return res.status(400).json({error:"Username already exists"});
}

// HASH PASSWORD HERE
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

// https://avatar-placeholder.iran.liara.run/

const boyProfilePic = `https://avatar.iran.liara.run/public/boy?username=${username}`;
const girlProfilePic = `https://avatar.iran.liara.run/public/girl?username=${username}`;

const newUser = new User({
fullName,
username,
password: hashedPassword,
gender,
profilePic: gender === "male" ? boyProfilePic : girlProfilePic,
});

if (newUser) {
// Generate JWT token here
generateTokenAndSetCookie(newUser._id, res);
await newUser.save();

res.status(201).json({
_id: newUser._id,
fullName: newUser.fullName,
username: newUser.username,
profilePic: newUser.profilePic,
});
} else {
res.status(400).json({error: "Invalid user data"});
}

} catch (error) {
console.log("Error in signup controller", error.message);
res.status(500).json({error: "Internal Server Error"});

}
};

export const login = async (req, res) => {
try {
const {username, password} = req.body;
const user = await User.findOne({username});
const isPasswordCorrect = await bcrypt.compare(password, user?.password || "");

if (!user || !isPasswordCorrect) {
return res.status(400).json({error: "Invalid username or password"});
}

generateTokenAndSetCookie(user._id, res);

res.status(200).json({
_id: user._id,
fullName: user.fullName,
username: user.username,
profilePic: user.profilePic,
});

} catch (error) {
console.log("Error in login controller", error.message);
res.status(500).json({error: "Internal Server Error"});
}
};

export const logout = (req, res) => {
try {
res.cookie("jwt", "", {maxAge: 0});
res.status(200).json({message: "Logged out succesfully"});
} catch (error) {
console.log("Error in logout controller", error.message);
res.status(500).json({error: "Internal Server Error"});
}
};
12 changes: 12 additions & 0 deletions backend/db/connectToMongoDB.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import mongoose from 'mongoose';

const connectToMongoDB = async () => {
try {
await mongoose.connect(process.env.MONGO_DB_URI);
console.log("Connected to MongoDB");
} catch (error) {
console.log("Error connecting to MongoDB", error.message);
}
};

export default connectToMongoDB;
13 changes: 13 additions & 0 deletions backend/routes/auth.routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import express from "express";
import { login, logout, signup } from "../controllers/auth.controller.js";


const router = express.Router();

router.post("/signup", signup);

router.post("/login", login);

router.post("/logout", logout);

export default router;
22 changes: 16 additions & 6 deletions backend/server.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import express from "express";
import dotenv from "dotenv";

import authRoutes from "./routes/auth.routes.js";
import connectToMongoDB from "./db/connectToMongoDB.js";

const app = express();
const PORT = process.env.PORT || 5000;

dotenv.config();
const PORT = process.env.PORT || 5000;

app.get("/", (req, res) => {
// root route http://localhost:5000/
res.send("Hello World!!");
});
app.use(express.json()); // to parse the incoming requests with JSON payloads (from req.body)

app.use("/api/auth", authRoutes);

// app.get("/", (req, res) => {
// // root route http://localhost:5000/
// res.send("Hello World!!");
// });

app.listen(PORT, () => console.log(`Server Running on port ${PORT}`));
app.listen(PORT, () => {
connectToMongoDB();
console.log(`Server Running on port ${PORT}`)
});

0 comments on commit 884a998

Please sign in to comment.