Angular auth.guard no persisten auth

时间:2017-11-20 14:06:59

标签: javascript angular firebase firebase-authentication angularfire

刷新页面后,身份验证似乎不会持续存在。每当我登录时,它都成功地重定向了我。但是,当我刷新时,再也无法访问了。

这是认证警卫

路由器

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavComponent } from './components/nav/nav.component';
import { HomeComponent } from './components/home/home.component';
import { GalleryComponent } from './components/gallery/gallery.component';
import { FooterComponent } from './components/footer/footer.component';

import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireDatabaseModule, AngularFireDatabase } from 'angularfire2/database';
import { FIREBASECONFIG as firebaseConfig } from './config/firebase-config';

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { ScrollToModule } from 'ng2-scroll-to';
import { NgxCarouselModule } from 'ngx-carousel';
import { AnimateOnScrollModule } from 'ng2-animate-on-scroll';

import { AuthService } from './services/auth.service';
import { AuthGuard } from './services/auth.guard.service';

import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';


const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'gallery', component: GalleryComponent, canActivate: [AuthGuard] }
];

@NgModule({
  declarations: [
    AppComponent,
    NavComponent,
    HomeComponent,
    GalleryComponent,
    FooterComponent,
  ],
  imports: [
    FormsModule,
    BrowserModule,
    AppRoutingModule,
    NgxCarouselModule,
    NgbModule.forRoot(),
    ScrollToModule.forRoot(),
    RouterModule.forRoot(routes),
    AnimateOnScrollModule.forRoot(),
    HttpClientModule,
    AngularFireModule.initializeApp(firebaseConfig),
    AngularFireAuthModule,
    AngularFireDatabaseModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  exports: [
    TranslateModule
  ],
  providers: [AngularFireDatabase, AuthService, AuthGuard],
  bootstrap: [AppComponent]
})

auth.guard.ts

import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import { AngularFireAuth } from 'angularfire2/auth';
import { Injectable, OnInit } from '@angular/core';
import { CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
  public user = null;
  constructor(private fireauth: AngularFireAuth, private router: Router) {
    this.fireauth.auth.onAuthStateChanged((user) => {
      if (user) {
        this.user = this.fireauth.auth.currentUser;
      }
    });
  }

  ongOnInit() {
  }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
    if (this.user) {
      return true;
    } else {
      this.router.navigate(['']);
      return false;
    }
  }
}

根据我的路线是可以的,我认为问题最多的是auth后卫,我猜。

1 个答案:

答案 0 :(得分:4)

试试此代码

const express = require('express');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const path = require('path');
const nodemailer = require('nodemailer');

const app = express();

// View engine setup
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

// Static folder
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/', express.static(path.join(__dirname, '')));

// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/', (req, res) => {
  res.render('contact');
});

app.post('/send', (req, res) => {
  const output = `
      <li>Name: ${req.body.name}</li>
      <li>Email: ${req.body.email}</li>
      <li>Phone: ${req.body.phone}</li>
    <p>${req.body.message}</p>
  `;

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    service: 'gmail',
    port: 25,
    secure: false, // true for 465, false for other ports
    auth: {
        user: 'EMAIL', // senders email
        pass: 'PASSWORD' // senders email password
    },
    tls:{
      rejectUnauthorized:false
    }
  });

  // setup email data with unicode symbols
  let mailOptions = {
      from: '"xyz Team" <xyz@info.com>', // sender address
      to: req.body.email, // receiver or receivers
      subject: 'xyz Support', // Subject line
      html: output // html body
  };

  // send mail with defined transport object
  transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
          return console.log(error);
      }
      console.log('Message sent: %s', info.messageId);   
      console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));

      res.render('contact', {msg:'message.'});
  });
  });

app.listen(3000, () => console.log('Server started...'));

我认为constructor( private router:Router, public fireauth:AngularFireAuth ){} canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> { return this.fireauth.authState.map((auth) => { if(auth == null) { this.router.navigate(['/']); return false; } else { return true; } }); } 在旧版本中使用