How to do login validation in Angular?

0

I would like to know how to do so in case the user type an invalid user login and password appears in the message "Login invalid". Here's the code I've already done.

import { Component, OnInit } from '@angular/core';
import { AuthService } from './auth.service';
import { Usuario } from './usuario';
import { User } from "./user";

@Component({
  selector: 'ngx-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.scss'],
})
export class LoginComponent implements OnInit {

  _user: User = new User();
  constructor(private _authService: AuthService) { }

  ngOnInit() {
    this.logout();
  }

  logout() {
    this._authService.userNoAuthenticated();
    if (this._authService.userIsAuthenticated() === true) {
      location.reload();
    }
  }

  makeLogin() {
    this._authService.getUser(this._user);
  }
}
<nb-auth-block>
    <h2 class="title">Login</h2>
    <small class="form-text sub-title">Olá! Faça login com seu email</small>

    <div class="row">
        <div class="input-field col s12">
            <div class="form-group">
                <label for="input-email" class="sr-only">Digite seu email</label>
                <input [(ngModel)]="_user.email" id="usuario" class="form-control" placeholder="Digite seu email">
            </div>
            <div class="form-group">
                <label for="input-password" class="sr-only">Password</label>
                <input [(ngModel)]="_user.password" id="senha" type="password" class="form-control" placeholder="Senha">
            </div>
            <button type="submit" name="action" (click)="makeLogin()" class="btn btn-block btn-hero-success"> Entrar </button>
        </div>
    </div>

    <br>
  <div *ngIf="!customerId"> Login ou senha invalida </div>

 
</nb-auth-block>

import { Router } from '@angular/router';
import { Component, Injectable, EventEmitter } from '@angular/core';
import { User } from './user';
import { Usuario } from './usuario';
import { Http, Response } from '@angular/http';
import { md5 } from './md5';
import { Observable } from 'rxjs/Observable';

import 'rxjs/Rx';

@Injectable()
export class AuthService {
  // customerId: any;

  constructor(private router: Router, private http: Http) { }

  private userAuthenticated: boolean = false;
  private customerId: string = '';
  private linkPortal: string;
  public user: User[] = [];
  private userString: string;
  private errorMessage: any = '';
  private url: string = 'http://14.28.240.19:2088/api/values/GetUser/';
  private hash: string;
  private userName: string;

  makeLogin() {
    // this.userString = users.email + users.password;

    if (this.userIsAuthenticated() === true) {
      this.userAuthenticated = false;
      console.log('Login verdadeiro');
    } else {
      const e = md5(this.userString);

      this.http
        .get(this.url + e)
        .map((res) => res.json())
        .subscribe((data) => this.user = data,
        () => console.log(this.user));
      for (const key in this.user) {
        if (this.user.hasOwnProperty(key)) {
          const element = this.user[key];
          this.customerId = element['IdCustomer'];
          this.linkPortal = element['linkPortal'];
          this.userName = element['UserName'];
          if (element['UserName'] !== '') {
            this.userAuthenticated = true;
            this.router.navigate(['/pages/dashboard']);
          } else {
            this.userAuthenticated = false;
          }
        }
      }
      if (this.customerId === '') {
        this.data();
      console.log('Login false');
      }
    }

  }

  data() {
    const dayAsync = new Promise((resolve, reject) => {
      setTimeout(() => {
        this.makeLogin();
      }, 1000);
    });
  }

  getUser(users: User) {
    this.userString = users.email + users.password;
    this.makeLogin();
  }

  public customerIsId() {
    return this.customerId;
  }

  public customerIsUserName() {
    return this.userName;
  }

  public customerIsLinkPortal() {
    return this.linkPortal;
  }

  userIsAuthenticated() {
    return this.userAuthenticated;
  }

  userNoAuthenticated() {
    this.customerId = '';
    this.userString = '';
    this.user = null;
  }

}
  makeLogin() {
this._authService.getUser(this._user)
  if ( this._authService.userIsAuthenticated() === false ){
      this.userAuthenticated = true;
      console.log('Login valido');
      this.messageLoginValido = 'Login valido';
    }else{
    this.message = 'Login invalido';
  }

}

<nb-auth-block>
<h2 class="title">Login</h2>
<small class="form-text sub-title">Olá! Faça login com seu email</small>

<div class="row">
    <div class="input-field col s12">
        <div class="form-group">
            <label for="input-email" class="sr-only">Digite seu email</label>
            <input [(ngModel)]="_user.email" id="usuario" class="form-control" placeholder="Digite seu email">
        </div>
        <div class="form-group">
            <label for="input-password" class="sr-only">Password</label>
            <input [(ngModel)]="_user.password" id="senha" type="password" class="form-control" placeholder="Senha">
        </div>
        <button type="submit" name="action" (click)="makeLogin()" class="btn btn-block btn-hero-success"> Entrar </button>
    </div>
</div>

<br>

{{message}}    {{messageLoginValid}}

    
asked by anonymous 30.04.2018 / 19:46

2 answers

0

On your makeLogin() use subscribe :

    ....
    this._authService.getUser(this._user )
      .subscribe(
        res => {
          if( [ CONDICAO AQUI DO RETORNO DO res] ){
            this.userAuthenticated = true;
            this.router.navigate(['/pages/dashboard']);
          } 
        },
        err => {
          this.message = 'Login invalido';
        }
    );
    ...
    
30.04.2018 / 20:32
0

Try to map the response.

    this._authService.getUser(this._user)
     .map( res => res.json()) //map
     .subscribe(
      res => {
        if( this._authService.userIsAuthenticated() === false ){
          this.userAuthenticated = true;
          this.router.navigate(['/pages/dashboard']);
        }
        // Tratativa de login incorreto aqui 
        //!customerId ~ usa esse cara atribuindo para undefinded para dar a mensagem de login inválido
      },
      err => {
        this.message = 'Login invalido';
      }
  );
    
30.04.2018 / 22:40