Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

Ionic / Angular / Capacitor / Firebase Facebook Auth & role based authentification

I have a facebook authentification working under Android created with Ionic Angular Capacitor Firebase that is fully working.

  • What I tried to do : Having a role based authentification.
  • What I went with : registering my User's facebook ID into a realtime database where I will just create type value for each user.

So when my user logs in for the first time, i create an enty in the realtimedatabase.

ERROR : Nothing is created in the database but I do not have any error message.

Here is my shared service :

import { Injectable } from '@angular/core';
import { User } from './User';
import { AngularFireDatabase, AngularFireList, AngularFireObject } from '@angular/fire/database';

@Injectable({
  providedIn: 'root'
})

export class UserService {
  userListRef: AngularFireList<any>;
  userRef: AngularFireObject<any>;

  constructor(private db: AngularFireDatabase) {}

  createUser(facebookID: string, name: string, email: string){
    let usr: User;
    usr.facebookID = facebookID;
    usr.name = name;
    usr.email = email;
    usr.type = "standard";

    return this.userListRef.push({
      facebookID: usr.facebookID,
      name: usr.name,
      email: usr.email
    })
  }

  getUser(facebookID: string) {
    let usr: User;
    this.userRef = this.db.object('/user/' + facebookID);
    this.userRef.snapshotChanges().subscribe(user => { user = user });
    return usr;
  }

    userExist(facebookID: string){
      if(this.getUser(facebookID).facebookID == facebookID) {return true;}
      else {return false;}
    }

  getUserList(){
    this.userListRef = this.db.list('/user');
    return this.userListRef;
  }

  updateUser(facebookID, username: string, type: string){
    let usr: User;
    usr = this.getUser(facebookID);

    return this.userRef.update({
      facebookID: usr.facebookID,
      name: username,
      email: usr.email,
      type: type
    })
  }
}

My sign in function for my facebook auth :

      async signIn(): Promise<void> {
    const FACEBOOK_PERMISSIONS = ['public_profile', 'email'];

    const result = await Plugins.FacebookLogin.login({ permissions: FACEBOOK_PERMISSIONS });
    if (result && result.accessToken) {
      let user = { token: result.accessToken.token, userId: result.accessToken.userId }
      let navigationExtras: NavigationExtras = {
        queryParams: {
          userinfo: JSON.stringify(user)
        }
      };
      this.router.navigate(["/feed"], navigationExtras);
    }
  }

My user class :

    export class User {
    $key: string;
    facebookID: string;
    name: string;
    email: string;
    type: string;
}

The page where I try to create an entry in my database :

    import { Component } from '@angular/core';
import { Plugins } from '@capacitor/core';
import { Router, ActivatedRoute } from '@angular/router';

import { UserService } from 'shared/user.service';

@Component({
  selector: 'app-feed',
  templateUrl: './feed.page.html',
  styleUrls: ['./feed.page.scss'],
})
export class FeedPage {
  logininfo: any;
  user: any;
  constructor(private route: ActivatedRoute,
    private router: Router,
    private usrService: UserService
  ) {
    this.route.queryParams.subscribe(params => {
      if (params && params.userinfo) {
        this.logininfo = JSON.parse(params.userinfo);
      }
    });
  }
  ionViewWillEnter() {
    this.getUserInfo();

    //Create a user based on facebookID
    if (this.usrService.userExist(this.user.id) == false) {
      this.usrService.createUser(this.user.id, this.user.name, this.user.email);
    }
  }

  async signOut(): Promise<void> {
    await Plugins.FacebookLogin.logout();
    this.router.navigate(['/home']);
  }

  async getUserInfo() {
    const response = await fetch(`https://graph.facebook.com/${this.logininfo.userId}?fields=id,name,gender,link,picture&type=large&access_token=${this.logininfo.token}`);
    const myJson = await response.json();
    this.user = myJson
  }
}

Of course all the firebase keys & IDs are set up in the environnement, here is my app.module.ts that leverages that :

    import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { AngularFireDatabaseModule } from '@angular/fire/database';
import { AngularFireStorageModule } from '@angular/fire/storage';

import { environment } from '../environments/environment';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFireAuthModule,
    AngularFireDatabaseModule,
    AngularFireStorageModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

How can I solve this problem ?

question from:https://stackoverflow.com/questions/65939506/ionic-angular-capacitor-firebase-facebook-auth-role-based-authentificati

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you are just missing a list binding to your user list. You could bind the list a few different places. One option is in the constructor like this.

constructor(private db: AngularFireDatabase) {
  this.userListRef = db.list('user');
}

This lets the AngularFireDatabase service know where to add the new user in the realtime database.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...