简体   繁体   中英

get Auth0 user profile when first login success too late

I encountered the following sitiation: I use Auth0 for user authentication. When I first login , I have an auth.service that retrieves the user profile and stores it in local storage. This service is injected in my component called items.component. I want to check a property of my profile (profile.user_metadata.admin) and show it in a div of my html right after the first login. The problem is that the profile wont be stored in local storage until the very very end and I can only check it if I check in ngAfterViewChecked(), which throws an error if I run in developer mode. How can I get my profile earlier? Or make the check in another way? Thanks in advance.

auth.service.component.ts

@Injectable()
export class Auth {
  // Configure Auth0
  lock = new Auth0Lock('xxxhiddenxx', 'xxxhiddemxxx', {});

  profile:any;

  constructor( private authHttp: AuthHttp, private router: Router) {
    // Add callback for lock `authenticated` event
   // this.userProfile = JSON.parse(localStorage.getItem('profile'));


    this.lock.on("authenticated", (authResult:any) => {
    this.lock.getUserInfo(authResult.accessToken, function(error:any, profile:any){
        if(error){
                throw new Error(error);                    
        }
        localStorage.setItem('id_token', authResult.idToken);
        localStorage.setItem('profile', JSON.stringify(profile));


  });

});



  }

  public login() {
    // Call the show method to display the widget.
    this.lock.show();
  }

  public authenticated() {

    // Check if there's an unexpired JWT
    // This searches for an item in localStorage with key == 'id_token'
    return tokenNotExpired();
  }

items.component.ts

export class ItemsComponent implements OnInit { 

items: Item[];
isAdmin:boolean;
 profile:any;


    constructor(private ItemService:ItemService,private auth:Auth, private authHttp: AuthHttp, private router: Router){
        this.ItemService.getItems()
        .subscribe(items =>{
            this.items=items;

//this.profile=JSON.parse(localStorage.getItem('profile'));
//this never finds the profile when first login occurs

    });
}

ngAfterViewChecked(){  //only way I can get the profile data when first login

        this.profile=JSON.parse(localStorage.getItem('profile'));

        if(this.profile!=undefined && this.profile!=null){
            console.log(this.profile.user_metadata.admin)

            if(this.profile.user_metadata.admin==1){

                this.isAdmin=true;
         }
        }

}

items.component.html

             <div class="row" *ngIf="auth.authenticated()" style="margin: 20px 20px">
        <div class="alert alert-success col-md-3 center" *ngIf="isAdmin===true">Admin account</div>
         </div>

Before I answer this question directly I should state that it is more usual to use routing when you have login. If you are not authenticated you route might be something like '/signIn'. On successful auth you would then route to another 'page' that would render your ItemsComponent (like '/home' for example). Under that scenario, you would not see the ItemsComponent unless you were logged in so it would always resolve. As it is you are loading the component before the auth has occurred which is making life more difficult than it would otherwise be.

If you want to show the ItemsComponent whether or not you are signed in and then you want the div to show up when you sign in, one way to do it is to create an authenticated observable in the auth service and set it to false and then when it is authenticated, set it to true. Then in your ItemsComponent you need to subscribe to that observable so that when it changes after you log in, you can run your auth code in the success callback. Basically, that code will then run whenever you log in or out.

If you are not sure about Observables yet, go with the routing suggestion. It is easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM