Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Load user from id_token or provide a means to populate the user$ observable #158

Open
thomaux opened this issue Sep 20, 2022 · 0 comments
Open

Comments

@thomaux
Copy link

thomaux commented Sep 20, 2022

Correct me if I'm wrong, but I believe currently the only way to make the user$ observable return a value is to call the loadUserInfo method?

Would it be possible to allow loading this info based on the returned id_token or alternatively to provide a way to set the value of the underlying _userSubject Subject?

FYI: My current solution is to hook into the events, then get the user data based on the token and either:
a) "hack" into the AuthService and access the private Subject or
b) Move everything in a separate service, which exposes its own user$ observable.

I went for option b:

import { Injectable } from '@angular/core';
import { TokenResponse } from '@openid/appauth';
import { AuthService } from 'ionic-appauth';
import { filter, Observable, Subject, switchMap, take, tap } from 'rxjs';

export interface User {
  name: string;
}

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private readonly userSubject: Subject<User | undefined> = new Subject();

  constructor(authService: AuthService) {
    authService.initComplete$.pipe(
      filter(complete => complete),
      switchMap(() => authService.isAuthenticated$),
      filter(isAuthenticated => isAuthenticated),
      take(1),
      switchMap(() => authService.token$),
      tap(tokens => {
        this.userSubject.next(getUserFromTokens(tokens));
      }),
    ).subscribe();
  }

  get user$(): Observable<unknown> {
    return this.userSubject.asObservable();
  }
}

function getUserFromTokens(tokens: TokenResponse): User | undefined {
  if (!tokens.idToken) {
    return;
  }
  return JSON.parse(Buffer.from(tokens.idToken.split('.')[1], 'base64').toString('ascii')) as User;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant