如何设置MEVN堆栈登录身份验证

时间:2019-09-18 20:43:50

标签: node.js mongodb express vue.js vuex

我正在使用Vue.js,Node,Express和MongoDB构建注册/登录身份验证界面。到目前为止,我已经成功设置了Register.vue组件,以将电子邮件和密码输入到MongoDB数据库中,并使用bcrypt软件包对密码进行了加密。我现在正尝试在users.post('/login', (req, res) => {}中设置users.js路由,以便将存储在mongoDB中的密码和电子邮件与登录页面中输入的密码和电子邮件进行比较。然后,我希望将有效负载分配给token,然后将该令牌传递给localStorage(请参见store.js)。

为此,我添加了一条路由users.get('/allUsers', (req, res) => {}来处理存储数据的请求和响应,但是不确定如何设置users.post('/login', (req, res) => {}以便将存储的数据与存储的数据进行比较。在Login.vue中输入了数据以便登录。

关于如何实现此目标的任何建议?谢谢!我的代码如下:

Login.vue

<template lang="html">
  <v-container>
    <v-form
      @submit.prevent="login()"
    >
      <v-text-field
        v-model="email"
        label="E-mail"
        required
      ></v-text-field>

      <v-text-field
        v-model="password"
        type="password"
        label="Password"
        required
      ></v-text-field>

      <v-btn type="submit" color="primary">Login</v-btn>
    </v-form>
  </v-container>
</template>

<script>
import axios from 'axios'
export default {
  data() {
    return {
      email: "",
      password: ""
    }
  },
  methods: {
    async login() {
      await axios.post('http://localhost:5000/users/login', {
        email: this.email,
        password: this.password
      })
      await this.$store.dispatch("login")
      this.$router.push('/')
    }
  }
}
</script>

<style lang="css" scoped>
</style>

users.js

const express = require("express")
const users = express.Router()
const cors = require("cors")
const jwt = require("jsonwebtoken")
const bcrypt = require("bcrypt")

const User = require("../models/User")
users.use(cors())

process.env.SECRET_KEY = 'secret'

users.get("/allUsers", (req, res) => {
  User.find({}, 'email password', function (error, newData) {
    if (error) { console.error(error); }
    res.send({
      newData: newData
    })
  })
})

users.post("/register", (req, res) => {
  const today = new Date()
  const userData = {
    email: req.body.email,
    password: req.body.password,
    created: today
  }
  User.findOne({
    email: req.body.email
  })
  .then(user => {
    if (!user) {
      bcrypt.hash(req.body.password, 10, (err, hash) => {
        userData.password = hash
        User.create(userData)
        .then(user => {
          res.json({ status: user.email + ' registered' })
        })
        .catch(err => {
          res.send('error: ' + err)
        })
      })
    } else {
      res.json({ error: 'User already exists' })
    }
  })
  .catch(err => {
    res.send('error: ' + err)
  })
})

users.post('/login', (req, res) => {
  User.findOne({
    email: req.body.email,
  })
  .then(user => {
    if (user) {
      if (bcrypt.compareSync(req.body.password, user.password)) {
        const payload = {
          _id: user._id,
          email: user.email
        }
        let token = jwt.sign(payload, process.env.SECRET_KEY, {
          expiresIn: 1440
        })
        res.send(token)
      } else {
        res.json({ error: 'User does not exist' })
      }
    } else {
      res.json({ error: 'User does not exist' })
    }
  })
  .catch(err => {
    res.send('error: ' + err)
  })
})

module.exports = users

store.js

import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const LOGIN = "LOGIN";
const LOGIN_SUCCESS = "LOGIN_SUCCESS";
const LOGOUT = "LOGOUT";

export default new Vuex.Store({
  state: {
    isLoggedIn: localStorage.getItem("token")
  },
  mutations: {
    [LOGIN](state) {
      state.pending = true;
    },
    [LOGIN_SUCCESS](state) {
      state.isLoggedIn = true;
      state.pending = false;
    },
    [LOGOUT](state) {
      state.isLoggedIn = false;
    }
  },
  actions: {
    async login({
      commit
    }) {
      let result = await axios.get('http://localhost:5000/users/allUsers')
      localStorage.setItem('token', result.data.newData)
      commit(LOGIN); // show spinner
      return new Promise(resolve => {
        setTimeout(() => {
          commit(LOGIN_SUCCESS);
          resolve();
        }, 1000);
      });
    },
    logout({
      commit
    }) {
      localStorage.removeItem("token");
      commit(LOGOUT);
    }
  }
})

0 个答案:

没有答案