Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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();
- });
- }
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement