hiteshchoudhary / chai-backend Goto Github PK
View Code? Open in Web Editor NEWA video series on chai aur code youtube channel
A video series on chai aur code youtube channel
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
When i tested login route , i get some error and then i debugged it . i noticed that data i received from req .body is a empty object.
where should be problem ?
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.
I might be wrong. Please correct me if I'm. Happy Coding : )
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
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 ?
When I send request through Postman it's through an error of jwt malformed
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
An error occurred while attempting to send the request.
If you want to check the loginUser here is the response and cookies after doing API testing on {{server}}/users/login.
This has been done using ThinderClient
destructure generateAccesstokenAndRefreshToken as { accessToken, refreshToken: newRefreshToken }
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
`
const options={
httpOnly:true
}
// remove secure option
`
(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
[TypeError: Converting circular structure to JSON in nodejs]
at - return res
.status(201)
.json(new ApiResponse(201, createdUser, "User registered Successfully"));
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)
So I am in the video of 'ROUTES AND CONTROLLER WITH DEBUGGING". After the creating my register route, i started the server and got:
`Server is running on port 8000
/n Database connected !! DB HOST: ac-fdtffkb-shard-00-02.gcq7rur.mongodb.net
Error in DB Connection TypeError: Cannot read properties of undefined (reading 'method')
at Function.handle (C:\Users\Harshit\Desktop\Chai Aur Code Backend\chai_aur_backend\node_modules\express\lib\router\index.js:139:34)
at Function.handle (C:\Users\Harshit\Desktop\Chai Aur Code Backend\chai_aur_backend\node_modules\express\lib\application.js:181:10)
at app (C:\Users\Harshit\Desktop\Chai Aur Code Backend\chai_aur_backend\node_modules\express\lib\express.js:39:9)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async file:///C:/Users/Harshit/Desktop/Chai%20Aur%20Code%20Backend/chai_aur_backend/src/index.js:15:1
`
I am unable to identify the problem yet. But it was connecting properly the last time I checked..
This is my index.js
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.
In the user.controller.js file while writing refreshAccessToken function you forgot the ! in the if statement.
Line 188
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;
lowecase: true,
should be
lowercase: true,
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);
when Im sending my email and password the "generateAccessAndRefereshTokens" fn catching error that "Something went wrong while generating access and refresh token" .
when I console log the "user" its working but when I consolelog the "refreshToken" the fn goes to catch block
I think something is wrong with "generateAccessToken" and "generateRefreshToken" methods defined in user.model file
const generateAccessAndRefereshTokens = async(userId) =>{
try {
const user = await User.findById(userId)
const accessToken = await user.generateAccessToken()
const refreshToken = await user.generateRefreshToken()
user.refreshToken = refreshToken
await user.save({ validateBeforeSave: false })
return {accessToken, refreshToken}
} catch (error) {
throw new ApiError(500, "Something went wrong while generating referesh and access token")
}
}
When reister user postman itsays canot read properties of undefined
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
user.controller.js
cloudinary.js
multer.middleware.js
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.
RefreshToken is there in the Database
cookies are gone but from the database, the refresh token is still there
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.
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
we have missed api to add videos in watchHistory
.cookie("accessToken", accesToken, options)
.cookie("refreshToken", refreshToken, options)
In cookie options secure:true not working what should i do
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:
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.
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.
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.
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) }
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
in refreshAccessToken() function in User controller
after generating new refresh and access token,
const { accessToken, newRefreshToken } = await generateAccessAndRefreshTokens(user?._id);
Shouldn't the database be updated with the new refresh token?
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
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',
})
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)
);
}
);
Hi, so if a registered user calls the "register" api again with avatar and coverImage field in body then multer uploads the files in public/temp and there is no unlinking happening there and can be fixed with the check in "if" block of "existedUser" we can unlink there
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.