Skip to content

Instantly share code, notes, and snippets.

@ShankarSumanth
Created February 22, 2017 02:55
Show Gist options
  • Select an option

  • Save ShankarSumanth/ed86debaecfdf4925fa9f41108adff15 to your computer and use it in GitHub Desktop.

Select an option

Save ShankarSumanth/ed86debaecfdf4925fa9f41108adff15 to your computer and use it in GitHub Desktop.
// Login.Component.ts
// check if user is already logged in
ngOnInit() {
this.checkLoginSubscriber = this.loginService.isLoggedIn()
.subscribe(loggedIn => {
//console.log("Logged In?: " + loggedIn);
if (loggedIn) {
this.loginService.redirectToAuthorizedPage();
}
});
}
// do on demand login when the login button is clicked for example.
doLogin() {
this.loginSubscriber = this.loginService.login().subscribe(loggedIn => {
//console.log("logged IN ");
if (loggedIn)
this.router.navigate(['/test']);
});
}
// Login.Service.ts
private keycloakAuth: any;
constructor(private router: Router) {
this.keycloakAuth = new Keycloak('../keycloak.json');
}
// on demand login
login(): Observable<boolean> {
this.auth = null;
return Observable.create(obserer => {
this.keycloakAuth.init({ onLoad: 'login-required' })
.success(() => {
if (this.keycloakAuth.authenticated) {
//console.log('login success');
this.createAuth(); // the auth object as mentioned in the keycloak angular 2 example
obserer.next(true);
}
obserer.next(false);
});
});
}
// login check if previously logged in or after a reply from keycloak
isLoggedIn(): Observable<boolean> {
return Observable.create(observer => {
if (this.auth) { // store this object to prevent multiple keycloak calls
observer.next(this.auth.loggedIn);
observer.complete();
} else {
this.keycloakAuth.isLoggedIn().success((isLoggedIn: boolean) => {
if (isLoggedIn) {
this.keycloakAuth.watchLogin();
if (!this.auth)
this.createAuth();
observer.next(true);
} else {
observer.next(false);
}
observer.complete();
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment