2017-11-09 1 views
0

나는 PassportJS를 통해 클라이언트 쪽 Angular app에 대한 액세스를 제한하려고합니다.평균 - NodeJS 경로를 초과하는 각도의 경로

기본적으로 로그인 할 인증 공급자로 리디렉션하기 위해 앱에 액세스하려는 모든 사용자를 라우팅하려고합니다. 그러나 각도 경로가 NodeJS Express 경로보다 우선합니다.

그래서 '/'로 이동하면 각도 앱을로드하고 리디렉션하지 않습니다. 각도 경로와 동일한 경로를 사용하는 모든 경로에 대해 동일한 경우입니다.

server.js는 니펫을 :

다음 코드는 페이스 북에 로그인하는 모든 사람을 리디렉션합니다. 대신 각도 색인 페이지를로드합니다.

function checkAuthentication(req,res,next){ 
    if(req.isAuthenticated()){ 
     //if user is looged in, req.isAuthenticated() will return true 
     console.log("/ " + true); 
     res.sendFile(path.join(__dirname, 'dist/index.html')); 
    } else{ 
     console.log("/ " + false); 
     res.redirect("/api/passport/login/facebook"); 
    } 
} 

app.get('/*', checkAuthentication ,(req, res) => { 
}); 

각도 index.html을 조각은 : 명시 라우터에 표시되는

index.html 페이지가 같은 경로를 사용합니다.

<base href="/"> 

의 난 '/ 응용 프로그램 /'과 같이 사용할 수있는 index.html을의 기본 href 변경한다고 가정 해 봅시다 : 로그인 한 사용자 리디렉션

<base href="/app/"> 

및 표현에 라우팅 설정에 '/ 응용 프로그램/'그래서 같은 :

angular.route 예 :

app.use("/app", express.static(path.join(__dirname, 'dist'))); 

function checkAuthentication(req,res,next){ 
    if(req.isAuthenticated()){ 
     //if user is looged in, req.isAuthenticated() will return true 
     console.log("/app" + true); 
     res.sendFile(path.join(__dirname, '../../dist/index.html')); 
    } else{ 
     console.log("/app" + false); 
     res.redirect("/api/passport/login/facebook"); 
    } 
} 

router.get('/app', checkAuthentication, (req, res) => { 
    console.log("approuter hit"); 
}); 

module.exports = router; 

및 이동'직접/응용 프로그램 '. 앵귤러 index.html 페이지를로드하고 로그인 할 리디렉션하지 않습니다. 그러나 '/'로 이동하면 로그인 할 수있게됩니다.

내 NodeJS 익스프레스의 오버 라이딩을 어떻게 중지합니까? 노선?

UPDATE :

app.route.js는 니펫을 :

import { Routes } from '@angular/router'; 
import { HomeComponent } from './home'; 

export const ROUTES: Routes = [ 
    { path: '',  component: HomeComponent }, 
]; 
+0

의사 소통? –

+0

@mohituprim 각도 경로의 관련 부분을 포함했습니다. 너가 완전한 것을 필요로하면 다만 묻으 십시요. –

답변

2

당신은 AuthGuard와 클라이언트 사이의 의사 소통 역할을 클라이언트 측에서 인증 서비스 (즉, 각도)를 구현해야 섬기는 사람. isAuthenticated와 같은 변수를 유지하여 로그인 상태를 추적하십시오.

AuthGuard :

import { Injectable }  from '@angular/core'; 
import { CanActivate, CanActivateChild, Router } from '@angular/router'; 

import { AuthenticationService } from './auth.service'; 

@Injectable() 
export class AuthGuard implements CanActivate, CanActivateChild { 

    constructor(private authService: AuthenticationService, private router: Router) {} 
    canActivate() : boolean { 
     console.log('AuthGuard#canActivate called ' + this.authService.isAuthenticated); 
     return this.checkLoggedIn("random"); 
    } 

    canActivateChild() : boolean { 
     return this.canActivate(); 
    } 

    checkLoggedIn(url: string): boolean { 
     if (this.authService.isLoggedIn()) { 
      return true; 
     } 
     this.authService.redirectUrl = url; 
     this.router.navigate(['/login']); 
     return false; 
    } 

} 

AuthenticationService :

import { Injectable } from '@angular/core'; 
import { Router } from '@angular/router'; 
import { Http, Response, Headers, RequestOptions } from '@angular/http'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch'; 
import { Observable } from 'rxjs/Rx'; 
import { NgForm } from "@angular/forms"; 

import { AuthenticationApi } from "../../modules/authentication/authentication-api"; 
import { IUser } from "app/modules/authentication/user"; 
var headers = new Headers({ 'Content-Type': 'application/json' }); 
var options = new RequestOptions({ headers: headers }); 

@Injectable() 
export class AuthenticationService implements AuthenticationApi { 
    currentUser: IUser; 
    redirectUrl: string; 
    changePassoword:() => Observable<any>; 
    forgotPassowrd:() => Observable<any>; 

    isAuthenticated = false; 
    constructor(private router: Router, private http: Http) { 
    this.currentUser = null 
    } 

    isLoggedIn(): boolean { 
    return !!this.currentUser; 
    } 

    logIn(logInUser:any): Observable<any> { 
    console.log('UserService.signIn: ' + logInUser.userName + ' ' + logInUser.password + ' ' + logInUser.rememberMe); 
    this.isAuthenticated = true; 
    this.currentUser = { 
     userName: logInUser.userName 
    } 
    return this.http.post('http://localhost:3000/auth/login', 
     JSON.stringify(logInUser), 
     options 
    ) 
    .map((resp: Response) => resp.json()) 
    .catch(this.handleError); 
    //return Observable.of({}).delay(2000); 
    // return Observable.of({}).delay(2000).flatMap(x=>Observable.throw('Invalid User Name and/or Password')); 
    } 

    register(registerUser:any): Observable<any> { 
    this.isAuthenticated = true; 
    console.log(registerUser); 
    return this.http.post('http://localhost:3000/auth/register', 
     JSON.stringify(registerUser), 
     options 
    ) 
    .map((resp: Response) => resp.json()) 
    .catch(this.handleError); 
     //this.router.navigate(['/signin']); 
     //return Observable.of({}).delay(2000); 
    } 

    connectWithFacebook() :Observable<any> { 
    this.isAuthenticated = true; 
    //return Observable.of({}).delay(2000); 
    return this.http.get('http://localhost:3000/auth/facebook') 
    .map((resp: Response) => resp.json()) 
    .catch(this.handleError); 
    } 

    connectWithGoogle() :Observable<any> { 
    this.isAuthenticated = true; 
    //return Observable.of({}).delay(2000); 
    return this.http.get('http://localhost:3000/auth/google') 
    .map((resp: Response) => resp.json()) 
    .catch(this.handleError); 
    } 

    handleError(error: any) { 
    console.error(error); 
    return Observable.throw(error.json().error || 'Server error'); 
    } 

    logOut(): Observable<any>{ 
    this.isAuthenticated = false; 
    this.currentUser = null; 
    this.router.navigate(['/login']); 
    return Observable.of({}) 
    } 

} 

AuthenticationApi : 일반적인 방법은 먼저 각 경로의 세부 사항을 게시 할 수

import { Observable } from 'rxjs'; 

export abstract class AuthenticationApi { 
    logIn : (loginUser:any) => Observable<any>; 
    logOut :() => Observable<any>; 
    register : (registerUser:any) => Observable<any>; 
    connectWithFacebook :() => Observable<any>; 
    connectWithGoogle :() => Observable<any>; 
    changePassoword :() => Observable<any>; 
    forgotPassowrd :() => Observable<any>; 
} 
+0

인증 가드 사용이 작동하는 것 같습니다! –

관련 문제