0

Da Firebase das Hinzufügen eines Benutzernamens zu einem registrierten Benutzer nicht standardmäßig unterstützt, versuche ich einen Weg zu finden, den Benutzernamen und seine Benutzer-ID in die Datenbank zu schreiben. Deshalb habe ich versucht, eine User ID Beziehung in die Datenbank zu schreiben. Aber irgendwie führt es die Methode nie aus. Sie können den folgenden Code finden.Hinzufügen einer Dokument-Datenbank zur Anmeldung

HTML-Vorlage:

<mat-tab label="Register"> 
<div class="registerContainer"> 
    <mat-form-field> 
    <input #usernameRegister (keyup.enter)="register(usernameRegister.value, emailRegister.value, passwordRegister.value)" matInput placeholder="Enter your username"> 
    </mat-form-field> 
    <br> 
    <mat-form-field> 
    <input #emailRegister (keyup.enter)="register(usernameRegister.value, emailRegister.value, passwordRegister.value)" matInput placeholder="Enter your email"> 
    </mat-form-field> 
    <br> 
    <mat-form-field> 
    <input #passwordRegister (keyup.enter)="register(usernameRegister.value, emailRegister.value, passwordRegister.value.toString())" matInput placeholder="Enter your password" [type]="hide ? 'text' : 'password'"> 
    <mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' : 'visibility_off'}}</mat-icon> 
    </mat-form-field> 
    <br> 
    **<button mat-raised-button color="primary" (click)="register(usernameRegister.value, emailRegister.value, passwordRegister.value)">Register</button>** 
</div> 

Registrierung Betrieb:

register(username:string, email: string, password: string):void{ 
if (username.length != 0) { 
    if (email.length != 0) { 
     this.authenticationService.register(username.toString().trim(), email.toString().trim(), password.toString()) 
     .then((user) => { 
      **console.log('database operation'); 
      this.userService.add(user, username) 
      .then(()=>{ 
       console.log('wrote to database.'); 
      }) 
      .catch((error)=>{ 
       console.log('Error writing to database' + error); 
      });** 
      user.sendEmailVerification() 
      .catch((error) => { 
       console.log(error); 
      }); 
      this.authenticationService.logout() 
      .catch((error)=>{ 
       console.log(error); 
      }); 
      this.dialogRef.close(); 
      this.snackBar.open('Registration completed', null, {duration: 1000}); 
     }) 
     .catch((error) => { 
      console.log(error); 
     }) 
    } 
    else { 
    this.snackBar.open('Please enter an email address.', null, {duration: 1000}); 
    } 
} 
else { 
    this.snackBar.open('Please enter an username.', null, {duration: 1000}); 
} 

Modell Benutzer:

export class User implements IFirebaseStorable { 
    constructor(
    public uID:string, 
    public username:string) { 
    } 


} 

Authentication Service:

@Injectable() 
export class AuthenticationService { 

    constructor(public afAuth: AngularFireAuth) { } 

    // login with email address 
    // returns: Promise<any> 
    loginWithEmail(email:string, password:string):Promise<any>{ 
    return this.afAuth.auth.signInWithEmailAndPassword(email, password); 
    } 

    // login via facebook account 
    // returns: Promise<any> 
    loginWithFacebook():Promise<any>{ 
    return this.afAuth.auth.signInWithPopup(new firebase.auth.FacebookAuthProvider()); 
    } 

    // login via Github 
    // returns: Promise<any> 
    loginWithGithub():Promise<any>{ 
    return this.afAuth.auth.signInWithPopup(new firebase.auth.GithubAuthProvider()); 
    } 

    // login via google account 
    // returns: Promise<any> 
    loginWithGoogle():Promise<any>{ 
    return this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()); 
    } 

    // login via Twitter 
    // returns: Promise<any> 
    loginWithTwitter():Promise<any>{ 
    return this.afAuth.auth.signInWithPopup(new firebase.auth.TwitterAuthProvider()); 
    } 

    // register method 
    // parameters: Email - string, Password - string 
    // returns: Promise<any> 
    **register(username:string, email: string, password: string):Promise<any>{ 
    return this.afAuth.auth.createUserWithEmailAndPassword(email, password); 
    }** 

    // checks whether a user is signed in or not 
    // returns: Boolean 
    userIsSignedIn():boolean{ 
    return this.afAuth.auth.currentUser != null; 
    } 

    // logout method 
    // returns: Promise<any> 
    logout() : Promise<any> { 
    return this.afAuth.auth.signOut(); 
    } 

    // returns: current user with following properties: 
    // 
    // displayName: string | null; 
    // email: string | null; 
    // phoneNumber: string | null; 
    // photoURL: string | null; 
    // providerId: string; 
    // uid: string; 
    getLoggedInUser():firebase.User{ 
    return this.afAuth.auth.currentUser; 
    } 

    // send user an email to restore the password 
    forgotPassword(email:string):Promise<any>{ 
    return this.afAuth.auth.sendPasswordResetEmail(email); 
    } 
} 

Benutzerdatenbankbetrieb Service

@Injectable() 
export class UserService { 
    private userCollection: AngularFirestoreCollection<User>; 
    user: Observable<User[]>; 

    constructor(private afs: AngularFirestore) { 
    this.userCollection = afs.collection<User>('User'); 
    this.user = this.userCollection.valueChanges(); 
    } 

    **add(user ,username:string):Promise<DocumentReference>{ 
    const uID = user.uid.toString(); 
    const userAdded : User = {uID, username}; 
    return this.userCollection.add(userAdded); 
    }** 

} 

Antwort

0

Dieses Beispiel geschrieben wird, in Reaktion durch die Redux Aktionen, aber die Javascript ist alle gleich. Sie möchten alle Informationen aus dem Anmeldeformular erfassen, senden Sie die signupUserWithEmailAndPassword() und legen Sie diese Daten dann auf die Datenbank ....

Da Sie Oauth verwenden, müssen Sie die Antwort von jeder Version erfassen von signin, dann erstellen Sie Ihr eigenes benutzerdefiniertes Objekt, um es in die Datenbank zu setzen. Dies war eine PITA für mich bei der Verwendung verschiedener Oauth Clients.

export const signupRequest = (email, password, username) => dispatch => { 
// ******** The signup actions only trigger for first time users, no need to check database ******** 
console.log('RECIEVED USER TO SIGNUP', email, password); 
firebase.auth().createUserWithEmailAndPassword(email, password) 
    .then((authData) => { 
     // ******** Firebase will create a route with whatever KEY is fed to the .set method ******** 
     // ******** We dont actually want this to avoid deep nesting ******** 
     // ******** So we package up our user.account object and .set(account) without any key value pairs ******** 
     let account = {} 
     account.email = email.toLowerCase() 
     account.uid = authData.uid 
     account.username = username 
     firebase.database().ref('users/' + authData.uid).set({ 
      account 
     }).then(() => { 
      // ******** Now we need to grap a snapshot from the DB to validate account creation and update the redux store locally ******** 
      firebase.database().ref('users/' + authData.uid).once('value').then(function (snapshot) { 
       let updatedUser = snapshot.val(); 
       console.log(' FOUND THIS USER FROM THE DB after signup', username); 
      }).then(() => { 
       dispatch(userSet(updatedUser)); 

      }) 
     }) 
    }).catch((err) => console.log(err)); 

};

Verwandte Themen