Firebase身份验证限制由同一用户登录

时间:2018-01-13 06:20:54

标签: firebase firebase-realtime-database firebase-authentication

Firebase中是否有办法同时限制同一用户的登录次数,我说我希望一次为一个帐户设置3个设备的限制,我该如何实现?

3 个答案:

答案 0 :(得分:1)

Firebase不支持。您可以做的最好的事情就是跟踪令牌auth_time。这是登录的时间。您将为此保留3个条目的队列。每次登录用户时,发送他们的ID令牌进行验证,将auth_time添加到队列中(如果它不存在),并将队列中最旧的auth_time出列(如果超过它)最大尺寸(3)。您只允许在该队列中使用auth_times访问ID令牌的数据。

答案 1 :(得分:0)

您应该使用数据库(实时数据库或Firestore)来保存用户的设备,并从那里检查他是否可以登录。

答案 2 :(得分:0)

我遇到了类似的情况,然后我实施了 bojeil 方法来限制使用一个用户凭据的同时登录。

我在用户文档中维护了以下数组字段和数字字段。

{
    allowed_auth_times : [

    ],
    max_granted_login : 3
}

上的此数组中添加条目
  1. 用户注册。
  2. 如果大小(allowed_auth_times)是另一个人使用相同的凭据(在相同或不同的设备上)登录系统

如果size(allowed_auth_times)== max_granted_login   然后删除最旧的身份验证时间(allowed_auth_times [0]),然后添加新的身份验证时间条目。

这样,您将确保在任何给定时间点,有限的用户都可以使用该系统。我已经使用Angular + AngularFire2实现了它 如果有人可以提出改进建议,我将非常高兴。预先感谢。

身份验证组件:

trySignInWithEmailAndPassword() {

    // Actual Signin process starts here.
    this._firebaseAuthenticationService.signInUserWithEmailAndPassword(this.userCredentials.value)
      .then((user) => {
        this._firebaseAuthenticationService.OTCheckAndUpdateDBAuthTime().then((result) => {
          bootbox.hideAll();
          if (result === true) {
            this._router.navigate(['/home']);
          }
        }, (err) => {
          bootbox.hideAll();
          bootbox.alert("Error Occured. Please contact support team with screenshot. " + err);
        });
      }).catch((err) => {
        console.error("Login failed. Redirecting user to authentication page.");
        bootbox.alert("Some Error Occured While Authenticating " + this.userCredentials.get("email").value);
        this._router.navigate(['/authentication']);
      });
  }

FirebaseAuthService

