Reactord
Reactord

Reputation: 106

User not existend in the database JWT?

So i have got a slight problem with the user authentication with JWT token. When i Login it returns to me "user doesnt exist", although there's clearly an user in the database. I've tried to fix by not looking for the password in the database and comparing it and it worked, but my question is how can i compare passwords in mongoose database and check if the user exists?

Login route:

//create route for sign in
router.post('/signin', async (req, res) => {
    //destructure email and password from req.body
    const user = await User.findOne({
        email: req.body.email,
        password: req.body.password,
    })
    if (!user) res.status(400).send({ message: 'User doesnt exist' })
    else {
        const valid = compare(req.body.password, user.password)
        if (!valid) res.send(400).send({ message: 'Password doesnt match' })

        if (valid) {
            const accesstoken = createAccessToken(user._id)
            const refreshtoken = createRefreshToken(user._id)
            return res.send({
            email: user.email,
            refreshtoken: user.refreshtoken,
            sendAccessToken: sendAccessToken(req, accesstoken),
            sendRefreshToken: sendRefreshToken(refreshtoken),
        })
        }
    }
})

user Model:

const mongoose = require('mongoose')
// const SALT_WORK_FACTOR = 10
// const bcrypt = require('bcryptjs')

//how a user will be stored in the mongodb schema
const userSchema = new mongoose.Schema({
    name: { type: String, required: true, index: { unique: true } },
    email: { type: String, required: true, unique: true, dropDups: true },
    password: { type: String, required: true, minlength: 6, trim: true },
    isAdmin: { type: Boolean, required: true, default: false },
    refreshtoken: { type: String },
})

const userModel = mongoose.model('Users', userSchema)

module.exports = userModel

login page:

import React, { useState, useEffect, useContext } from 'react'
import { userContext } from '../../App'
// import { useDispatch, useSelector } from 'react-redux'
// import { login } from '../../actions/userActions'

function Login(props) {
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [user, setUser] = useContext(userContext)
    //acces the userLogin from redux store
    // const userLogin = useSelector((state) => state.userLogin)
    // const { loading, userInfo, error } = userLogin

    // const dipsatch = useDispatch()
    // useEffect(() => {
    //     if (userInfo) {
    //         props.history.push('/')
    //     }
    // }, [userInfo])

    //handlesubmit
    const handleSubmit = async (e) => {
        e.preventDefault()
        const result = await (
            await fetch('http://localhost:5000/users/signin', {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    email,
                    password,
                }),
            })
        ).json()
        if (result.accesstoken) {
            setUser({
                accesstoken: result.accesstoken,
            })
            window.location = '/'
        } else {
            alert(result.error)
        }
    }
    useEffect(() => {
        console.log(user)
    }, [user])

    return (
        <div>
            <h1 className="login-h">Login</h1>

            <form onSubmit={handleSubmit} className="login">
                <div className="login-form">
                    <label>email</label>
                    <br />
                    <input
                        type="email"
                        placeholder="username or email"
                        for="email"
                        onChange={(e) => setEmail(e.target.value)}
                    ></input>
                    <br />
                    <label>Password</label>
                    <br />
                    <input
                        type="password"
                        placeholder="Password"
                        for="password"
                        onChange={(e) => setPassword(e.target.value)}
                    ></input>
                    <br />
                    <p className="forget-pw">
                        <a href="/">Forgot password?</a>
                    </p>
                    <button>Login</button> <br />
                    <br />
                    {/* <p style={{ color: 'red' }}>{result.error}</p> */}
                </div>
                <p className="have-ccl">
                    {' '}
                    No account yet?<a href="/signup">Signup</a>
                </p>
            </form>
        </div>
    )
}

export default Login

Upvotes: 0

Views: 207

Answers (1)

user14520680
user14520680

Reputation:

There are a few problems:

  1. Remove the unnecessary password: req.body.password line from your mongoose query. This is basically comparing unhashed passwords with hashed passwords in a plain JavaScript object. This never returns true because the hash is always different from the unhashed password.
  2. Is it possible that your body is never actually sent? You need to add the name attribute to inputs before they can be parsed. Are you using body-parser?

Upvotes: 1

Related Questions