将Firebase身份验证集成到AngularDart应用中

时间:2018-07-10 16:00:23

标签: firebase dart firebase-authentication angular-dart

我找不到关于如何将 Firebase 身份验证(Google,电子邮件,电话等)集成到 AngularDart (版本)的清晰完整的解释5)应用。

你能给我吗?或者,您能告诉我在哪里找到它吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

firebase_dart_ui为我工作。该存储库也包含一个example

答案 1 :(得分:0)

同样。我花了很长时间试图找到一些东西。虽然是Angular Dart these examples的新手,但在不错的地方确实可以工作。回购中包含简单的auth +电话和存储等示例。

md简要介绍了您需要在Firebase控制台中进行设置的内容,还需要允许主机访问Cloud Console中由Firebase生成的密钥。

正如Gazihan所说,如果您想使用Firebase UI,firebase_dart_ui软件包将使用Google等登录,并同意,在查找步骤方面很难遵循。我必须更改开发人员依赖项才能使其正常工作,但确实做到了:

dev_dependencies:
  build_runner: ^1.7.0
  build_test: ^0.10.8
  build_web_compilers: ^2.4.0

以下来自FirebaseDart存储库的user / pwd登录示例更加直接,可能会有所帮助。

首先,从项目的Firebase设置页面获取您的App详细信息。

index.dart

import 'dart:convert';
import 'dart:html';

import 'package:firebase/firebase.dart' as fb;

main() async {

  try {
    fb.initializeApp(
        apiKey: "your api key",
        authDomain: "your auth domain",
        databaseURL: "your database url",
        storageBucket: "your storage bucket");

    AuthApp();
  } on fb.FirebaseJsNotLoadedException catch (e) {
    print(e);
  }
}

class AuthApp {
  final fb.Auth auth;
  final FormElement registerForm;
  final InputElement email, password;
  final AnchorElement logout;
  final TableElement authInfo;
  final ParagraphElement error;
  final SelectElement persistenceState, verifyEmailLanguage;
  final ButtonElement verifyEmail;
  final DivElement registeredUser, verifyEmailContainer;

  AuthApp()
      : this.auth = fb.auth(),
        this.email = querySelector("#email"),
        this.password = querySelector("#password"),
        this.authInfo = querySelector("#auth_info"),
        this.error = querySelector("#register_form p"),
        this.logout = querySelector("#logout_btn"),
        this.registerForm = querySelector("#register_form"),
        this.persistenceState = querySelector("#persistent_state"),
        this.verifyEmail = querySelector('#verify_email'),
        this.verifyEmailLanguage = querySelector('#verify_email_language'),
        this.registeredUser = querySelector("#registered_user"),
        this.verifyEmailContainer = querySelector("#verify_email_container") {
    logout.onClick.listen((e) {
      e.preventDefault();
      auth.signOut();
    });

    this.registerForm.onSubmit.listen((e) {
      e.preventDefault();
      var emailValue = email.value.trim();
      var passwordvalue = password.value.trim();
      _registerUser(emailValue, passwordvalue);
    });

    // After opening
    if (auth.currentUser != null) {
      _setLayout(auth.currentUser);
    }

    // When auth state changes
    auth.onAuthStateChanged.listen(_setLayout);

    verifyEmail.onClick.listen((e) async {
      verifyEmail.disabled = true;
      verifyEmail.text = 'Sending verification email...';
      try {
        // you will get the verification email in selected language
        auth.languageCode = _getSelectedValue(verifyEmailLanguage);
        // url should be any authorized domain in your console - we use here,
        // for this example, authDomain because it is whitelisted by default
        // More info: https://firebase.google.com/docs/auth/web/passing-state-in-email-actions
        await auth.currentUser.sendEmailVerification(
            fb.ActionCodeSettings(url: "followmyvoyage.firebaseapp.com"));
        verifyEmail.text = 'Verification email sent!';
      } catch (e) {
        verifyEmail
          ..text = e.toString()
          ..style.color = 'red';
      }
    });
  }

  _registerUser(String email, String password) async {
    if (email.isNotEmpty && password.isNotEmpty) {
      var trySignin = false;
      try {
        // Modifies persistence state. More info: https://firebase.google.com/docs/auth/web/auth-state-persistence
        var selectedPersistence = _getSelectedValue(persistenceState);
        await auth.setPersistence(selectedPersistence);
        await auth.createUserWithEmailAndPassword(email, password);
      } on fb.FirebaseError catch (e) {
        if (e.code == "auth/email-already-in-use") {
          trySignin = true;
        }
      } catch (e) {
        error.text = e.toString();
      }

      if (trySignin) {
        try {
          await auth.signInWithEmailAndPassword(email, password);
        } catch (e) {
          error.text = e.toString();
        }
      }
    } else {
      error.text = "Please fill correct e-mail and password.";
    }
  }

  String _getSelectedValue(SelectElement element) =>
      element.options[element.selectedIndex].value;

  void _setLayout(fb.User user) {
    if (user != null) {
      registerForm.style.display = "none";
      registeredUser.style.display = "block";
      email.value = "";
      password.value = "";
      error.text = "";

      var data = <String, dynamic>{
        'email': user.email,
        'emailVerified': user.emailVerified,
        'isAnonymous': user.isAnonymous,
        'metadata.creationTime': user.metadata.creationTime,
        'metadata.lastSignInTime': user.metadata.lastSignInTime
      };

      data.forEach((k, v) {
        if (v != null) {
          var row = authInfo.addRow();

          row.addCell()
            ..text = k
            ..classes.add('header');
          row.addCell().text = "$v";
        }
      });

      print('User.toJson:');
      print(const JsonEncoder.withIndent(' ').convert(user));

      verifyEmailContainer.style.display =
          user.emailVerified ? "none" : "block";
    } else {
      registerForm.style.display = "block";
      registeredUser.style.display = "none";

      authInfo.children.clear();
    }
  }
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Auth demo</title>
  <style type="text/css">
    #register_form p {
      color: red;
    }
    #auth_info td {
      padding: 1px;
    }
    #auth_info td.header {
      font-weight: bold;
      text-align: right;
    }
  </style>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
  <h1>Auth demo</h1>
  <form id="register_form" style="display: none">
    <h2>Register</h2>
    <p></p>
    <label for="persistent_state">State persistence type</label>
    <select id="persistent_state">
      <option value="local">LOCAL</option>
      <option value="session">SESSION</option>
      <option value="none">NONE</option>
    </select>
    <br>
    <input type="email" placeholder="Your E-mail" id="email">
    <input type="password" placeholder="Your Password" id="password">
    <input type="submit" value="Register me">
  </form>
  <div id="registered_user" style="display: none">
    <table id="auth_info">
    </table>
    <div id="verify_email_container">
      <h2>Send verify email</h2>
      <label for="verify_email_language">Email language</label>
      <select id="verify_email_language">
        <option value="en">English</option>
        <option value="cs">Czech</option>
        <option value="de">German</option>
        <option value="fr">French</option>
      </select>
      <button id="verify_email">Verify email</button>
    </div>
    <a href="#" id="logout_btn">Log out</a>
  </div>
</div>
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-auth.js"></script>
<script defer src="index.dart.js" type="application/javascript"></script>
</body>
</html>

pubspec.yaml

dependencies:
firebase: ^5.0.0
http: '>=0.11.3 <0.13.0'
js: ^0.6.0

这个答案到处都是,希望在两个例子之间讨论它是有用的。