GithubHelp home page GithubHelp logo

chai-backend's Introduction

chai aur backend series

This is a video series on backend with javascript


Summary of this project

This project is a complex backend project that is built with nodejs, expressjs, mongodb, mongoose, jwt, bcrypt, and many more. This project is a complete backend project that has all the features that a backend project should have. We are building a complete video hosting website similar to youtube with all the features like login, signup, upload video, like, dislike, comment, reply, subscribe, unsubscribe, and many more.

Project uses all standard practices like JWT, bcrypt, access tokens, refresh Tokens and many more. We have spent a lot of time in building this project and we are sure that you will learn a lot from this project.


Top Contributer to complete all TODOs

  1. Spiderman (just sample) Link to Repo

How to contribute in this open source Project

First, please understand that this is not your regular project to merge your PR. This repo requires you to finish all assignments that are in controller folder. We don't accept half work, please finish all controllers and then reach us out on Discord or Twitter and after checking your repo, I will add link to your repo in this readme.

chai-backend's People

Contributors

hiteshchoudhary avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chai-backend's Issues

refresh token

const user = await User.create(
{
username,
email,
fullname,
avatar: avatar.url,
coverImage: coverImage?.url || "",
password,
refreshToken: ""
}
)
guru ji refresh token database me save nhi ho rha uska field bhi nhi dikha rha h kya usko blank rkh skte h. or i did any mistake

Error showing while sending data from postman

error showing (Avatar file is required) due to the connection was not establishing with cloudinary and
after wasting few hours then i import dotenv in cloudinary.js file and error gone

import dotenv from 'dotenv';

dotenv.config({
path: '.env',
})

reference issue

it shows the reference error when i am using the $addfeild method of mongo aggeregation pipeline .

to solve that i used the route to not store the feilds as addfeild instead i used the $project and passed the values

// User.find({username}) const channel = await User.aggregate([ { $match: { username: username } }, { $lookup: #{ from: "subscriptions", localField: "_id", foreignField: "channel", as: "subscribers" } }, { $lookup: { from: "subscriptions", localField: "_id", foreignField: "subscriber", as: "subscribedTo" } }, { # $project: { fullName: 1, username: 1, avatar: 1, coverImage: 1, email: 1, subscribersCount: { $size: "$subscribers" }, subscribedCount: { $size: "$subscribedTo" }, isSubscribed: { $cond: { if: { $in: [req.user?._id, "$subscribers.subscriber"] }, then: true, else: false } } } } ]);

then it solved

is there any other way to solve it

Issue logout user

When I send request through Postman it's through an error of jwt malformed

Cannot POST /api/v1/users/register

i dont know what is wrong
console is showing mongoDB is been connected server is runnning at port 8000
Yet cant make post request in postman

//app.js

import express from "express";
import cors from "cors";
import cookieParser from "cookie-parser";

const app = express();

// cross orign resource pairing 
app.use(cors({
  orgin: process.env.CORS_ORIGIN,
  credentials: true
})) 
app.use(express.json({limit: "16kb"}))
app.use(express.urlencoded({
  extended: true,
  limit: "16kb"
}))
app.use(express.static("public"))
app.use(cookieParser())

//routes import 
import userRouter from "./routes/user.routes.js"

//routes declaration
app.use("/api/v1/users", userRouter)
// // https://localhost:3000/api/v1/users/register

export { app }
//user.controller.js

import { asyncHandler } from "../utils/asyncHandler.js";

const registerUser = asyncHandler( async (req,res) => {
  return res.status(200).json({
    message: "ok"
  })
})

export { registerUser }
//asyncHandler.js

// using promise method 
const asyncHandler = () => {
  (req,res,next) => {
    Promise.resolve(requestHandler(req,res,next)).catch((err) => next(err))
  }
}

// learn about node.js api errors

export {asyncHandler}
//user.routes.js

import { Router } from "express";
import { registerUser } from "../controllers/user.controller.js";

const router = Router();

// Add middleware to parse the request body
// router.use(express.json());

