如何使此身份验证有效?

时间:2019-07-14 01:20:26

标签: node.js express authentication

我是Web开发的新手。我遵循了此指南: https://medium.com/queers-in-tech/server-side-json-web-token-implementation-with-postgresql-and-node-7278eb9dc1b2 但是我没有得到我想要的结果,而我对下一步完全不了解。我希望有人可以帮助我吗?

routes / authentication.js

const express = require("express");
const passport = require('passport')

const Authentication = require('../controllers/authentication')

const requireSignIn = passport.authenticate('local', {session: false})

const router = express.Router()

router.get('/sign-up', (req, res) => {
    res.json({msg: 'Assuming I need a frontend here.'})
    //res.render('authentication/sign-up')
})

router.post('/sign-up', Authentication.signup)

router.get('/sign-in', (req, res) => {
    res.render('authentication/sign-in')
})

router.post('/sign-in', requireSignIn, Authentication.signin)

module.exports = router

controllers / authentication.js

const jwt = require('jwt-simple')
require('dotenv').config();
const {createUser} = require('../actions/signUp')
const bcrypt = require('bcrypt')

const tokenForUser = (user) => {
    const timestamp = new Date().getTime()
    return jwt.encode({sub: user.id, iat: timestamp}, process.env.secret)
}

const signin = (req, res, next) => {
    res.send({ token: tokenForUser(req.user)})
}

const signup = (req, res, next) => {
    const {name, email, password} = req.body
    const saltRounds = 12

    if (!email || !password) {
        res.status(422).send({error: 'You must provide an email and a password.'})
    }
    // see if a user with a given email exists.
    bcrypt.hash(password, saltRounds)
        .then((hash) => {
            return createUser(name, email, hash)
                .then((newUser) => {
                    res.json({token: tokenForUser(newUser)})
                })
                .catch((err) => {
                    res.json({error: 'Error saving user to database.'})
                })
        })
        .catch((err) => {
            return next(err)
        })
}

module.exports = {signup, signin}

actions / signUp.js

const db = require('../config/database');

const createUser = (name, email, password) => {
    const query = `
        INSERT INTO users
        (name, email, password)
        VALUES ($1, $2, $3)
        RETURNING *`
    return db.one(query, [name, email, password])
}

module.exports = {createUser}

server.js的顶部

const express = require('express');
const cors = require('cors');
//const bodyParser = require('body-parser');
const path = require('path');
require('dotenv').config();

// Database
const db = require('./config/database');

// Authentication
//import authentication from './routes/authentication'
const passport = require('passport')
const passportService = require('./services/passport')

const requireAuth = passport.authenticate('jwt', {session: false})

// Test DB 
db.sequelize.authenticate()
    .then(() => console.log('Database connected...'))
    .catch(err => console.log('Error: ' + err))

const app = express();

app.use(cors());

// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', requireAuth, (req, res) => res.send('Nothing to see here'));
app.use('/', require('./routes/authentication'))

我正在使用Postman尝试将名称,电子邮件和密码传递给localhost:3000 / sign-up,然后返回“无法发布/ sign-up /”消息。

在routes / authentication.js中,我已注释掉“ res.render('authentication / sign-up')”,并用一条基本消息替换了它。我收到一个未指定默认引擎的错误,但是我认为这是因为本教程实际上并未详细介绍如何向浏览器呈现任何内容。

有人可以告诉我我做错了什么,以及如何使它按预期方式将数据实际发布到数据库吗?

非常感谢您!

安迪

0 个答案:

没有答案