0
votes

So I have the backend setup such that if I POST login, then it starts a session and if I POST logout, it ends that session. I want to write Angular2 auth guard such that it keeps track of if the user is logged in or not.

//login.component.ts

export class LoginComponent implements OnInit {
    questions: any[]; 
    error_message: string = 'Login Unsuccessful'

  constructor(public router: Router, 
    private authenticationService: AuthenticationService, 
    question_service: LoginQuestionService) {

    this.questions = question_service.getQuestions(); 
    this.authenticationService.logged_in.subscribe((value) => {
      console.log("Login Status: " + value);
    });
  }

  ngOnInit() {
  }

  formSubmitted(data): void {
    this.login(data.username, data.password);
  }


  login(username, password) {
    event.preventDefault();
    this.authenticationService.login(username, password)
    .subscribe(
      response => {
        this.authenticationService.logged_in.next(true);
        this.router.navigate(['home']);
      },
      error => {
        this.authenticationService.logged_in.next(false);
        alert(this.error_message);
        this.router.navigate(['login']);
        console.log(error);
      }
      );
  };

//authenticationservice.ts

@Injectable()
export class AuthenticationService {    
    private base_url: string;
    public logged_in: Subject<boolean> = new Subject();
     
    constructor(private http: Http) {
        this.base_url = 'http://localhost:3000/';
    }

    login(username: string, password: string): Observable<Response> {
        let query_url = `${this.base_url}login`;
        let payload = JSON.stringify({username: username, password: password});
        return this.http.post(query_url, payload)
        .map(res => res.json())
        .catch((error:any) => Observable.throw(error.json()));
    }

    logout(): Observable<Response>{
        let query_url = `${this.base_url}logout`;
        return this.http.post(query_url, null);
    }
}

How would go about writing an auth guard that keeps track of the variable in the service? What is the best way to keep track of login? I know in AngularJS, there is $rootscope variable but not in Angular2

1
You should use JWT-tokens as @crash states. It's a quick and safe method for checking whether a user is logged in or not. - Gustaf Gunér

1 Answers

0
votes

It's quite a lot to handle in SO.

I suggest to have a look at this module https://github.com/auth0/angular2-jwt to handle jwt tokens and authentication in general.