Search code examples
asp.net-mvcangulartypescriptadmin

Validating Admin in Angular 2


I'm trying to implement a website so that after logging in with username "[email protected]" and password "Admin", the user will be logged in and redirected to the home page. However, if the user has given any values other than the specified ones, the website will throw an error.

How can I write a piece of code in angular 2 to do such a thing?

The following is my login.component.ts file:

    import { Component }   from '@angular/core';
import { Router }      from '@angular/router';
import { AuthService } from '../../Services/auth.service';

@Component({
  templateUrl: './login.component.html',
})
export class LoginComponent {
  message: string;
  constructor(public authService: AuthService, public router: Router) {
    this.setMessage();
  }

  setMessage() {
    this.message = 'Logged ' + (this.authService.isLoggedIn ? 'in' : 'out');
  }

  login() {
    this.message = 'Trying to log in ...';

    this.authService.login().subscribe(() => {
      this.setMessage();
      if (this.authService.isLoggedIn) {
        // Get the redirect URL from our auth service
        // If no redirect has been set, use the default
        let redirect = this.authService.redirectUrl ? this.authService.redirectUrl : '/home';

        // Redirect the user
        this.router.navigate([redirect]);
      }
    });
  }

  logout() {
    this.authService.logout();
    this.setMessage();
  }


}

And my login.component.html file is:

<h1>Please login to proceed</h1>
<br />
<br />
<form >
    <table border="0">
        <tr>
            <td>
                <div class="form-group">
                    <label for="uname" style="display: inline-block">Username:* &emsp;</label>
                </div>
            </td>
            <td>
                <div class="form-group">
                    <input style="display: inline-block" id="uname" type="text" class="form-control"
                           placeholder="Username">
                </div>
            </td>
        </tr>
        <tr>
            <td>
                <div class="form-group">
                    <label for="pwd" style="display: inline-block">Password:* &emsp;</label>
                </div>
            </td>
            <td>
                <div class="form-group">
                    <input style="display: inline-block" type="password" class="form-control"
                            placeholder="Password">
                </div>
            </td>
        </tr>
        <tr>
            <td>
                <p style="color: red">* Required Fields</p>
            </td>
        </tr>
        <tr>
            <td>
                <p>
                    <button  class="btn btn-info" (click)="login()" *ngIf="!authService.isLoggedIn">Login</button>
               </p>
            </td>
    </table>
</form>

Solution

  • You can use Route Guard. It will solve your solution.

    // src/app/auth/auth-guard.service.ts

    import { Injectable } from '@angular/core';
    import { Router, CanActivate } from '@angular/router';
    import { AuthService } from './auth.service';
    
    @Injectable()
    export class AuthGuardService implements CanActivate {
    
      constructor(public auth: AuthService, public router: Router) {}
    
      canActivate(): boolean {
        if (!this.auth.isAuthenticated()) {
          this.router.navigate(['login']);
          return false;
        }
        return true;
      }
    
    }
    

    // src/app/app.routes.ts

    import { Routes, CanActivate } from '@angular/router';
    import { ProfileComponent } from './profile/profile.component';
    import { AuthGuardService as AuthGuard } from './auth/auth-guard.service';
    
    export const ROUTES: Routes = [
      { path: '', component: HomeComponent },
      { path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
      { path: '**', redirectTo: '' }
    ];