import { Injectable, OnInit } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import * as firebase from 'firebase/app';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AngularFirestore } from '@angular/fire/firestore';
import { environment } from 'src/environments/environment';
import { first, take } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class FirebaseAuthenticationService implements OnInit {
  ngOnInit(): void {
  }

  uid: string = "";
  constructor(private _angularFireAuth: AngularFireAuth,
    private db: AngularFirestore,
    private _router: Router) { }

  trySignOut() {
    return new Promise<any>((resolve, reject) => {
      this._angularFireAuth.auth.signOut().then(() => {
        resolve();
      }, (error) => {
        reject(error);
      }
      );
    });
  }

  getCurrentUserUID(): string {
    if (this._angularFireAuth.auth.currentUser != undefined || this._angularFireAuth.auth.currentUser != null) {
      let uid = this._angularFireAuth.auth.currentUser.uid;
      if (uid == undefined || uid == null) {
        return "";
      } else {
        return uid;
      }
    }
    return this._angularFireAuth.auth.currentUser.uid;
  }

  getCurrentUserUID2(): Observable<firebase.User> {
    return this._angularFireAuth.authState.pipe(first());
  }

  createUserWithEmailAndPassword(userCredentials: any) {
    return new Promise<any>((resolve, reject) => {
      this._angularFireAuth.auth.createUserWithEmailAndPassword(userCredentials.email, userCredentials.password)
        .then((userData) => {
          userData.user.getIdTokenResult().then((a) => {
            console.log("Auth Time : " + a.authTime);
            resolve(userData.user);
          });
        });
    });
  }

  signInUserWithEmailAndPassword(userCredentials: any) {
    return new Promise<any>((resolve, reject) => {
      this._angularFireAuth.auth.signInWithEmailAndPassword(userCredentials.email, userCredentials.password)
        .then((userData) => {
          console.log(userData);
          // If email is not verified then send verification email every time.
          if (this._angularFireAuth.auth.currentUser.emailVerified == false) {
            this.sendEmailVerification();
          }
          userData.user.getIdTokenResult().then((a) => {
            console.log("Auth Time : " + a.authTime);
            resolve(userData.user);
          });
        }, err => {
          console.error("Error Occured During Signin user with email and password in auth service.");
          console.error(err);
          reject(err);
        });
    });
  }

  // This function checks entry in allowed_auth_times [] depending on max_logins : in user profile.
  OTCheckAndUpdateDBAuthTime() {
    return new Promise<any>((resolve, reject) => {
      this._angularFireAuth.authState.subscribe((userAuthState) => {
        if (userAuthState.uid != null || userAuthState.uid != undefined || userAuthState.uid != "") {
          const user_doc_id = userAuthState.uid;
          this.db.collection("users").doc(user_doc_id).snapshotChanges().subscribe((docData) => {
            let doc: any = docData.payload.data();
            let allowed_auth_times_arr: string[] = doc.allowed_auth_times;
            let max_granted_login: number = parseInt(doc.max_granted_login);
            this.getAuthTime().then((currentUserAuthTime) => {
              if (allowed_auth_times_arr && allowed_auth_times_arr.includes(currentUserAuthTime)) {
                resolve(true);
              } else {
                if (allowed_auth_times_arr) {
                  if (allowed_auth_times_arr.length == max_granted_login) {
                    allowed_auth_times_arr.splice(0, 1);      // Delete Oldest Entry
                  }
                  allowed_auth_times_arr.push(currentUserAuthTime);
                  this.updateDBAuthTimesArr(userAuthState.uid, allowed_auth_times_arr).then(() => {
                    resolve(true);
                  }, (error) => {
                    bootbox.alert("Error Occured While Updating Auth Times. Please take screenshot of this and contact June Support team. " + error);
                    reject(false);
                  });
                }
              }
            });
          });
        }else{
          console.error("Authentication Service > OTCheckAndUpdateDBAuthTime > userAuthState is blank");
        }
      });
    });
  }

// Update 

  updateDBAuthTimesArr(uid: string, allowed_auth_times_arr: string[]) {
    return this.db.collection(environment.collctn_users).doc(uid).update({
      allowed_auth_times: allowed_auth_times_arr
    });
  }

// Get Auth Time of Currently Signed in User

 getAuthTime() {
    return new Promise<any>((resolve, reject) => {
      try {
        this._angularFireAuth.authState.pipe(take(1)).subscribe((userAuthState) => {
          if (userAuthState) {
            userAuthState.getIdTokenResult().then((tokenResult) => {
              console.log("Token result obtained. ");
              console.log("Auth time obtained : " + tokenResult.authTime);
              resolve(tokenResult.authTime);
            });
          } else {
            console.error("Blank UserAuthState Captured.");
            reject(null);
          }
        });
      } catch (err) {
        console.error("Error Occured while obtaining the auth time of the user.");
        reject(null);
      }
    });
  }

**// You will be using this in other components. If there is entry of authTime in allowed_auth_times array then keep this user signed in, otherwise signout forcefully.**
  validateAuthTime(uid: string): Observable<boolean> {
    return new Observable<any>((observer) => {
      this.db.collection(environment.collctn_vendor_list).doc(uid).snapshotChanges().subscribe((docData) => {
        let doc: any = docData.payload.data();
        this.getAuthTime().then((currentUserAuthTime) => {
          if (doc.allowed_auth_times.includes(currentUserAuthTime)) {
            observer.next(true);
          } else {
            console.log("ValidateAuthTime > else : Observer returning false.");
            observer.next(false);
            //this.trySignOut().then(() => {
              //this._router.navigate(['/authentication']);
            //});
          }
        });
      });

    });
  }


}