1
const loginUser = async(foundUser,password,res) =>{
    
    const hashedPass = await hash.MD5(password)
    if(hashedPass !== foundUser.password){
        return res.status(401).json({
            "result":false,
            error:'Invalid username/password'
        });
    }

    const access_token = generateAccessToken({username:foundUser.username, firstname:foundUser.fname});
    const refresh_token = generateRefreshToken({username:foundUser.username, firstname:foundUser.fname});

    res.cookie("refreshtoken", refresh_token,{
        httpOnly:true,
        path:`/api/refresh_token`,
        maxAge: 30*24*60*60*1000, //30 days
    })
    res.status(200).json({
        "result":true,
        "jwt":access_token,
        "message":"Signin success"
    })

}
 refreshToken:async(req,res)=>{
        try {
            const rf_token = req.cookies.refreshtoken;
            if (!rf_token) return res.status(400).json({ msg: "Please login first" });
            
            const decoded = (
                JWT.verify(rf_token, `${process.env.SECRET_REFRESH_TOKEN}`)
            )

            if (!decoded) return res.status(400).json({ msg: "Please login first" });
            
            fs.readFile('userInfo.json',(err,data)=>{
                if(err) throw err;
                const allUsers = JSON.parse(data);
                const user = allUsers.find((user)=>{
                    return user.username === decoded.username
                })
                console.log(user)
                if(!user) return res.status(400).json({msg:'This account doesnot exist'})
                const access_token = generateAccessToken({
                    username:user.username,
                    firstname:user.fname
                })
                res.json({ 
                    "result":"true",
                    "data":user,
                    access_token
                });
            })
            
            

            // 
        } catch (err) {
            return res.status(500).json({msg:err.message})
        }
    }
const JWT = require('jsonwebtoken');

const auth = async(req,res,next) =>{
    try {
        const token = req.headers["authorization"];
        
        if(!token) return res.status(401).json({
            "result":false,
            "error":"Please provide a JWT token"
        })
        
        const authToken = token.split(' ')[1];
        console.log({authToken})
        console.log(process.env.SECRET_ACCESS_TOKEN)
        const decoded = JWT.verify(authToken, `${process.env.SECRET_ACCESS_TOKEN}`);
        console.log({decoded})
        if(!decoded) return res.status(400).json({
            "result":false,
            "error":"JWT Verification Failed"
        })
        
        req.username = decoded.username;
        next()

    } catch (err) {
        return res.status(500).json({msg:err.message});
    }
}

module.exports = auth;
const JWT = require('jsonwebtoken');

const generateAccessToken = (payload) =>{
    return JWT.sign(payload, `${process.env.SECRET_ACCESS_TOKEN}`, {expiresIn:'10m'})
}

const generateRefreshToken = (payload) =>{
    return JWT.sign(payload, `${process.env.SECRET_REFRESH_TOKEN}`,{expiresIn:'30d'})
}

module.exports = {generateAccessToken, generateRefreshToken}

Below code is of authentication when user tries to access his information.

I searched for any other answers but they are saying that token might be invalid which isn't the case here !

I am getting both authToken and process.env.SECRET_ACCESS_TOKEN value correctly.

still getting unexpected token error.

Please help me . If you need any other resource please comment it down

Anuj Shaan
  • 83
  • 1
  • 9
  • what is the exact output of `console.log({authToken})`? – jps May 11 '22 at 08:01
  • 1. What library are you using for the jwt 2. How are you signing the jwt token 3. Are you using bearer before the token – ardritkrasniqi May 11 '22 at 08:05
  • @jps the output is { authToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFudWpzaGFhIiwiZmlyc3RuYW1lIjoiYW51aiIsImlhdCI6MTY1MjI1NjE1MywiZXhwIjoxNjUyMjU2NzUzfQ.o7KhDEc-1F2oQHkeuXYOKiLa_nNKuy7b8Rz4ijt2VOs' } – Anuj Shaan May 11 '22 at 08:16
  • @ardritkrasniqi I have provided the code of signing the jwt token – Anuj Shaan May 11 '22 at 08:19
  • you should provide the generateAccessToken function, otherwise we cannot know how are you signing it – ardritkrasniqi May 11 '22 at 08:32
  • The token looks fine. Btw. thanks for posting code, but now you don't show the code in which the error happens anymore. – jps May 11 '22 at 08:32
  • @ardritkrasniqi I don't think it's relevant how the token was created, the OP already posted the token and it looks ok. The error happens during verification. – jps May 11 '22 at 08:34
  • @jps updated the required – Anuj Shaan May 11 '22 at 08:35
  • @ardritkrasniqi i have posted generateAccessToken code – Anuj Shaan May 11 '22 at 08:37
  • ran a the code on my local machine, everything looks fine. You should check for syntax error propably any missing parenthesis or any module export failure – ardritkrasniqi May 11 '22 at 09:35

0 Answers0