我正在研究MEAN应用程序,其中我使用本地护照猫鼬作为身份验证。当我使用POSTMAN向其余api端点发送和获取请求时,此应用程序运行良好。但是当我从使用服务的角度传递数据时,passport-local-mongoose身份验证不起作用并给出错误,并且由于此身份验证错误,crud-page.component.ts文件中ngOnInit函数中的getBooks()函数也给出了错误(由于用户身份验证)。我不知道为什么使用Angular无法正常工作。需要帮忙。下面是一个错误:
Error: Authenticated FailedError: Your are not authenticated
at auth (E:\JavaScript\Projects\bookstore\app.ts:86:19)
at Layer.handle [as handle_request] (E:\JavaScript\Projects\bookstore\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (E:\JavaScript\Projects\bookstore\node_modules\express\lib\router\index.js:317:13)
at E:\JavaScript\Projects\bookstore\node_modules\express\lib\router\index.js:284:7
at Function.process_params (E:\JavaScript\Projects\bookstore\node_modules\express\lib\router\index.js:335:12)
at next (E:\JavaScript\Projects\bookstore\node_modules\express\lib\router\index.js:275:10)
at SessionStrategy.strategy.pass (E:\JavaScript\Projects\bookstore\node_modules\passport\lib\middleware\authenticate.js:338:9)
at SessionStrategy.authenticate (E:\JavaScript\Projects\bookstore\node_modules\passport\lib\strategies\session.js:75:10)
at attempt (E:\JavaScript\Projects\bookstore\node_modules\passport\lib\middleware\authenticate.js:361:16)
at authenticate (E:\JavaScript\Projects\bookstore\node_modules\passport\lib\middleware\authenticate.js:362:7)
at Layer.handle [as handle_request] (E:\JavaScript\Projects\bookstore\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (E:\JavaScript\Projects\bookstore\node_modules\express\lib\router\index.js:317:13)
at E:\JavaScript\Projects\bookstore\node_modules\express\lib\router\index.js:284:7
at Function.process_params (E:\JavaScript\Projects\bookstore\node_modules\express\lib\router\index.js:335:12)
at next (E:\JavaScript\Projects\bookstore\node_modules\express\lib\router\index.js:275:10)
at initialize (E:\JavaScript\Projects\bookstore\node_modules\passport\lib\middleware\initialize.js:53:5)
我的app.ts文件
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const usersRouter = require('./routes/users.ts');
// Passport authentication and session
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const cookieParser = require('cookie-parser');
const session = require('express-session');
const FileStore = require('session-file-store')(session);
// const authenticate = require('./authenticate.ts');
// All Routers
const bookRouter = require('./routes/bookRouter.ts');
const indexRouter = require('./routes/indexRouter.ts');
const User = require('./models/registration.ts');
const config = require('./config.ts');
const PORT = 3000;
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
// Express session
// app.use(cookieParser('12345-54321'));
app.use(session({
name: 'session-id',
secret: '12345-54321',
saveUninitialized: false,
resave: false,
store: new FileStore()
}));
// app.use(session({ secret: '12345-54321'}));
// Configure passport middleware
app.use(passport.initialize());
app.use(passport.session());
// app.use(express.static(path.join(__dirname, 'public')));
// Configure passport-local to use account model for authentication
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// Establishing the connection
const url = config.mongoUrl;
const connect = mongoose.connect(url, { useNewUrlParser: true });
connect.then((db) => {
console.log('Connection Successful');
}, (err) => { console.log('Cannot connect to the database bookstore ', err);
});
app.listen(PORT, () => {
console.log('Server started at port: ' + PORT);
});
// Before accessing books router and catching any error
function auth(req, res, next) {
console.log(req.session);
console.log('Req. user ', req.user);
if (!req.user) {
// let authHeader = req.headers.authorization;
// console.log('Auth header is: ', authHeader);
console.log(req);
const err = new Error('Your are not authenticated');
res.status = 403;
err.message = 'Authenticated Failed' + err;
return next(err);
} else {
next();
}
}
app.use('/register', usersRouter);
app.use(auth);
app.use('/books', bookRouter);
app.get('*', function(req, res) {
res.render('error');
console.log('Error occurred');
});
module.exports = app;
// login.component.ts
import { PostService } from './../services/post.service';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-login-page',
templateUrl: './login-page.component.html',
styleUrls: ['./login-page.component.sass']
})
export class LoginPageComponent implements OnInit {
serverErrorMessages: string;
username: string;
constructor(private postService: PostService, private router: Router) { }
goToRegistration() {
this.router.navigateByUrl('register')
.then(value => {
console.log(value);
})
.catch (err => { console.log(err); });
}
onSubmit(form) {
// this.user.firstName = form.value.
console.log('Form ', form);
this.postService.loginForm(form).subscribe(
(res) => {
// this.showSucessMessage = true;
// setTimeout(() => this.showSucessMessage = false, 4000);
// this.resetForm(form);
console.log('Login Component res: ', res.result.response._id);
this.username = res.result.response._id;
console.log('Username is: ', this.username);
this.router.navigate(['crud']);
},
err => {
console.log('Login unsuccessful', err);
if (err.status === 422) {
this.serverErrorMessages = err.error.join('<br/>');
}
else if (err.status === 401) {
console.log('Invalid username or password ');
}
else {
this.serverErrorMessages = 'Something went wrong.Please contact admin.';
console.log(err);
}
},
() => {
console.log('Login successfull completed ');
}
);
}
ngOnInit() {
}
}
// crud-page.component.ts
import { PostService } from './../services/post.service';
import { NgForm } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
import { Book } from './../user.model';
import { Router } from '@angular/router';
import { MatDialog, MatDialogConfig } from '@angular/material';
import { UpdateBookComponent } from '../update-book/update-book.component';
@Component({
selector: 'app-crud-page',
templateUrl: './crud-page.component.html',
styleUrls: ['./crud-page.component.sass']
})
export class CrudPageComponent implements OnInit {
// Structure to send books data to db
book: Book = new Book();
// Array of all books in mongodb database
displayedColumns: string[] = ['position', 'name', 'author1', 'category', 'author2', 'edition', 'language', 'cost', 'isbn', 'actions'];
books: Book[] = [];
onSubmit(book: NgForm) {
console.log(book);
this.postService.createBook(book).subscribe(
res => {
if (res.status === true) {
this.router.navigate(['crud']);
}
else
{
console.log('If function not working');
}
},
err => {
console.log('onCreate Error: ', err);
},
() => {
this.ngOnInit();
console.log('Successfully added book');
}
);
}
// Update Book
onUpdate(book) {
// Passing data using data property
console.log('Update: ', book);
this.dialog.open(UpdateBookComponent, {
data: book
});
console.log('After Dialog');
}
// Delete Book
onDelete(event) {
console.log(event._id);
this.postService.deleteBook(event._id).subscribe(
res => {
console.log('Deleted Book ', res);
},
err => {
console.log('onDelete Error: ', err);
},
() => {
this.ngOnInit();
console.log('Deleted');
}
);
}
constructor(private postService: PostService, private router: Router, private dialog: MatDialog) {}
ngOnInit() {
this.postService.getBooks().subscribe(
(res: any) => {
console.log('Res ', res);
this.books = res.response;
console.log('Lenght: ', this.books.length);
},
error => {
console.log('Error ', error);
},
() => {
console.log('Fetched all the books ');
}
);
}
}
// post.service.ts
import { User } from './../user.model';
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError, pipe } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { RENDER_FLAGS } from '@angular/compiler/src/render3/view/util';
@Injectable({
providedIn: 'root'
})
export class PostService {
uri = 'http://localhost:3000';
private isAuthenticated = false;
constructor(private http: HttpClient) { }
getBooks() {
return this.http.get(this.uri + '/books')
.pipe(
map((res: Response) => {
console.log('Books: ', res);
return { success: true, response: res };
}),
catchError((error) => {
return throwError(error);
})
);
}
deleteBook(bookId: number): Observable<any> {
// const result: Observable<any> = this.http.delete<any>(this.uri + id);
// return result;
return this.http.delete(this.uri + '/books/' + bookId)
.pipe(
map((res: Response) => {
return { status: true };
}),
catchError((error) => {
return throwError(error);
})
);
}
createBook(book) {
return this.http.post(this.uri + '/books/', book)
.pipe(
map((res: Response) => {
console.log('Response: ', res);
return { status: true };
}),
catchError((error) => {
return throwError(error);
})
);
}
updateBook(book) {
console.log('Post Service updateBook: ', book);
return this.http.put(this.uri + '/books/' + book._id, book)
.pipe(
map((res: Response) => {
return { status: true };
}),
catchError((error) => {
return throwError(error);
})
)
}
postUser(user: User): Observable<any> {
console.log('User available', user);
const authData: User = {
firstName: user.firstName, lastName: user.lastName, email: user.email, username: user.username, gender: user.gender,
password: user.password, contactNumber: user.contactNumber, dateOfBirth: user.dateOfBirth, city: user.city,
state: user.state, pinCode: user.pinCode };
return this.http.post(this.uri + '/register', authData)
.pipe(
map((res: Response) => {
console.log('Response: ', res);
return { status: res.status };
}),
catchError(error => {
console.log('Error in catchError: ', error);
return throwError(error);
})
);
}
//
getIsAuth() {
return this.isAuthenticated;
}
// Login Form Service
loginForm(form): Observable<any> {
console.log('Form value: ', form);
return this.http.post(this.uri + '/register/login', form)
.pipe(
map(
(res: Response) => {
// Do not use res.json(). It wil give error. Please Don't
console.log('Login Request ', res);
this.isAuthenticated = true;
return { success: true, result: res };
}
),
catchError(err => {
console.error('Unauthorized user ', err.message);
return throwError(err);
})
);
}
}
// users.ts文件
const User = require('../models/registration.ts');
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
// For authenticating
const passport = require('passport');
router.use(bodyParser.json());
router.post('/', function(req, res, next) {
console.log('Request in express route ', req.body);
User.register(new User({ username: req.body.username, firstName: req.body.firstName, lastName: req.body.lastName,
email: req.body.email, city: req.body.city, contactNumber: req.body.phoneNumber, state: req.body.state,
pinCode: req.body.pinCode, gender: req.body.gender }), req.body.password, (error, user) => {
if (error) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
console.log('Error occurred', error);
res.json({ error: error });
}
else {
passport.authenticate('local')(req, res, () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
console.log('User got it: ', user);
res.json({ success: true, status: true });
// res.redirect('/');
});
}
});
});
router.post('/login', passport.authenticate('local'), (req, res) => {
// Creating a token
// var token = authenticate.getToken({ _id: req.user._id });
console.log('In Users.ts Req.user is: ', req.user);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
console.log('Successful');
res.json({ success: true, response: req.user });
});
/* router.get('/logout', (req, res, next) => {
if (req.session) {
req.logout();
req.session.destroy();
res.clearCookie('session-id');
res.redirect('/');
// this.router.navigate(['login']);
} else {
let err = new Error('You are not logged in!');
res.status = 403;
next(err);
}
}); */
module.exports = router;