how to get redirected to login page if user is not logged in?(Frontend: Angular7) (Backend: Node Js)

Viewed 39

I use two pages with login and crud operations in my project. I need some help. I want to check user login first and redirect to login page if not logged. There are crud operations after the user logs in. Whichever user logs in, only the products added by them will appear. How can I do that? I used node js on backend.

this is login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup, FormControl } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { LoginService } from '../shared/login.service';

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

    loginForm: FormGroup;

    username = new FormControl('');
    password = new FormControl('');

    constructor(
        private http: HttpClient,
        private authService: LoginService,
        private formBuilder: FormBuilder,
        private _router: Router) { }

        ngOnInit() {
            this.loginForm = this.formBuilder.group({
              username: ['', Validators.required],
              password: ['', Validators.required]
            });
          }

          get f() { return this.loginForm.controls; }

    loginSubmit() {
        this.http.post("http://localhost:3000/login", { username: this.username.value, password: this.password.value })
            .subscribe(result => {
                debugger;
                if(result.result){
                    this._router.navigate(["/payment"]);
                    // sessionstorage
                }else{
                    alert("Bilgiler yanlış");
                }
            }, error => {
                alert('hata oluştur');
            });
    }

}

and this is login.service.ts

import { loginDetail } from './login.model';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class LoginService {

  //private readonly mockedUser = new SignInData()
  isAuthenticated = false;

  loginFormData: loginDetail= {
    username: null,
    password: null,
    user_id: null
  };

  list : loginDetail[];

  readonly rootURL = 'http://localhost:5000/api';
  readonly rootURLnode = 'http://localhost:3000/';


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


  login() {
    
    //debugger;
    //console.log(this.loginFormData)
    this.isAuthenticated = true;
    this.router.navigate(['payment-details']);

    return this.http.post(this.rootURLnode + 'payment-details', this.loginFormData);
  }
}
1 Answers

Use a route guard to check if the user is authenticated or not. Below you can find an example:

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private _authService: AuthService, private _router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const url: string = state.url;

    return this.checkLogin(url);
  }
  
checkLogin(url: string): boolean {
    if (this._authService. isAuthenticated) { 
       return true; 
    }

    // Store the attempted URL for redirecting
    this._authService.redirectUrl = url;

    // Navigate to the login page
    this.router.navigate(['/login']);
    return false;
  }
}

You can use it in the routing module like so:


const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('.home/home.module').then((m) => m.HomeModule),
    canActivate: [AuthGuard]
  }
];

Your login method should be like this:

login() {
    return this.http.post(this.rootURLnode + 'payment-details', 
     this.loginFormData).pipe(
       tap(() => {
            // you need to do this only for the success case
            this.isAuthenticated = true;
            this.router.navigate(['payment-details']);
        })
  }
}

I recommend you to go through the tutorial from the Angular docs https://angular.io/guide/router-tutorial

Related