Search code examples
angulartypescriptfirebasefirebase-authenticationangular-canload

How to store user data in local storage using Capacitor’s Storage Plugin?


I am trying to add Firebase Authentication to my Angular app.

Here is the signUp() method in my AuthService:

signUp(email: string, password: string, name: string) {
    const userCredential = from(
      firebase.auth().createUserWithEmailAndPassword(email, password)
        .then(
          (data) => {

            let newUser: firebase.User = data.user;

            newUser.updateProfile({
              displayName: name,
              photoURL: ''
            }).then(() => {
              firebase.firestore().collection('users').add({
                userId: firebase.auth().currentUser.uid,
                userName: firebase.auth().currentUser.displayName,
                created: firebase.firestore.FieldValue.serverTimestamp()
              });
            });
            Plugins.Storage.set({
              key: 'userCredential',
              value: newUser.uid
            });
          }
        )
    );
    return userCredential;
  }

With this method, I'm able to store newUser.uid in local storage using Capacitor's Storage plugin.

But I want to be able to store the same information as what is being stored below (namely localId, email, idToken & expirationTime:

 login(email: string, password: string) {
    return this.http.post<AuthResponseData>(
      `firebaseUrl/v1/accounts:signInWithPassword?key=${
      environment.firebaseAPIKey
      }`,
      { email: email, password: password, returnSecureToken: true }
    ).pipe(tap(this.setUserData.bind(this)));
  }

private setUserData(userData: AuthResponseData) {
    const expirationTime = new Date(
      new Date().getTime() + (+userData.expiresIn * 1000)
    );
    this._user.next(
      new User(
        userData.localId,
        userData.email,
        userData.idToken,
        expirationTime
      )
    );
    this.storeAuthData(userData.localId, userData.idToken, expirationTime.toISOString(), userData.email);
  }

  private storeAuthData(userId: string, token: string, tokenExpirationDate: string, email: string) {
    const data = JSON.stringify({
      userId: userId,
      token: token,
      tokenExpirationDate: tokenExpirationDate,
      email: email
    });
    Plugins.Storage.set({ key: 'authData', value: data });
  }

Can someone please tell me how I can get these 4 values in my signUp() method?


Solution

  • AuthService Login():

    login(email: string, password: string) {
        const userCredential = from(firebase.auth().signInWithEmailAndPassword(email, password).then(loggedInUser => {
          Plugins.Storage.set({
            key: 'userCredential',
            value: loggedInUser.user.displayName
          });
        }));
        return userCredential;
      }
    

    Auth Guard:

    userCredential;
    
    canLoad(
        route: Route,
        segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
        return Plugins.Storage.get({ key: 'userCredential' }).then(userCredential => {
          this.userCredential = userCredential;
          return this.autoLogin();
        });
      }
    
      autoLogin() {
        if (!this.userCredential || this.userCredential.value === null) {
          this.router.navigateByUrl('login');
          return false;
        } else {
          return true;
        }
      }