Angular 2 User Profile

Sample Project

Download this sample project configured with your Auth0 API Keys.

System Requirements
  • Angular 2.0.1
Show requirements

In this step, we will retrieve and display user profile information using the same Auth service defined in the Login tutorial.

Profile

To fetch user profile information, call the lock.getProfile function, specifying the idToken and a callback to process the response.

Once the user profile is retrieved, we can store it in localStorage (or another form of storage if you prefer) and assign it to a userProfile attribute so you can access it later.

// ./auth.service.ts

import {Injectable} from '@angular/core';
import {tokenNotExpired} from 'angular2-jwt';

// Avoid name not found warnings
declare var Auth0Lock: any;

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

  //Store profile object in auth class
  userProfile: Object;

  constructor() {
    // Set userProfile attribute of already saved profile
    this.userProfile = JSON.parse(localStorage.getItem('profile'));

    // Add callback for the Lock `authenticated` event
    this.lock.on("authenticated", (authResult) => {
      localStorage.setItem('id_token', authResult.idToken);

      // Fetch profile information
      this.lock.getProfile(authResult.idToken, (error, profile) => {
        if (error) {
          // Handle error
          alert(error);
          return;
        }

        localStorage.setItem('profile', JSON.stringify(profile));
        this.userProfile = profile;
      });
    });
  };

  ...

  public logout() {
    // Remove token and profile from localStorage
    localStorage.removeItem('id_token');
    localStorage.removeItem('profile');
    this.userProfile = undefined;
  };
}

To see user profile information, inject the Auth service into a component:

// home.component.ts

export class HomeComponent {

  constructor(private auth: Auth) {}

}

Then display the userProfile attributes in your component's template:

  <!-- ./home.template.ts -->

  <div *ngIf="auth.authenticated() && auth.userProfile">
    <h4>You are logged in</h4>
    <div class="row">
      <div class="col-md-6">
        <h3>Profile</h3>
        <img [src]="auth.userProfile.picture" alt="" class="profile-img">
        <p><strong>Name: </strong> {{auth.userProfile.name}}</p>
        <p><strong>Email: </strong> {{auth.userProfile.email}}</p>
        <p><strong>Nickname: </strong> {{auth.userProfile.nickname}}</p>
        <p><strong>Created At: </strong> {{auth.userProfile.created_at}}</p>
        <p><strong>Updated At: </strong> {{auth.userProfile.updated_at}}</p>
      </div>
    </div>
  </div>
  <h4 *ngIf="!auth.authenticated()">You are not logged in, please click 'Log in' button to login</h4>

Custom Sign Up Fields for Lock

You can add additional input fields to Lock's sign up form by adding additionalSignUpFields to the options parameter of the Auth0Lock instantiation.

NOTE: See Additional sign up fields for more information.

// auth.service.ts

...

  // Configure Auth0
  lock = new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN', {
    additionalSignUpFields: [{
      name: "address",                              // required
      placeholder: "enter your address",            // required
      icon: "https://example.com/address_icon.png", // optional
      validator: function(value) {                  // optional
        // only accept addresses with more than 10 characters
        return value.length > 10;
      }
    }]
  });

...

Each additionalSignUpFields value is saved to the profile in the user_metadata attribute of the user's Auth0 profile.

To display this data, read it from the profile's user_metadata:

  <!-- profile_show.template.html -->
  <strong>Address: </strong> {{auth.userProfile.user_metadata.address}}

Update the User's Profile

Auth0 allows you to store user information that has not come from the identity provider as metadata. There are two types of metadata: user_metadata and app_metadata. For more information, see User Metadata.

You can add an address attribute to the user profile's user_metadata by creating a component and a simple form. You will need to call the Update a user endpoint on form-submit.

To call the endpoint, you can use the AuthHttp helper from angular2-jwt which provides the same interface as the Http module but automatically adds the authorization header to requests.

First, add AUTH_PROVIDERS from angular2-jwt:

/* ===== app/app.module.ts ===== */
import { AUTH_PROVIDERS } from 'angular2-jwt';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  providers: [
    ...
    AUTH_PROVIDERS,
    ...
  ],
  imports: [
    ...
  ],
  bootstrap: [AppComponent]
})

Then import AuthHttp, inject it in your component, and use it to make the authenticated request.

In this example, the patch method takes the endpoint URL, body, and headers:

// app/profile_edit.component.ts

import { AuthHttp } from 'angular2-jwt';

@Component({
  selector: 'profile',
  templateUrl: 'app/profile_edit.template.html'
})

export class ProfileEdit {

  address: String

  constructor(private auth: Auth, private authHttp: AuthHttp, private router: Router) {
    if(auth.userProfile.user_metadata && auth.userProfile.user_metadata.address){
      this.address = auth.userProfile.user_metadata.address;
    }
  }

  onSubmit() {
    var headers: any = {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    };

    var data: any = JSON.stringify({
      user_metadata: {
        address: this.address
      }
    });

    this.authHttp
      .patch('https://' + 'YOUR_AUTH0_DOMAIN' + '/api/v2/users/' + this.auth.userProfile.user_id, data, {headers: headers})
      .map(response => response.json())
      .subscribe(
        response => {
          //Update profile
          this.auth.userProfile = response;
          localStorage.setItem('profile', JSON.stringify(response));
          this.router.navigate(['/profile']);
        },
        error => alert(error.json().message)
      );
  }
}

Then create a simple form template to add/update the address attribute:

  <!-- app/profile_edit.template.html -->

  <div *ngIf="auth.authenticated() && auth.userProfile">
    <div class="row">
      <div class="col-md-6">
        <h3>Profile</h3>
        <img [src]="auth.userProfile.picture" alt="" class="profile-img">
        <form (ngSubmit)="onSubmit()">
          <div class="form-group">
            <label for="name">Address</label>
            <input type="text" class="form-control" [(ngModel)]="address" name="address" placeholder="Enter address">
          </div>
          <button type="submit" class="btn btn-default">Submit</button>
        </form>
      </div>
    </div>
  </div>
  <h4 *ngIf="!auth.authenticated()">You are not logged in, please click 'Log in' button to login</h4>
Previous Tutorial
4. Session Handling
Use Auth0 for FREECreate free Account