Advertisement
Guest User

Untitled

a guest
Feb 21st, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. // Login.Component.ts
  2.  
  3. // check if user is already logged in
  4. ngOnInit() {
  5. this.checkLoginSubscriber = this.loginService.isLoggedIn()
  6. .subscribe(loggedIn => {
  7. //console.log("Logged In?: " + loggedIn);
  8. if (loggedIn) {
  9. this.loginService.redirectToAuthorizedPage();
  10. }
  11. });
  12. }
  13.  
  14. // do on demand login when the login button is clicked for example.
  15. doLogin() {
  16. this.loginSubscriber = this.loginService.login().subscribe(loggedIn => {
  17. //console.log("logged IN ");
  18. if (loggedIn)
  19. this.router.navigate(['/test']);
  20. });
  21. }
  22.  
  23. // Login.Service.ts
  24.  
  25. private keycloakAuth: any;
  26.  
  27. constructor(private router: Router) {
  28. this.keycloakAuth = new Keycloak('../keycloak.json');
  29. }
  30.  
  31. // on demand login
  32. login(): Observable<boolean> {
  33. this.auth = null;
  34. return Observable.create(obserer => {
  35. this.keycloakAuth.init({ onLoad: 'login-required' })
  36. .success(() => {
  37. if (this.keycloakAuth.authenticated) {
  38. //console.log('login success');
  39. this.createAuth(); // the auth object as mentioned in the keycloak angular 2 example
  40. obserer.next(true);
  41. }
  42. obserer.next(false);
  43. });
  44. });
  45. }
  46.  
  47. // login check if previously logged in or after a reply from keycloak
  48. isLoggedIn(): Observable<boolean> {
  49. return Observable.create(observer => {
  50. if (this.auth) { // store this object to prevent multiple keycloak calls
  51. observer.next(this.auth.loggedIn);
  52. observer.complete();
  53. } else {
  54. this.keycloakAuth.isLoggedIn().success((isLoggedIn: boolean) => {
  55. if (isLoggedIn) {
  56. this.keycloakAuth.watchLogin();
  57. if (!this.auth)
  58. this.createAuth();
  59. observer.next(true);
  60. } else {
  61. observer.next(false);
  62. }
  63. observer.complete();
  64. });
  65. }
  66. });
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement