登录成功后,不会重定向到主页,Authguard表示登录失败的平均值2



所以在这里我尝试登录时有一个均值的2个auth应用程序说登录成功,但它不会导航到主页,并说请先从authguard

登录。

这是我的登录组件html

<div class="d-flex justify-content-center align-items-center height-full">
<md-card class="force-login-wrapper align-self-center text-center">
    <div>
        <div>
            <div class="login-logo justify-content">
                <img src="assets/img/logo.svg" class="mb-4">
                <p>Please enter your user information</p>
            </div>
        </div>
        <form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
            <div>
                <md-input-container class="mggn-b-po full-wid">
                    <input #userEmail mdInput placeholder="E-Mail" type="text" formControlName="email">
                </md-input-container>
                <div [hidden]="email.valid || email.pristine" class="alert alert-danger">Please enter a valid email format</div>
                <md-input-container class="mggn-b-po full-wid">
                    <input mdInput placeholder="Password" type="password" formControlName="password">
                </md-input-container>
                <div [hidden]="password.valid || password.pristine" class="alert alert-danger">Password must contain 6 or more characters</div>
                <!-- <div class="row">
                    <div class="col-md-6">
                        <md-checkbox class="remember-me">Remember Me</md-checkbox>
                    </div>
                </div> -->
                <div>
                    <button class="bg-primary btn-block mb-12" md-raised-button type="submit" [disabled]="!myForm.valid">SIGN IN</button>
                </div>
                <div style="margin-top: 20px">
                    <a [routerLink]="['/forgot-password']">Forgot Password?</a>
                    <p>Don't have an account? <a [routerLink]="['/register']" class="mat-text-primary">Click here to create one</a></p>
                </div>
            </div>
        </form>
    </div>
</md-card>

**这是登录组件TS **

 "use strict";
import { Component, OnInit ,ViewEncapsulation, AfterViewInit, ViewChild, ElementRef, Renderer} from '@angular/core';
import { Router } from "@angular/router";
import { ReactiveFormsModule, FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
import {AuthService} from '../../auth/auth.service';
import {ToastsManager} from 'ng2-toastr';
import {User} from '../../auth/user.model';
@Component({
   selector: 'ms-login-session',
   templateUrl:'./login-component.html',
   styleUrls: ['./login-component.scss'],
   encapsulation: ViewEncapsulation.None,
})
export class LoginComponent implements OnInit, AfterViewInit {
  myForm: FormGroup;
  email: FormControl;
  userId: string;
  password: FormControl;
  @ViewChild('userEmail') userEmail: ElementRef;
  constructor(
   private fb: FormBuilder,
   private authService: AuthService,
   private router: Router,
   private toastr: ToastsManager, 
   private renderer: Renderer
  ) { }
  ngOnInit() {
    this.email    = new FormControl('', [Validators.required, this.emailValidator]);
    this.password = new FormControl('', [Validators.required, Validators.minLength(6)]);
    this.myForm = this.fb.group({
      email   : this.email,
      password: this.password
    });
    // check if the user is logged in while trying to access the login page, if the user is logged in, we redirect him to the form page
    if (this.authService.isLoggedIn()) {
      this.toastr.info('You are already logged in');
      this.router.navigate(['/']);
    }
  }
  ngAfterViewInit() {
    setTimeout(() => {
      this.renderer.invokeElementMethod(this.userEmail.nativeElement, 'focus', []);
    }, 50);
  }
   // submit the login form with the user credentials and navigate the user to the index page of our app
  onSubmit() {
    const user = new User(this.myForm.value.email, this.myForm.value.password);
    this.authService.signin(user)
      .subscribe(
        data => {
          // if the user credentials are correct, set the localStorage token and userId,
          // we need these info in order to do stuff later when the user is signed in and verified
          localStorage.setItem('id_token', data.token);
          localStorage.setItem('userId', data.user._id);
          localStorage.setItem('email', data.user.email);
          localStorage.setItem('role', data.user.role[0]);
          // navigate user to index page of our app
          this.router.navigate(['/']);
          // display toastr success message pop up to inform the user that he logged in successfully
          this.toastr.success('You have been logged in!');
        },
        error => console.log(error)
      );
  }
  // input validator to check if the email entered by the user is actually text in an email form
  emailValidator(control) {
    let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
    if (!EMAIL_REGEXP.test(control.value)) {
      return {invalidEmail: true};
    }
  }
}

这是Authguard,也许这是导致其在登录后不会重定向到主页的问题

import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs';
import {AuthService} from './auth.service';
import {ToastsManager} from 'ng2-toastr';
@Injectable()
export class AuthGuardService implements CanActivate {
  constructor(private authService: AuthService, private router: Router, private toastr: ToastsManager) {
  }
  // we check if the user is logged in or not
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
    // user is actually logged in
    if (this.authService.isLoggedIn()) {
      return true;
      // user is not logged in, return the user to the login page
    } else {
      this.router.navigate(['/login']);
      this.toastr.error('Please login first');
    }
  }
}

