登录用户,其凭据存储在mongo数据库节点&express

时间:2018-12-02 05:13:26

标签: node.js angular mongodb express passport.js

我一直在尝试许多方法,使用Passport中间件使我对这项任务的了解最远。我认为我缺少最后一步才能正常运行,现在没有错误。这是我的代码:

我有一个login.component.html

<form method="POST" action="login">
  Username: <input type="text" name="username" required>
  Password: <input type="text" name="password" required>
  <input type="submit" value="Submit">
</form>

用户模型:

var mongoose = require('mongoose');
const express = require('express');
const bodyParser = require('body-parser');
var app = express();

const Schema = mongoose.Schema;

let user = new Schema({
    username: String,
    password: String
});


const User = module.exports = mongoose.model('User', user);

用户路线:

const express = require('express');
const router = express.Router();
const passport = require('passport');


let User = require('../models/user');

//Login form
router.get('/login', function(req, res)
{
    res.render('login');
})

//Login process
router.post('/login', function(req, res, next)
{
    passport.authenticate('local',
    {
        successRedirect: '/admin',
        failureRedirect: '/login',
        failureFlash: true
    })(req,res,next);
});

module.exports = router;

Passport.js

const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user');
const config = require('../config/db');
const bcrypt = require('bcryptjs'); 

module.exports = function(passport)
{
    passport.use(new LocalStrategy(function(username, password, done)
    {
        let query = {username:username};
        User.findOne(query, function(err, User)
        {
            if(err) throw err;

            if(!User)
            {
                return done(null, false, {message: 'No user found'});
            }

            bcrypt.compare(password, User.password, function(err, isMatch)
            {
                if(err) throw err;

                if(isMatch)
                {
                    return done(null, User);
                }
                else
                {
                    return done(null, false, {message: 'Wrong pass'});
                }
            });

        }); 
    }));

    passport.serializeUser(function(User,done)
    {
        done(null, User.id);
    });

    passport.deserializeUser(function(id, done)
    {
        User.findById(id, function(err, User)
        {
            done(err, User);
        });
    });
}

我已经为此工作了几个小时,但无济于事。如果有人可以给我一些帮助或在下一步中指出我的想法,以使其正常工作,那就太好了。

我觉得我缺少了一些东西,但不确定是什么。我还没有更改我的login.component.ts中的任何代码,这可能是代码没有执行我想要的操作的原因。

在这里login.component.ts:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';



@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {


  constructor(private router: Router, ) {
   }

  ngOnInit() {
  }

}

1 个答案:

答案 0 :(得分:1)

在用户路线上,如果要从Angular应用程序的POST /登录中订阅并使用其响应作为以后的参考,则无需重定向即可直接返回它的响应

用户路线:

//Login process
router.post('/login', function(req, res, next)
{
    passport.authenticate("local", (err, user, info) => {
        if (err) return next(err);
        if (!user) return res.status(404).json('No user found');   // Or err.message / err.info depends on the passed error message you had set

        req.logIn(user, err => {
           if (err) next(err);
           else res.status(200).json(user);     // Return user object from successfully fetched passport user auth
        });
   })(req, res, next);
});

用户服务:

  signIn(credentials: any): Observable<any> {
    return this.http
       .post('http://localhost:3000/auth/login', credentials)   // Or any url you had set.
       .map((response: any) => response);
  }

登录组件

login(credentials: any): void {       // You can either pass credentials or not as you can also access it inside your component with 'this.form.value'
   this.userService
      .signIn(credentials)
      .subscribe(
         response => {
            localStorage.setItem("user", JSON.stringify(user));  // Optional; Store your user/token response on the localStorage for future reference.
             this.router.navigate([ "/home" ]);                  // Navigate to the next page after user is authenticated
         },
      error => console.error(error)
      );
}