MEVN认证

时间:2018-10-22 15:39:35

标签: node.js express vuejs2 passport.js

好的,所以我已经看了一段时间了。我正在尝试通过护照本地身份验证设置一个简单的MEVN堆栈样板。当仅运行端口8081时,这在我的生产版本上起作用,但这对开发非常不方便。

如果我在8080上启动客户端,在8081上启动服务器,则身份验证有效,我可以注册用户并登录,但是current_user函数不起作用。我在使用isAuthenticated的isLoggedIn失败,它总是错误的。我查看了与此相关的其他讨论,并认为这是一个cors问题,但是找不到有效的设置。我也查看过cookie,但不确定最佳设置。我正在看几个教程,他们只是去运行NPM构建并使用生产构建,但是每次您对Vue组件进行更改时,构建它似乎都是一件很痛苦的事情。我还尝试了webpack的代理设置,但似乎也没有任何改变。

server.js

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const morgan = require('morgan');
const fs = require('fs');
const config = require('./config/Config');
const session = require('express-session');
// const cookieSession = require('cookie-session')
const passport = require('passport');
const app = express();
const router = express.Router();
const serveStatic = require('serve-static');
const history = require('connect-history-api-fallback');

app.use(morgan('combined'));
app.use(bodyParser.json());
// app.use(cookieSession({  
//   name: 'mysession',
//   keys: ['vueauthrandomkey'],
//   maxAge: 24 * 60 * 60 * 1000 // 24 hours
// }))
app.use(cors())

app.use(session({
    secret: config.SECRET,
    resave: true,
    saveUninitialized: true,
    cookie: { httpOnly: false }
  }))
app.use(passport.initialize());
app.use(passport.session());

//connect to mongodb
mongoose.connect(config.DB, { useMongoClient: true }, () => {
  console.log('Connection has been made');
})
.catch(err => {
  console.error('App starting error:', err.stack);
  process.exit(1);
});

// Include controllers
fs.readdirSync("controllers").forEach(function (file) {
    if(file.substr(-3) == ".js") {
      const route = require("./controllers/" + file)
      route.controller(app)
    }
  })

app.use(history());
app.use(serveStatic(__dirname + "/dist"));

router.get('/api/current_user', isLoggedIn, function(req, res) {
    console.log(req.user);
    if(req.user) {
      res.send({ current_user: req.user })
    } else {
      res.status(403).send({ success: false, msg: 'Unauthorized.' });
    }
  })

  function isLoggedIn(req, res, next) {
    console.log(req.isAuthenticated());
    if (req.isAuthenticated())
      return next();

    res.redirect('/');
    console.log('error! auth failed')
  }

router.get('/api/logout', function(req, res){
    req.logout();
    res.send();
  });
router.get('/', function(req, res) {
  res.json({ message: 'API Initialized!'});
});

const port = process.env.API_PORT || 8081;
app.use('/', router);
app.listen(port, function() {
  console.log(`api running on port ${port}`);
});

login.vue

<template>
<v-container>
  <v-form v-model="valid" ref="form" lazy-validation>
    <v-text-field
      label="Email"
      v-model="user.email"
      :rules="emailRules"
      required
    ></v-text-field>
    <v-text-field
      label="Password"
      v-model="user.password"
      required
    ></v-text-field>
    <v-btn
      @click="submit"
      :disabled="!valid"
    >
      submit
    </v-btn>
    <v-btn @click="clear">clear</v-btn>
  </v-form>
  </v-container>
</template>
<script>
import { http } from '@/config/http.js'
import axios from 'axios'
import bus from '@/bus'

export default {
  data: () => ({
    valid: true,
    user: {
        email: '',
        password: '',
    },
    emailRules: [
      v => !!v || 'E-mail is required',
      v => /\S+@\S+\.\S+/.test(v) || 'E-mail must be valid',
    ],
  }),
  methods: {
    submit() {
      http
        .post("/users/login/", this.user, {'headers': {'Content-Type': 'application/json'}})
        .then((response) => {
            this.$swal('Great!', 'You are ready to start!', 'success');
            bus.$emit('refreshUser');
            this.$router.push({ name: 'Home' });
        })
        .catch((error) => {
            const message = error.response.data.message;
            this.$swal('Oh oo!', `${message}`, 'error');
            this.$router.push({ name: 'login' });
        });
        },
      clear() {
      this.$refs.form.reset();
    },
  },
};
</script>

App.vue

<template>
  <div id="app">
    <h1 v-if="current_user">Current User {{ current_user.name }}</h1>
    <h1 v-else>Please Login or Register</h1>
    <!-- <img src="./assets/logo.png"> -->
    <router-view/>
  </div>
</template>

<script>
import './assets/stylesheets/main.css';
import axios from 'axios';
import bus from '@/bus';
import { http } from './config/http';


export default {
  name: 'App',
  data: () => ({
    current_user: null,
  }),
    mounted() {
    this.fetchUser();
    this.listenToEvents();
  },
  methods: {
    listenToEvents() {
      bus.$on('refreshUser', () => {
        this.fetchUser();
      });
    },
    async fetchUser() {
      http
      .get('/api/current_user/')
      .then((response) => {
        this.current_user = response.data.current_user;
      })
      .catch(() => {
      });
    },
  }
}
</script>

<style>

</style>

0 个答案:

没有答案