这是Auth Service

import {Injectable} from '@angular/core';
import {Headers, Response} from '@angular/http';
import {User} from './user.model';
import {Observable} from 'rxjs';
import 'rxjs/operator/map';
import 'rxjs/operator/catch';
import {ToastsManager} from 'ng2-toastr';
import {ErrorService} from '../errorHandler/error.service';
import {Reset} from './password.model';
import {AuthHttp, tokenNotExpired} from 'angular2-jwt';
import {AUTH_API_URL} from '../config/config';
@Injectable()
export class AuthService {
  constructor(private authHttp: AuthHttp, private errorService: ErrorService, private toastr: ToastsManager) {
  }
// sending request to back end to login the user
  signin(user: User) {
    const body    = JSON.stringify(user);
    const headers = new Headers({
      'Access-Control-Request-Origin': 'http://localhost:3000',
      'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
      'Access-Control-Allow-Methods': 'GET, PUT, POST, PATCH, DELETE, OPTIONS',
      'Content-Type': 'application/json'});
    return this.authHttp.post(`${AUTH_API_URL}/login`, body, {headers: headers})
      .map((response: Response) => response.json())
      .catch((error: Response) => {
        this.errorService.handleError(error.json());
        return Observable.throw(error.json());
      });
  }
 logout() {
    localStorage.clear();
    this.toastr.info('You have been logged out');
  }
  // check if the user is logged in or not, if token is expired, token is deleted from localstorage
  isLoggedIn() {
    if (!tokenNotExpired()) {
      localStorage.clear();
    }
    return tokenNotExpired();
  }
}

这是路由模块

"use strict";
import { NgModule, ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MainComponent }   from './main/main.component';
import { DashboardComponent }  from './dashboard/dashboard-v1/dashboard.component';
import { AddappComponent } from './myapp/addapp/addapp.component'
import { AddbookComponent } from './mybook/addbook/addbook.component';
import { MymediaComponent } from './mymedia/mymedia.component';
import { MybookComponent } from './mybook/mybook.component';
import { MyappComponent } from './myapp/myapp.component';
import { LoginComponent }  from './session/login/login.component';
import { AdminLoginComponent } from './admin/login/login.component';
import { RegisterComponent }  from './session/register/register.component';
import { ForgotPasswordComponent }  from './session/forgot-password/forgot-password.component';
import { LockScreenComponent }  from './session/lockscreen/lockscreen.component';
import { AdminComponent } from './admin/admin.component';
import { AdminGuard } from './core/auth/adminlogin.guard'
import {AuthGuardService} from './auth/authguard.service';
const appRoutes: Routes = [
    {   
        path: 'login',
        component: LoginComponent,
    },{ 
        path: 'register',
        component: RegisterComponent,
    },{ 
        path: 'forgot-password',
        component: ForgotPasswordComponent,
    },{ 
        path: 'lockscreen',
        component: LockScreenComponent,
    },{
        path: 'adminlogin',
        component: AdminLoginComponent
    },{
         path: 'admin', 
         component:AdminComponent, 
         canActivate: [AdminGuard] 
    },{
        path: '',
        component: MainComponent,
        canActivate: [AuthGuardService],
        pathMatch: 'full', 
        children: [
            { path: '', component: DashboardComponent },
            { path: 'dashboard', component: DashboardComponent },
            { path: 'myapps', component:MyappComponent },
            { path: 'myapps/addapp', component:AddappComponent },
            { path: 'mybooks', component:MybookComponent },
            { path: 'mybooks/addbook', component:AddbookComponent },
            { path: 'mymedia', component:MymediaComponent },
        ]
    },{ 
        path: '**',
        redirectTo: "dragndrop/dragula"
    }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

我想像路由模块一样使登录成功并重定向到主页

但是,当我从后端获得成功并显示成功时,它不会重定向和吐司说,请首先登录,这是从authguard出现的

我假设您正在使用angular2-jwt,因为您正在使用tokenNotExpired()

来自 docs 我们可以看到:

注意:默认情况下,tokenNotExpired将假设令牌名称为 token,除非将令牌名称传递给它,ex: tokenNotExpired('token_name')

所以您在localStorage中存储的令牌是id_token

localStorage.setItem('id_token', data.token);

因此,要么将名称更改为token,要么将id_token作为参数传递到tokenNotExpired

相关内容

  • 没有找到相关文章

最新更新