router.route("/register").post(registerUser); 

export default router;

AddToWatchHistory and removeFromeWatchHistory

AddToWatchHistory and removeFromeWatchHistory functions should be there in user.controller.js to add or remove videos to watch history.

I have made the function anyone can check that in my forked repository.

Logout Issue

Getting this error while logging out user. Please help !

image

issue in subscription route

Screenshot from 2024-01-11 02-30-36

we got issue
getUserChannelSubscriber required channelId as we wrote subscribedId
and getSubscribedChannel don't requried anything as it got from req.user._id

While doing API testing the logout is getting failed and getting Unauthorized request `Need Help`

The issue is actually occurring in verifyJWT middleware router.route("/logout").post(verifyJWT, logoutUser);

Inside verifyJWT I console logged the req and what I found is req.cookies is empty. and thereby the token is undefined and I am getting Unauthorized request error

Here is the code for verifyJWT
image

An error occurred while attempting to send the request.image

If you want to check the loginUser here is the response and cookies after doing API testing on {{server}}/users/login.

image
image

This has been done using ThinderClient

updateUserAvatar , updateUserCoverImage

(correct me if i wrong)

const user = await User.findByIdAndUpdate(req.user?._id,{
$set:{
avatar:avatar.url
}
},{new:true}).select("-passworrd");

we are updating but not save in database . so we have to save user like
user.save() using save method

i got multer error when i am upload the file

it's error details:
MulterError: Unexpected field
at wrappedFileFilter (C:\PROJECTS\MERN PROJECT\Youtube\node_modules\multer\index.js:40:19)
at Multipart. (C:\PROJECTS\MERN PROJECT\Youtube\node_modules\multer\lib\make-middleware.js:107:7)
at Multipart.emit (node:events:514:28)
at HeaderParser.cb (C:\PROJECTS\MERN PROJECT\Youtube\node_modules\busboy\lib\types\multipart.js:358:14)
at HeaderParser.push (C:\PROJECTS\MERN PROJECT\Youtube\node_modules\busboy\lib\types\multipart.js:162:20)
at SBMH.ssCb [as _cb] (C:\PROJECTS\MERN PROJECT\Youtube\node_modules\busboy\lib\types\multipart.js:394:37)
at feed (C:\PROJECTS\MERN PROJECT\Youtube\node_modules\streamsearch\lib\sbmh.js:248:10)
at SBMH.push (C:\PROJECTS\MERN PROJECT\Youtube\node_modules\streamsearch\lib\sbmh.js:104:16)
at Multipart._write (C:\PROJECTS\MERN PROJECT\Youtube\node_modules\busboy\lib\types\multipart.js:567:19)
at writeOrBuffer (node:internal/streams/writable:556:12)

Password is not being hashed properly. You get Invalid Password despite both the passwords being the same.

I encountered this bug while logging in the user. The login controller was throwing "Invalid Password" each time despite the passwords being the same.

So, I thought of checking it out on Replit. I registered the user and got hashed password from the MongoDB document, and then compared them in Replit but the return value was still false, here are the images for reference.

User registered successfully
image

Error while logging in
image

Hashed password from MongoDB
image

Error on Replit
image

Then I asked ChatGPT to generate a code for the same and it started working as it should work

    const user = this;
    if (!user.isModified('password')) {
        return next();
    }
    try {
        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(user.password, salt);
        user.password = hashedPassword;
        next();
    } catch (error) {
        next(error);
    }
});

I am still trying to understand what was wrong in the original code. Sir it's a request please check this on your side and let us know about it.

JWT malformed

Error : JWT is malformed, when hitting the /refresh-token end point.

To resolve this change the code like this.
const { accessToken, refreshToken } = await generateAccessAndRefereshTokens(user._id);

instead of
const { accessToken, newRefreshToken } = await generateAccessAndRefereshTokens(user._id);

Refresh Token Doesn't gone

When the refreshToken is generated, while login the user then, it will stored in the database
then the next step is to logout the user.

Logout of the user there is a problem starts

