Skip to content

Commit

Permalink
Created backend routes
Browse files Browse the repository at this point in the history
  • Loading branch information
Ratnesh4193 committed Jan 15, 2024
1 parent 3bf61fd commit 1e5298e
Show file tree
Hide file tree
Showing 54 changed files with 1,403 additions and 2 deletions.
5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/PledgeUp-backend/node_modules
/PledgeUp-frontend/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build
/PledgeUp-backend/build

# misc
.DS_Store
Expand Down
20 changes: 20 additions & 0 deletions PledgeUp-backend/config/connectDb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import mongoose from "mongoose";
const connectDB = async () => {
try {
const MONGO_URI =
process.env.MONGO_URI ||
"mongodb+srv://{USERNAME}:{PASSWORD}@cluster0.v2loj.mongodb.net/pledgeup?retryWrites=true&w=majority";
console.log(MONGO_URI);
const conn = await mongoose.connect(MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
});

console.log(`MongoDB Successfully Connected: ${conn.connection.host}`);
} catch (error) {
console.error(`DB-Error:${error.message}`);
process.exit(1);
}
};

export default connectDB;
69 changes: 69 additions & 0 deletions PledgeUp-backend/controllers/userControllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import asyncHandler from "express-async-handler";
import generateToken from "../utils/generateToken.js";
import User from "../models/userModel.js";

// @desc Auth user and get token
// @route POST /api/users/login
//@access Public
const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });

if (user && (await user.matchPassword(password))) {
res.json({
_id: user._id,
name: user.name,
email: user.email,
token: generateToken(user._id),
});
} else throw new Error("Invalid email or password");
});

// @desc Register new user
// @route POST /api/users/
//@access Public
const registerUser = asyncHandler(async (req, res) => {
const { name, email, password } = req.body;
const userExist = await User.findOne({ email });

if (!userExist) {
const user = await User.create({ name, email, password });
if (user) {
res.status(201).json({
_id: user._id,
name: user.name,
email: user.email,
});
} else {
res.status(401);
throw new Error("Invalid user details");
}
} else {
res.status(401);
throw new Error("Email already exist");
}
});

// @desc get user profile
// @route GET /api/users/profile
//@access Private
const getUserProfile = asyncHandler(async (req, res) => {
const user = await User.findById(req.body.id).select("-password");
if (user) {
console.log("id: ", req.body.id);
console.log({
_id: user._id,
name: user.name,
email: user.email,
});
res.status(201).json({
_id: user._id,
name: user.name,
email: user.email,
});
} else {
res.status(404);
throw new Error("User not Found");
}
});
export { authUser, registerUser, getUserProfile };
32 changes: 32 additions & 0 deletions PledgeUp-backend/middlewares/authMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import jwt from "jsonwebtoken";
import asyncHandler from "express-async-handler";
import User from "../models/userModel.js";

const protect = asyncHandler(async (req, res, next) => {
let token;

const JWT_SECRET = "pledgeup" || process.env.JWT_SECRET;
const authorization = req.headers.authorization || req.body.authorization;
if (authorization && authorization.startsWith("Bearer ")) {
try {
token = authorization.split(" ")[1];

const decoded = jwt.verify(token, JWT_SECRET);

req.user = await User.findById(decoded.id).select("-password");

next();
} catch (error) {
console.error(error);
res.status(401);
throw new Error("Not authorized, token failed");
}
}

if (!token) {
res.status(401);
throw new Error("Not authorized, no token");
}
});

export { protect };
40 changes: 40 additions & 0 deletions PledgeUp-backend/models/userModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import mongoose from "mongoose";
import bcrypt from "bcryptjs";

const userSchema = mongoose.Schema(
{
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
},
{
timestamps: true,
}
);

userSchema.methods.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};

userSchema.pre("save", async function (next) {
if (!this.isModified("password")) {
next();
}

const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
});

const User = mongoose.model("User", userSchema);

export default User;
Loading

0 comments on commit 1e5298e

Please sign in to comment.