首页 > 解决方案 > 如何添加 firebase 规则以仅允许使用实时数据库访问一封用户电子邮件?

问题描述

我正在使用这些规则。

{
  "rules": {
      ".read": "auth != null",
        ".write": "auth != null",
      "registries":{
        "uid": {
    "user": {     
         ".read": "auth.token.email.matches(/.*augustomarce100@hotmail.com$/) && auth != null",
        ".write": "auth.token.email.matches(/.*augustomarce100@hotmail.com$/) && auth != null",
}
      }
    }
  }
}
 

我也尝试使用这些规则,但它们不起作用。

{
"rules":{
 "user": {
   "$uid": {
     "email": ***<email>*** this part isnt working
   }
 },
 "whitelist": {
   "augustomarce100@hotmail%2Ecom": true,
 }  
 }
}

{
  "rules": {
registries:{
"$uid": {
    "user": {
        ".read": "true",
        ".write": "root.child('whitelist').child(newData.child('email').val().replace('.', '%2E')).exists()"
      }
    }
  }
}
}

我只想允许一封电子邮件访问该页面。如果我以后想添加更多电子邮件,我认为白名单选项是最好的。我使用此代码登录:

    import { Router } from '@angular/router';
import { AuthService } from 'src/app/services/auth.service';
import { ConfigService } from 'src/app/services/config.service';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFireFunctions } from '@angular/fire/functions';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  public formLogin: FormGroup;
  public showLoginError: boolean;

  constructor(
    private afAuth: AngularFireAuth,
    private afFunction: AngularFireFunctions,
    private formBuilder: FormBuilder,
    public config: ConfigService,
    private authService: AuthService,
    private route: Router
  ) {


    this.formLogin = this.formBuilder.group({
      email: new FormControl('', [Validators.required, Validators.email]),
      pass: new FormControl('', Validators.required)
    })
    this.showLoginError = false;
  }

  ngOnInit() {
  }

  /**
   * Compruebo si el login es correcto
   */
  checkLogin() {

    // Cojo el email y el pass
    let email = this.formLogin.get('email').value
    let pass = this.formLogin.get('pass').value

    // Nos logueamos
    this.authService.login(email, pass).then(state => {

      console.log(state);

      this.route.navigate(['/resume'])

    }, error => {
      console.error(error);
      this.showLoginError = true;
    })

  }

   }

我将此代码用于 auth.service:

   import { Router } from '@angular/router';
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';



@Injectable({
  providedIn: 'root'
})
export class AuthService {



  private _isLoggued: boolean;

  set isLoggued(value: boolean) {
    this._isLoggued = value;
  }

  constructor(
    private afAuth: AngularFireAuth,
    private route: Router
  ){
    this._isLoggued = false;
    // Compruebo si estoy subscrito
    this.afAuth.authState.subscribe(user => {
      if (user) {
        this._isLoggued = true;
        this.route.navigate(['/resume']);
      }
      })
    }
  /**
   * Compruebo si estoy logueado
   */
  isAuthenticated() {
    return this._isLoggued;
  }

  /**
   * Me logueo dado un email y contraseña, devuelve una promesa
   * @param email email del usuario
   * @param pass pass del usuario
   */
  login(email: string, pass: string) {
    return this.afAuth.auth.signInWithEmailAndPassword(email, pass);
  }

  /**
   * Nos desploguea de la aplicacion
   */
  logout() {
    this.afAuth.auth.signOut();
    this._isLoggued = false;
    this.route.navigate(['/login']);
  }

  /**
   * Comprueba si el usuario existe, dado un email
   * @param email email del usuario a comprobar
   */
  checkAccount(email) {
    return this.afAuth.auth.isSignInWithEmailLink(email);
  }

  /**
   * Devuelve el usuario actual
   */
  currentUser() {
    if (this.afAuth.auth.currentUser) {
      return this.afAuth.auth.currentUser.email;
    }
    return '';
  }

  /**
   * Crea una cuenta dado un email y un pass. Devuelve una promesa
   * @param email email del usuario a crear
   * @param pass pass del usuario a crear
   */
  createAccount(email: string, pass: string) {

    // Chequeo si la cuenta existe
   if(this.checkAccount(email)){
  return new Promise((resolve, reject) => {
    reject('el usuario ya existe')

      })
    } else {
      // Creo la cuenta y devuelvo una promesa con el estado
      return this.afAuth.auth.createUserWithEmailAndPassword(email, pass).then(authState => {
        return authState;
      }).catch(error => {
        throw error;
      })
    }

  }
  async resetPassword(email: string): Promise<void> {
    try {
      return this.afAuth.auth.sendPasswordResetEmail(email);
    } catch (error) {
      console.log(error);
    }
  }
}

我试图为我的页面增加更多的安全性,我只想通过电子邮件允许某些用户完全访问其他用户仅用于阅读,我使用实时数据库,因为我熟悉它,请帮助,我被困在这里。

标签: javascriptangularfirebase-realtime-databasefirebase-security

解决方案


推荐阅读