while logout refreshToken should dropped from the database.
as per the logic, the refresh token should be deleted from the database.

step 1: Register user
image

User Data in DataBase
image

step 2: Login the User
image

RefreshToken is there in the Database
image

step 3: Logout the User
image

cookies are gone but from the database, the refresh token is still there
image

Subscription controllers

i am not sure whether these controller functions are at there correct place:

const router = Router();
router.use(verifyJWT); // Apply verifyJWT middleware to all routes in this file

router
  .route("/c/:channelId")
  .get(getSubscribedChannels)
  .post(toggleSubscription);

router.route("/u/:subscriberId").get(getUserChannelSubscribers);

because in the controllers files:
getSubscribedChannels is fetching the subscriberId
and
getUserChannelSubscribers is fetching the channelId

coverImage undefined issue

I'm getting the " Cannot read properties of undefined (reading '0')
   at file:///C:/Users/krish/OneDrive/Desktop/Programming/Web%20development/Backend_project/src/controllers/user.controller.js:44:52
   at process.processTicksAndRejections (node:internal/process/task_queues:95:5) ""
Its saying something is wrong with coverImage
Screenshot 2024-05-07 235108
Screenshot 2024-05-07 235227

Issue Occur in LogOut

if i send req using postman (generally issue occur in logout route)!!
jwt must be a string
Error: Invalid AccessToken
at file:///C:/Users/win11/OneDrive/Desktop/Backend/src/middleware/auth.middleware.js:30:17

Error uploading Cover Image

Cover Image not being saved to "Local Path" and therefore not on "Cloudinary" also even after providing it on postman
below are the attachments of output and my code please help

I have read all the previous solutions to similar issue but error dosen't resolve

Screenshot 2023-12-25 184823

user.controller.js

Screenshot 2023-12-25 185242

cloudinary.js

Screenshot 2023-12-25 185416

multer.middleware.js

Screenshot 2023-12-25 185549

Register controller not throwing error if any of the required field is undefined

Where: if (
[fullName, email, username, password].some((field) => field?.trim() === "")
) {
throw new ApiError(400, "All fields are required")
}
Expected behaviour -> When request body doesn't contain any of the field then it should throw error.
Actual behaviour -> It is not able to catch the undefined field hence error is missing

Avatar Upload failed

Screenshot 2024-04-26 130431
I noticed that in my public folder the images I am sending from postman is NOT GETTING stored, I tried debugging it but couldn't find the solution

cookie not set

.cookie("accessToken", accesToken, options)
.cookie("refreshToken", refreshToken, options)

In cookie options secure:true not working what should i do

Using params

Hey Hitesh,

I need some info about in some routes we are using subsciber or userId as params, as we take care or extract from jwt then why we are getting ids in params in the form of userId. Is this intentionally or the sake of easiness.

Routes are following:

  1. router.route("/user/:userId").get(getUserTweets);
  2. router.route("/u/:subscriberId").get(getUserChannelSubscribers);
  3. router.route("/user/:userId").get(getUserPlaylists);

MongoServerError: Invalid database name:

While sending API request I getting this error Invalid database name: '/VideoApplication'

This is .env file SC where I am storing the DB_NAME
image

inside db/index.js
image

SC of the error
image

But also the user is getting created in mongodb and the images are getting uploaded in cloudinary.

Local file path for coverImage (optional chaining)

Can't we use - const coverImageLocalPath = req.files?.coverImage?.[0]?.path;
instead of
const coverImageLocalPath = req.files?.coverImage[0]?.path;

optional chaining while getting local file path for cover image ?
It is working fine.

getallvideos in video controller question

const getAllVideos = asyncHandler(async (req, res) => {
const { page = 1, limit = 10, query, sortBy, sortType, userId } = req.query
})

for what purpose we are using query parameter in req.query ?

temp file creating even if an error occurs

Hello Sir ,
In routers while the request coming through middleware, the file which are coming in requests are creating even if the user.controller.js gives an error while execution. We need to try and catch so that when the error will occur it should excute the unlinkSync(filepath).I have tried this and it worked. please correct me If i am wrong in the next video.

