M
M
mrrangerr2020-07-06 15:52:02
MySQL
mrrangerr, 2020-07-06 15:52:02

Why is the user not being authenticated?

Hello everyone, I'm trying to make authorization using a session. I switch to the desired route, the validation works correctly, but if I enter the correct data, it first takes a long time to load. and the error "Page is not available The site localhost did not send data" takes off. What is the problem?

const express = require('express')
const bodyParser = require('body-parser')
const session = require('express-session')
const MySQLStore = require('express-mysql-session')(session)
const Sequelize = require('sequelize')
const db = require('./models')
const bcrypt = require('bcryptjs')
const hbs = require('hbs')
const expressHbs = require("express-handlebars");

const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
    extended: true
}))
app.engine('hbs', expressHbs({
    layoutsDir: 'views/layouts',
    defaultLayout: 'layout',
    extname: 'hbs'
}))
hbs.registerPartials(__dirname + '/views/partials')
app.use("/public", express.static("public"))


const User = db.user
const SequelizeStore = require('connect-session-sequelize')(session.Store)
const sequelize = new Sequelize('stroymag', 'root', 'password', {
    dialect: 'mysql',
})
const myStore = new SequelizeStore({
    db: sequelize
})

const TWO_HOURS = 1000 * 60 * 60 * 2
const {
    PORT = 3000,
    NODE_ENV = 'development',
    SESS_NAME = 'sid',
    SESS_LIFETIME = TWO_HOURS,
    SESS_SECRET = 'ssh!quiet,it\'asecret!'
} = process.env

const IN_PROD = NODE_ENV === 'production'

app.use(session({
    name: SESS_NAME,
    resave: false,
    saveUninitialized: false,
    secret: SESS_SECRET,
    store: myStore,
    cookie: {
        maxAge: SESS_LIFETIME,
        sameSite: true,
        secure: IN_PROD
    }
}))

myStore.sync()

app.get('/', (req, res) => {
    res.render('index.hbs')
})

app.get('/profile', (req, res) => {
    if (req.session.userId) {
        User.findOne({
            raw: true,
            where: {
                id: req.session.userId
            }
        })
            .then(user => {
                if (!user) {
                    console.log("Что то пошло не так")
                }
                res.render('profile.hbs', {
                    name: user.username,
                    email: user.email
                })

            })
    } else {
        res.send("Нет сессии")
    }
})

app.get('/login', (req, res) => {
    if (req.session.userId) {
        res.redirect('/profile')
    } else {
        res.render('login.hbs')
    }
})

app.post('/login', (req, res) => {
    User.findOne({
        where: {
            email: req.body.email
        }
    })
        .then(user => {
            if (!user) {
                return res.status(404).send({ message: "Введены неправильные данные!" });
            }
            const passwordIsValid = bcrypt.compareSync(req.body.password, user.password)
            if (!passwordIsValid) {
                return res.status(401).send({
                    message: "Введены неправильные данные!"
                });
            }
            req.session.userId = user.id
        })
})

app.listen(PORT, () => console.log(`http://localhost:${PORT}`))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-07-06
@mrrangerr

If I enter the correct data, first there is a long download. and the error "Page is not available" The site localhost did not send data.

so he doesn’t send anything, then you need to render or redirect something, or send some kind of response to the browser
app.post('/login', (req, res) => {
    User.findOne({
        where: {
            email: req.body.email
        }
    })
        .then(user => {
            if (!user) {
                return res.status(404).send({ message: "Введены неправильные данные!" });
            }
            const passwordIsValid = bcrypt.compareSync(req.body.password, user.password)
            if (!passwordIsValid) {
                return res.status(401).send({
                    message: "Введены неправильные данные!"
                });
            }

            req.session.userId = user.id   // ОК
            // и что дальше?

        })
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question