Jwt getting expired as the code starts executing

18 Views Asked by At
import jwt from 'jsonwebtoken';
import 'dotenv/config';
import express, { Express, NextFunction, Request, Response } from 'express';
const createAccessToken = (userId: string) => {
    return jwt.sign({ userId }, process.env.ACCESS_TOKEN_SECRET!, {
        expiresIn: '1h' 
    });
}

const createRefreshToken = (userId: string) => {

    return jwt.sign({ userId }, process.env.REFRESH_TOKEN_SECRET!, {
        expiresIn: "7d"
    })
}

const sendaccessToken = (req:Request,res:Response, token: string) => {

    res.status(200).json({ accessToken: token })
}
const sendrefreshToken = (res: any, token: string) => {(
res.cookie('refreshtoken',token,{
    httpOnly:true,
    path: '/'   
})


)}

export { createAccessToken, createRefreshToken,sendrefreshToken,sendaccessToken}

This is how I generate my token and when I run my refresh tokwn i get my jwt has expired within a second.Please note that the jwt obtained when i signed is same as which i use in refreshtoken only issue is jwt verify throws an expired error

const UserRefreshToken = async (req: Request, res: Response) => {
  
  const token=req.cookies.refreshtoken;
console.log(token)
  //if no toem in our request
  if(!token){
return res.status(400).json({accestoken:""})
  }
  let payload:any=null
  try{
    //if toekn verify

    payload=verify(token,process.env.REFRESH_TOKEN_SECRET!)
    console.log(payload)
  }catch(error){
    console.log(error)
     return res.status(300).json({accestoken:""})
  
}
}

const user=await prisma.refreshToken.findUnique({where:{userId:payload.userId}})
console.log(user)
if(!user){
  return res.status(400).json({accestoken:""})
    }
    
    if(user?.token!==token){
      return res.status(400).json({accestoken:""})
    }
      
      const accesstoekn=createAccessToken(user.userId)
      const refreshtoken=createRefreshToken(user.userId)
    
      await prisma.refreshToken.update({where:{userId:user.userId},data:{token:refreshtoken}})
      res.send({accesstoekn})
}

every time i run the verify the code it always throws up expired error

0

There are 0 best solutions below