GET information from user in database

  express, javascript, mongodb, node.js

I am making full stack app and learn from tutorials and videos . I have a problem with GET request to get information about user which is login in the system. I use Postman to check the requests. When I add user with /login , the Postman look user’s accesstoken code. I copy his code and paste it in authorization key in headers in Postman and when I change the URL in localhost to /infor to get information about this user and send it. But it say me "Invalid Authentication". I can’t find the wrong. I think the problem is in controllers/userCtrl.js in getUser function. Can you help me?

I put the code:

server.js

require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const fileUpload = require('express-fileupload')
const cookieParser = require('cookie-parser')


const app = express()
app.use(express.json())
app.use(cookieParser())
app.use(cors())

// Use temp files instead of memory for managing the upload process.
app.use(fileUpload({
    useTempFiles: true
}))

// Routes

app.use('/user', require('./routes/userRouter'))

// Connect to Mongodb
const URL = process.env.MONGO_URL
mongoose.connect(URL,{
    useCreateIndex: true,
    useFindAndModify: false,
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err =>{
    if(err) throw err;
    console.log('Connected to MongoDB')
})



const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
    console.log('Server is running on port', PORT)
})

.env

MONGO_URL = ***********
ACCESS_TOKEN_SECRET = ***********
REFRESH_TOKEN_SECRET = *************

routes/userRouter.js

require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const fileUpload = require('express-fileupload')
const cookieParser = require('cookie-parser')


const app = express()
app.use(express.json())
app.use(cookieParser())
app.use(cors())

// Use temp files instead of memory for managing the upload process.
app.use(fileUpload({
    useTempFiles: true
}))

// Routes

app.use('/user', require('./routes/userRouter'))

// Connect to Mongodb
const URL = process.env.MONGO_URL
mongoose.connect(URL,{
    useCreateIndex: true,
    useFindAndModify: false,
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err =>{
    if(err) throw err;
    console.log('Connected to MongoDB')
})



const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
    console.log('Server is running on port', PORT)
})

models/userModel.js

const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        trim: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true,
       
    },
    role: {
        type: Number,
       default: 0
    },
    cart: {
        type: Array,
        default: []
    }
}, {
    timestamps: true
})

module.exports = mongoose.model('Users', userSchema)

middleware/auth.js

const jwt = require('jsonwebtoken')

const auth = (req, res, next) => {
    try{
        const token = req.header("Authorization")
        if(!token) return res.status(400).json({ msg: "Invalid Authentication" })

        jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
            if(!err) return res.status(400).json({msg: "Invalid Authentication" })

            req.user = user
            next()
        })
    } catch (err) {
        return res.status(500).json({msg: err.message})
    }
}

module.exports = auth

controllers/userCtrl.js

const Users = require('../models/userModel')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')

const userCtrl = {
    register: async (req, res) => { // async before a function means one simple thing: a function always returns a promise. 
       try{
           const { name, email, password } = req.body

           const user = await Users.findOne({ email }) // wait until the promise resolves
           if(user) return res.status(400).json({msg: "The email already exists"})

           if(password.length < 6)
           return res.status(400).json({msg: "Password is at least 6 characteres long."})

           //Password encryption
           const passwordHash = await bcrypt.hash(password, 10)
           const newUser = new Users({
               name, email, password: passwordHash
           })

           // save mongodb
           await newUser.save()

           //then create jsonwebtoken to authentication
           const accesstoken = createAccessToken({ id: newUser._id })
           const refreshtoken = createRefreshToken({ id: newUser._id })

           res.cookie('refreshtoken', refreshtoken, {
            httpOnly: true,
            path: '/user/refresh_token'
          });

           res.json({accesstoken})

       } catch(err){
           return res.status(500).json({msg: err.message})
       }
    },
    login: async (req, res) => {
        try{
            const {email, password} = req.body;

            const user = await Users.findOne({email})
            if(!user) return res.status(400).json({msg: "User does not exist."})

            const isMatch = await bcrypt.compare(password, user.password)
            if(!isMatch) return res.status(400).json({msg: "Incorrect password"})
           
            // if login success, create access token and refresh token
            const accesstoken = createAccessToken({ id: user._id })
            const refreshtoken = createRefreshToken({ id: user._id })
 
            res.cookie('refreshtoken', refreshtoken, {
             httpOnly: true,
             path: '/user/refresh_token'
           });

           res.json({accesstoken})

        } catch(err){
            return res.status(500).json({msg: err.message})
        }
    },
    logout: async (req, res)=> {
        try{
            res.clearCookie('refreshtoken', {path: '/user/refresh_token'})
            return res.json({msg: "Logged out"})
        }catch(err){
            return res.status(500).json({msg: err.message})

        }
    },
    refreshToken: (req, res) => {
        try{
            const rftoken = req.cookies.refreshtoken
            if(!rftoken) return res.status(400).json({msg: "Please login or Register"})
           jwt.verify(rftoken, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
               if(err) return res.status(400).json({msg: "Please login or Register"})
               const accesstoken = createAccessToken({id: user.id})
               res.json({ accesstoken })

           })

        }catch (err) {
            return res.status(500).json({msg: err.message})
        }
        
    },
    getUser: async (req, res) => {  // problem
        try{
            const user = await (await Users.findById(req.user.id)).isSelected('-password')
            if(!user) return res.status(400).json({ msg: "Useer does not exist."})

            res.json(req.user)
        }catch (err) {
            return res.status(500).json({msg: err.message})
        }
    }
} 
    const createAccessToken = (user) => {
        return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1d' })
    }

    const createRefreshToken = (user) => {
        return jwt.sign(user, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '7d' })
    }
 

module.exports = userCtrl

Source: Ask Javascript Questions

LEAVE A COMMENT