Redirect before logging in - Angular

1

I have a login screen, with the total "/ authentication / login".

How to do angular when the user enters the system, it goes straight to this route?

After logging in if he entered this route, it always validates and if the user has logged in he goes to route "/"?

Route

import { Routes } from '@angular/router';

import { FullComponent } from './layouts/full/full.component';
import { AppBlankComponent } from './layouts/blank/blank.component';

export const AppRoutes: Routes = 
[
  {
    path: '',
    component: FullComponent,
    children: 
    [
      {
        path: '',
        loadChildren: './dashboards/dashboards.module#DashboardsModule'  
        /*pathMatch: 'full',
        redirectTo: '/dashboards/dashboard1', */
      },
      {
        path: 'configuracao',
        loadChildren: './paginas/configuracao/configuracao.module#ConfiguracaoModule'  
      },
      {
        path: 'arquivo',
        loadChildren: './paginas/arquivo/arquivo.module#ArquivoModule'  
      },
      {
        path: 'declaracao',
        loadChildren: './paginas/declaracao/declaracao.module#DeclaracaoModule'  
      },
      {
        path: 'parametro',
        loadChildren: './paginas/parametro/parametro.module#ParametroModule'  
      },
      {
        path: 'endereco',
        loadChildren: './paginas/endereco/endereco.module#EnderecoModule'  
      },
      {
        path: 'contribuinte',
        loadChildren: './paginas/banco/banco.module#BancoModule'  
      },
      {
        path: 'dashboard',
        loadChildren: './dashboards/dashboards.module#DashboardsModule'  
      }
    ]
  },
  {
    path: '',
    component: AppBlankComponent,
    children: 
    [
      {
        path: 'authentication',
        loadChildren: './authentication/authentication.module#AuthenticationModule'
      }
    ]
  },
  {
    path: '**',
    redirectTo: '404' 
  }
];

Angle version: 5.0.0

    
asked by anonymous 16.05.2018 / 15:38

1 answer

0

I did so and so resolved.

CanActivateAuthGuard

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthenticationService } from '../servico/authentication/authentication.service';

@Injectable()
export class CanActivateAuthGuard implements CanActivate {

  constructor(
    private router: Router, 
    private authService: AuthenticationService
  ) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.authService.isLoggedIn()) {
      return true;
    }
    this.router.navigate(['/authentication/login']);
    return false;
  }
}

Safe routes

import { Routes } from '@angular/router';
import { ArquivoComponent } from './arquivo/arquivo.component';
import { ArquivoFormComponent } from './arquivo-form/arquivo-form.component';
import { CanActivateAuthGuard } from '../../authentication/can-activate.authguard';

export const ArquivoRoutes: Routes = [
  {
    path: '',
    children: [
      {
        path: '',
        component: ArquivoComponent,
        canActivate: [CanActivateAuthGuard] 
      }
      , {
        path: 'novo',
        component: ArquivoFormComponent,
        canActivate: [CanActivateAuthGuard] 
      }
    ]
  }
];

AuthenticationService

  

import {Injectable} from '@ angular / core';       import {Http, Headers, Response} from '@ angular / http';       import {Observable} from 'rxjs / Rx';       import 'rxjs / add / operator / map';       import 'rxjs / add / operator / catch';       import 'rxjs / add / observable / throw';

import { Usuario } from '../../modelo/usuario/usuario.model';
import { BASE_AUT_URL } from '../base-api-url-defaul';

@Injectable()
export class AuthenticationService {

    private base: string;
    private options: Function;

    private headers = new Headers({
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': 'true'
    });

    constructor(private http: Http) {
        this.base = BASE_AUT_URL
    }

    login(usuario: Usuario): Observable<boolean> {
        console.log(this.headers);
        return this.http.post(this.base, JSON.stringify({login: usuario.login, senha: usuario.senha}), {headers: this.headers})
            .map((response: Response) => {
                let token = response.json() && response.json().token;
                if (token) {
                    localStorage.setItem('currentUser', JSON.stringify({ username: usuario.login, token: token }));
                    localStorage.setItem('token', token);
                    localStorage.setItem('user', JSON.stringify(usuario.login));
                    localStorage.setItem('usuario', response.json().usuario);
                    localStorage.setItem('nomeUsuario', response.json().nomeUsuario);
                    localStorage.setItem('grupoUsuario', response.json().grupo);
                    return true;
                } else {
                    return false;
                }
            }
        ).catch(
            (error:any) => Observable.throw(error.json().error || 'Server error')
        );
    }

    getToken(): String {
        //var currentUser = JSON.parse(localStorage.getItem('currentUser'));
        //var token = currentUser && currentUser.token;
        var token = localStorage.getItem('token');
        return token ? token : "";
    }

    logout(): void {
        localStorage.removeItem('currentUser');
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        localStorage.removeItem('usuario');
        localStorage.removeItem('nomeUsuario');
        localStorage.removeItem('grupoUsuario');
    }

    isLoggedIn(): boolean {
        var token: String = this.getToken();
        return token && token.length > 0;
    }
}

I used this article as a reference: Angular Authentication: Using Route Guards

    
16.05.2018 / 20:04