try{code block to execute} catch(error){ const avatarLocalPath= req.files?.avatar?.[0]?.path const coverImageLocalPath = req.files?.coverImage?.[0]?.path if(avatarLocalPath) fs.unlinkSync(avatarLocalPath) if (coverImageLocalPath) fs.unlinkSync(coverImageLocalPath) throw new ApiError(error.statusCode,error.message) }

In regiister user controller files are not deleted if same user tries to register again

As stated above, there are some issues with avatar and cover image when re-registering the same user, I made some changes in the controller of user model and it worked for me


const registerUser = asyncHandler(
    async (req, res) => {
        const { username, email, fullName, password } = req.body;
        let avatarLocalPath = "";
        let coverImagePath = "";
        if (req.files && Array.isArray(req.files.avatar) && req.files.avatar.length > 0) {
            avatarLocalPath = req.files?.avatar[0]?.path;
        }
        if (req.files && Array.isArray(req.files.coverImage) && req.files.coverImage.length > 0) {
            coverImagePath = req.files.coverImage[0].path;
        }
        if (!avatarLocalPath) {
            if (coverImagePath) {
                fs.unlinkSync(coverImagePath);
            }
            throw new ApiError(400, "Avatar files is required.");
        }
        if (
            [fullName, email, username, password].some(
                (field) => {
                    return field?.trim() === "";
                })
        ) {
            fs.unlinkSync(avatarLocalPath);
            if (coverImagePath) {
                fs.unlinkSync(coverImagePath);
            }
            throw new ApiError(400, "All fields are required");
        }

        const existedUser = await User.findOne({
            $or: [{ username }, { email }]
        });

        if (existedUser) {
            fs.unlinkSync(avatarLocalPath);
            if (coverImagePath) {
                fs.unlinkSync(coverImagePath);
            }
            throw new ApiError(409, "User with same email or username exists in db.");
        }
        const avatar = await uploadOnCloudinary(avatarLocalPath);
        const coverImage = await uploadOnCloudinary(coverImagePath);

        if (!avatar) {
            throw new ApiError(400, "Avatar files is required.");
        }

        const user = await User.create({
            fullName,
            avatar: avatar.url,
            coverImage: coverImage?.url || "",
            username: username.toLowerCase(),
            email,
            password
        });

        const createdUser = await User.findById(user._id).select(
            "-password -refreshToken"
        );
        if (!createdUser) {
            throw new ApiError(500, "Something went wrong while registering the user");
        }
        return res.status(201).json(
            new ApiResponse(200, "User created successfully", createdUser)
        );
    }
);

Feature Request: Implement Email Link, Mobile OTP Verification, and Google Account Login

How can we implement email link or mobile OTP verification at the time of registration? If, later, we want, we can also implement this for two-factor authentication on the settings page.

Also, if someone wants to log in using their Google account, how do we implement that?

If you could implement this in the ongoing project, that would be great. Otherwise, please provide some ideas or explanations on how to implement this.

Sending and saving refresh token is not required ig - https://www.youtube.com/watch?v=L2_gIrDxCes&list=PLu71SKxNbfoBGh_8p_NS-ZAh6v7HhYqHW&index=17

Here sir has saved and sent both refresh and access token in the accessTokenRefresh controller. I suppose that is not required because once the access token has expired, you can hit a end point to refresh access token by sending refresh token cookie
as refresh token has long expiry period than access token. And we can generate only access token and send it to the response cookie rather than creating both and saving it in user collection and sending it.
For further requests, we can only send new generated access token and once if both expires, we can tell user to login again to generate new access and refresh token in login endpoint.
Screenshot 2023-12-24 130033
Screenshot 2023-12-24 143655

I might be wrong. Please correct me if I'm. Happy Coding : )

Avatar File is Required issue

I checked and everything is working, and when I sent a request using Postman,  this avatar file issue occurred. How can I resolve this issue?
Screenshot 2023-12-23 220508

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.