firebase auth

by Zdravko Kolev

通过Zdravko Kolev

如何使用auth和实时数据库构建Firebase Angular应用 (How to build a Firebase Angular app with auth and a real-time database)

For a long time, I was looking for a good Portfolio web app that can help me to easily track my Cryptocurrency profits/losses until I’ve decided to develop such on my own with the help of Firebase and Angular! Yes, it’s that easy, let me explain to you why.

长期以来,我一直在寻找一个好的Portfolio Web应用程序,该应用程序可以帮助我轻松跟踪我的加密货币盈亏,直到我决定借助Firebase和Angular自行开发此类资产! 是的,就是这么简单,让我向您解释原因。

Firebase gives the perfect tooling for applications with user authentication and Real-time database storage needs. It provides rich documentation with a variety of dev examples to help anyone gain a better understanding of how to create stellar apps.

Firebase为具有用户身份验证和实时数据库存储需求的应用程序提供了完美的工具。 它提供了丰富的文档以及各种开发示例,以帮助任何人更好地了解如何创建出色的应用程序。

I have covered the Angular application bootstrapping, using Ignite UI CLI, in another blog post.

我已经在另一篇博客文章中介绍了使用Ignite UI CLI引导Angular应用程序。

This article aims to:

本文旨在:

  • Go through the Firebase installation and setup.完成Firebase的安装和设置。
  • Set up Firebase Authentication.设置Firebase身份验证。
  • Implement Real-time database storing and synchronization.

    实现实时数据库存储和同步。

  • Add Observable data services.添加可观察的数据服务。
  • Visualize the data in an Angular application.

    在Angular应用程序中可视化数据 。

配置Firebase帐户 (Configure a Firebase account)

I want to go through the steps that we’ve taken to set up the Portfolio Firebase account. Projects are created from the Firebase console by choosing Add a new project. Once the Create project form is submitted you will see the following Project Overview.

我想完成设置投资组合Firebase帐户所采取的步骤。 通过选择添加新项目从Firebase控制台创建项目。 提交创建项目表单后,您将看到以下项目概述。

Under the Project Overview section, you can find all development tools that are used for Authentication and Data storing. Here is also located the configuration which is used in the Portfolio Web App. This configuration is generated by pressing Add Firebase to your web app, and it is later added in application’s app.module.ts file.

在“项目概述”部分下,您可以找到用于身份验证和数据存储的所有开发工具。 还可以找到投资组合Web应用程序中使用的配置。 通过将Add Firebase添加到您的Web应用程序来生成此配置,然后将其添加到应用程序的app.module.ts文件中。

Let’s get back to the sidebar on the left and select Authentication. From here we have access to the Sign-in methods that we need in the app. Navigate to the Sign-in tab, there you can see the providers that are enabled and used in the Portfolio application — Google, Facebook and Email/Password provider.

让我们回到左侧的边栏中,然后选择身份验证 。 从这里,我们可以访问应用程序中所需的登录方法 。 导航到“登录”选项卡,您可以在“投资组合”应用程序中看到已启用和使用的提供商-Google ,Facebook和电子邮件/密码提供商

Sign-in providers let users authenticate with Firebase using their Facebook and Google accounts by integrating their logins into the app. As for the Email/password provider, it represents a simple authentication mechanism by using only email and password. Firebase Auth provides built-in validation rules verifying the user entries, so we don’t need to configure something additional here.

登录提供商可以将用户的登录信息集成到应用中,从而使用户可以使用其Facebook和Google帐户向Firebase进行身份验证。 对于电子邮件/密码提供程序,它仅使用电子邮件和密码表示一种简单的身份验证机制。 Firebase Auth提供了内置的验证规则来验证用户条目,因此我们无需在此处进行其他配置。

The “trickiest” part here was the Facebook provider configuration because we needed to have a Facebook application in order to authenticate the login. We’ve created a FB app from Facebook Developers which provided us with the App ID and App Secret requested from Firebase.

这里最“棘手”的部分是Facebook提供程序配置,因为我们需要一个Facebook应用程序才能对登录进行身份验证。 我们已经从Facebook Developers创建了FB应用,该应用为我们提供了Firebase要求的App ID和App Secret。

Both API ID and Secret should be filled when enabling the Facebook provider. As for the Auth redirect URI (from the provider window) it should be pasted under Facebook/Facebook Login/Products section/Valid Auth Redirect URIs.

启用Facebook提供程序时, API IDSecret均应填写。 至于Auth重定向URI (从提供者窗口),应将其粘贴在Facebook/Facebook Login/Products section/Valid Auth Redirect URIs

Let’s continue with the Firebase console. From the Database view page, we’ve created a Real-time Database.

让我们继续使用Firebase控制台。 从数据库视图页面,我们创建了一个实时数据库。

In this view, we can find information about the application data items and write/read security rules. Below are the rules used by the Portfolio application:

在此视图中,我们可以找到有关应用程序数据项和写入/读取安全规则的信息。 以下是投资组合应用程序使用的规则:

{  "rules": {    "items": {      "$uid": {        ".read": "$uid === auth.uid",        ".write": "$uid === auth.uid"      }    }  }}

This Security Rule configuration will allow only authenticated users to be able to read and write in our database. If you want to learn how to define more advanced rules, I strongly recommend checking out the Official Security & Rules section.

此安全规则配置将仅允许经过身份验证的用户读取和写入我们的数据库。 如果您想学习如何定义更高级的规则,强烈建议您查看“ 官方安全和规则”部分。

Okay, where were we? Now that we’ve gone through the Portfolio Firebase account creation, let’s see how the Firebase development project was created.

好吧,我们在哪里? 现在,我们已经完成了投资组合 Firebase帐户的创建,让我们看看Firebase开发项目是如何创建的。

If we didn’t have a project created already, I would have recommended starting with installing the firebase CLI, that provides a variety of tools for managing and deploying Firebase projects. BUT we’ve bootstrapped the Portfolio Angular Project with Ignite UI CLI, so we just needed to install AngularFire and Firebase from npm. We need both packages in order to communicate with Firebase. AngularFire is the official library for Firebase and Angular development.

如果我们还没有创建项目,那么我建议您从安装firebase CLI开始 ,它提供了多种工具来管理和部署Firebase项目。 但是,我们已经使用Ignite UI CLI引导了Portfolio Angular项目 ,因此我们只需要从npm安装AngularFireFirebase 。 我们需要两个软件包才能与Firebase进行通信。 AngularFire是Firebase和Angular开发的官方库。

npm install firebase @angular/fire --save

All AngularFire modules that are used in the application are added in the app.module.ts file:

应用程序中使用的所有AngularFire模块都添加到app.module.ts文件中:

  • FirestoreModule is needed for the database features like working with collections, queries, and services for data streaming and manipulation.

    数据库功能(例如与集合,查询和数据流和处理服务一起使用)需要FirestoreModule

  • FireAuthModule is needed for authentication features like monitoring authentication state, Log-in providers and security.

    FireAuthModule是 监视身份验证状态,登录提供程序和安全性等身份验证功能所需的。

  • FireDatabaseModule allows us to work with Realtime databases. It’s very efficient for mobile and web apps that require synced states across clients in Realtime.

    FireDatabaseModule允许我们使用实时数据库。 对于需要实时在客户端之间同步状态的移动和Web应用程序,它非常高效。

The only common module that is not used in the Portfolio app is AngularFireStorageModule. You can use this module to quickly and easily store and serve user-generated content like photos and videos as well as monitor uploads and metadata associated with files.

组合应用程序中未使用的唯一通用模块是AngularFireStorageModule。 您可以使用此模块快速,轻松地存储和提供用户生成的内容(例如照片和视频),并监视与文件关联的上载和元数据。

Now that we know how the app was configured initially, we can take a look at the other Firebase features that are used.

现在我们知道了应用程序的最初配置方式,接下来我们可以看看所使用的其他Firebase功能

认证方式 (Authentication)

We use AngularFireAuth service to monitor the app authentication state. AngularFireAuth.auth returns an initialized firebase.auth.Auth instance, allowing us to log users in and out. The app demonstrates Sign-in capabilities using three providers: Facebook, Google, and Email.

我们用 AngularFireAuth服务 监视应用程序身份验证状态。 AngularFireAuth.auth返回一个初始化firebase.auth.Auth实例,让我们的用户登录和退出。 该应用程序使用三种提供程序来演示登录功能:Facebook,Google和电子邮件。

Firebase user instance is kept for every provider linked to the user, and when a user is registered or signs in, that user becomes the current user of the Auth instance. The instance persists the user’s state so that refreshing the page or restarting the application doesn’t lose the user’s information.

将为每个与该用户链接的提供程序保留Firebase用户实例,并且当用户注册或登录时,该用户将成为Auth实例的当前用户。 该实例将保持用户的状态,因此刷新页面或重新启动应用程序不会丢失用户的信息。

We use signInWithRedirect method for both Facebook and Google providers, in order to sign in by redirecting to the sign-in page. Password-based account creation is used for the Email sign-in provider, createUserWithEmailAndPassword and signInWithEmailAndPassword are the methods responsible for the user account creation and sign-in.

我们对Facebook和Google提供程序都使用signInWithRedirect方法,以便通过重定向到登录页面进行登录。 基于密码的帐户创建用于电子邮件登录提供程序createUserWithEmailAndPasswordsignInWithEmailAndPassword 是负责创建和登录用户帐户的方法。

I recommend the official Firebase docs for more detailed information on authentication and user lifecycle.

我建议使用Firebase官方文档,以获取有关身份验证和用户生命周期的更多详细信息。

实时数据库操作 (Real-time Database Actions)

Firebase offers two cloud-based, client-accessible database solutions, and we are using Firebase’s original database — Realtime. Check out the differences between Realtime and Cloud firestore on the official documentation page.

Firebase提供了两个基于云的,客户端可访问的数据库解决方案,并且我们正在使用Firebase的原始数据库-Realtime。 在官方文档页面上查看RealtimeCloud firestore之间的区别。

AngularFireDatabase and AngularFireList services are used in the Portfolio app to retrieve, save and remove data easily.

AngularFireDatabaseAngularFireList 组合应用程序中使用服务来轻松检索,保存和删除数据。

AngularFireDatabase can be injected through the constructor of a component or @Injectable() service. In our case we use the second approach:

AngularFireDatabase 可以通过组件的构造函数或@Injectable()注入 服务。 在我们的例子中,我们使用第二种方法 :

Data is retrieved through the AngularFireDatabase service, which fills Observable list of BlockItems. AngularFire provides methods like snapshotChanges() that returns Observable of data as a synchronized array. It is very handy if you want to limit event actions, like added, changed, removed and moved. By default, it listens to all four, however, you may only be interested in one of these events and you can specify which of them you’d like to use. In our application, we are subscribed to all of them.

通过AngularFireDatabase检索数据 服务,该服务填充BlockItems Observable列表。 AngularFire 提供诸如snapshotChanges()类的方法,这些方法以同步数组的形式返回Observable数据。 如果要限制事件动作(例如添加更改删除移动) ,这非常方便。 默认情况下,它会监听全部四个事件,但是,您可能只对其中一个事件感兴趣,并且可以指定要使用的事件。 在我们的应用程序中,我们已订阅所有这些。

Adding a new item, updating an existing one, or removing it from the list is achieved by using push(), update() and remove() methods.

通过使用push()update()remove()方法,可以添加新项目,更新现有项目或将其从列表中remove()

Each data operation method returns a promise, although we don’t need to use the completion promise to indicate success because the real-time database keeps the list in sync.

每个数据操作方法都返回一个Promise,尽管我们不需要使用完成Promise来表示成功,因为实时数据库使列表保持同步。

可观察的 (Observables)

CoinItem服务 (CoinItem service)

Cryptocompare API service manages async data and emits multiple values at a time with Observables. We use HttpClient get()method to request the data from the resource and subscribe to it, in order to transform it to Observable Array of CoinItem objects, which will be used later by our igxGrid, igxList, and igxCard components.

Cryptocompare API服务使用Observables管理异步数据并一次发出多个值。 我们使用HttpClient get( )方法从资源中请求数据并进行订阅,以便将其转换为CoinItem Observable Array 对象,稍后将由我们的igxGridigxListigxCard组件使用。

Rx.js allows us to cache the result of the HTTP Request. We retrieve this data initially, cache it and use the cached version during the application’s lifetime. The combination of publishReply(1, 300000) and refCount() does the following.

Rx.js允许我们缓存HTTP请求的结果。 我们首先检索此数据,对其进行缓存,并在应用程序的生命周期内使用缓存的版本。 publishReply(1, 300000)refCount()执行以下操作。

publishReply(1, 300000) tells Rx to cache the latest emitted value and to stay valid for 5 minutes. After that time, it will invalidate the cache.

publishReply(1,300000)告诉Rx缓存最新发出的值并保持有效5分钟。 在那之后,它将使缓存无效。

refCount() tells Rx to keep the Observable alive as long as there are any Subscribers.

refCount()告诉Rx只要有任何订阅服务器,就保持Observable处于活动状态。

Now after we subscribe to the Coins list, the result will be cached, and we won’t need to make another HTTP Request.

现在,当我们订阅硬币列表之后,结果将被缓存,并且我们不需要发出另一个HTTP请求。

BlockItem服务 (BlockItem service)

Portfolio Crypto Coins data is ensured by getItemsList() method that returns Observable BlockItem array to which the igxGrid component is subscribed to. Only authenticated users can use this service because of the AngularFireList that we manipulate is associated with unique user ids.

通过返回Observable BlockItem数组的getItemsList()方法确保投资组合加密硬币数据 igxGrid组件订阅的对象。 由于我们操作的AngularFireList与唯一的用户ID相关联,因此只有经过身份验证的用户才能使用此服务。

可视化数据 (Visualize the data)

For the visualization, we use UI Components from the Ignite UI for Angularlibrary. These components are responsible for data handling while providing access to custom templates and real-time updates, with intuitive API, by using minimal amount code.

对于可视化,我们使用Ignite UI for Angular库中的UI组件。 这些组件负责数据处理,同时使用最少的代码通过直观的API提供对自定义模板和实时更新的访问。

igxGrid (igxGrid)

Grids [data] property binding is used to pass the returned BlockItem array. Each <igx-column> represents a field of the object and it is used to define features like editing and sorting. The columns are templatable, and with the help of Angular pipes, we can declare display-value transformations in them easily. We use a decimal pipe to change the minimum number of integer digits before the decimal point.

网格 [data]属性绑定用于传递返回的BlockItem数组。 每个<igx-colu mn>代表对象的一个​​字段,它用于定义诸如编辑和排序之类的功能。 这些列是可模板化的,借助Angular管道的帮助,我们可以轻松地在其中声明显示值转换。 我们使用十进制管道来更改小数点前的最小整数位数。

The component provides straightforward event handlers and API for CRUD operations. Handlers like updateRow and deleteRow are implementing additional logic like AngularFireList manipulation and coin item restore logic with the igxSnackbar.

该组件为CRUD操作提供了直接的事件处理程序和API。 像处理程序updateRowdeleteRow正在实施类似的附加逻辑AngularFireList操纵和硬币项与恢复逻辑igxSnackbar

igx卡 (igxCard)

Cards are used to provide general information of Crypto coins using CSS Flexbox layout. These Card components can be filtered with the igxFilter directive, which can be used to filter different data sources. igxFilter can be applied as a pipe or as a directive.

卡用于使用CSS Flexbox布局提供加密硬币的常规信息。 可以使用igxFilter指令过滤这些Card组件,该指令可用于过滤不同的数据源。 igxFilter可以用作管道或指令。

igxFinancialChart (igxFinancialChart)

The Chart offers multiple ways in which the data can be visualized and interpreted, once it is returned by the service. There are several display modes for price and volume, and in our case we use chartType=”candle”.

一旦服务返回数据,图表就提供了多种可视化和解释数据的方式。 价格和数量有几种显示模式,在本例中,我们使用chartType=”candle”

The financial chart component analyzes and selects data columns automatically:- Date/Time column to use for x-axis- Open, High, Low, Close, Volume columns or the first 5 numeric columns for y-axis

金融图表组件分析并选择数据列自动: - Date/Time列于使用了x-axis - OpenHighLowCloseVolume列或前5分数值列y-axis

主题化 (Theming)

IgniteUI for Angular bases its component designs on the Material Design Principles and with just a few lines of code, we can easily change the colors, sizes, typography, and overall look and feel of our components.

IgniteUI for Angular的组件设计基于“ 材料设计原则” ,仅需几行代码,我们就可以轻松更改组件的颜色,大小,版式以及整体外观。

Now that we’ve provided all base definitions needed for the igx-theme, and have configured the igx-dark-theme mixin, we need to only apply .light-theme and .dark-theme CSS classes somewhere at DOM element root level and toggle it on button click.

现在,我们已经提供了igx-theme,所需的所有基本定义igx-theme,并配置了igx-dark-theme mixin,我们只需要在DOM元素根目录级别的某个位置应用.light-theme.dark-theme CSS类即可。单击按钮即可切换。

结果 (Result)

结语 (Wrapping up)

Everything is possible with the right tooling. We have created a Portfolio Web application using the full power of the Angular Framework, Firebase Authentication services, and Cloud Database store/synchronization.

使用正确的工具,一切皆有可能。 我们使用Angular Framework,Firebase身份验证服务和Cloud Database存储/同步的全部功能创建了一个Portfolio Web应用程序。

You can find the GitHub repository and the actual portfolio application here.

您可以在此处找到GitHub存储库和实际的投资组合应用程序 。

Feel free to share in the comments below any questions that you have, suggestions as to what can be improved or changed in the app, or any problems that you’ve encountered while configuring your Firebase account or application.

随时在下面的评论中分享您的任何问题,有关可在应用程序中进行哪些改进或更改的建议,或在配置Firebase帐户或应用程序时遇到的任何问题。

翻译自: https://www.freecodecamp.org/news/firebase-angular-application-with-auth-and-realtime-database-ae37fef5859d/

firebase auth

firebase auth_如何使用auth和实时数据库构建Firebase Angular应用相关推荐

  1. firebase auth_使用Auth0对Firebase和Angular进行身份验证:第1部分

    firebase auth 本文最初发布在Auth0.com博客上 ,并经许可在此处重新发布. 在这个分为两部分的系列教程中,我们将学习如何构建一个使用Auth0身份验证保护Node后端和Angula ...

  2. 如何在ASP.NET Core中使用SignalR构建与Angular通信的实时通信应用程序

    图片 假设我们要创建一个监视Web应用程序,该应用程序为用户提供了一个能够显示一系列信息的仪表板,这些信息会随着时间的推移而更新. 第一种方法是在定义的时间间隔(轮询)定期调用API 以更新仪表板上的 ...

  3. 最佳阵容 | Flutter Firebase 插件更新

    作者 / Chris Sells, Flutter 开发者体验产品经理 Flutter 不仅是一个引擎.一套 widget 和一些工具,它还包括一个庞大的 package 生态系统,让应用得以实现远多 ...

  4. vue firebase_如何使用Vue.js,Vuex,Vuetify和Firebase构建SPA:使用Firebase添加身份验证...

    vue firebase 第4部分:了解如何使用Firebase添加身份验证和购物车 (Part 4: learn how to use Firebase to add authentication ...

  5. firebase使用_如何使用Firebase和React(Hooks)构建实时聊天室

    firebase使用 by Aswin M Prabhu 由Aswin M Prabhu If you are into front-end development, I bet you know w ...

  6. Go实战--golang中使用firebase实时数据库(zabawaba99/firego)

    生命不止,继续 go go go !!! long long ago,写过两篇关于firebase的博客: Firebase介绍(只管写代码,后台交给Firebase) Qt中简单使用Firebase ...

  7. vuex构建vue项目_如何使用Vue.js,Vuex,Vuetify和Firebase构建单页应用程序

    vuex构建vue项目 如何使用Vuetify和Vue路由器安装Vue并构建SPA (How to install Vue and build an SPA using Vuetify and Vue ...

  8. Firebase常用功能和官方Demo简介

    一.Firebase简介 Firebase刚开始是一家实时后端数据库创业公司,它能帮助开发者很快的写出Web端和移动端的应用.自2014年10月Google收购Firebase以来,用户可以在更方便地 ...

  9. iOS Firebase身份验证入门

    Firebas e是一个跨平台的实时移动数据库平台,它使编码人员可以专注于自己最擅长的事情-对应用程序进行编码-而不必担心服务器基础结构和数据库建模等DevOps问题. 在Google的支持下,Fir ...

最新文章

  1. Linux通过端口号杀死指定进程
  2. 在Go中构建区块链 第7部分:网络
  3. 训练过程acc_AI 深度学习训练tricks总结(均有实验支撑)
  4. 使用Hyper-V Server创建Linux虚拟机
  5. centos7 install virt-sysprep
  6. 这是自己的第一篇博客
  7. 汉语语音情绪识别,Emotion Recognition by Speech Signal in Mandarin,音标,读音,翻译,英文例句,英语词典...
  8. linux man指令问题
  9. 商场客流量统计摄像头设备
  10. CocosCreator3D之相机跟随与旋转
  11. 最专业逻辑图和最专业项目文档制作实战讲解
  12. 北京电影学院及中央戏剧学院老师推荐的必看影片,我真是一条一条翻的,一条一条写的,是真的。...
  13. [OpenHarmony RK3568] (二)基础开发
  14. Qt 使用QMovie加载gif图片实现动态等待窗口
  15. 二次函数图像如何用计算机绘制,怎么在WPS表格中绘制二次函数曲线图
  16. 批处理删除指定名称的打印机
  17. 给计算机系学生的建议
  18. 万字整理,肝翻Linux内存管理所有知识点
  19. 对 Xml 文件的操作
  20. APP Invertor 蓝牙BLE 个人案例分享 快速开发自己的蓝牙APP

热门文章

  1. java 多线程阻塞队列 与 阻塞方法与和非阻塞方法
  2. R语言的自定义函数—字符组合
  3. 用1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列,如:512234、412345等,要求:4不能在第三位,3与5不能相连。...
  4. IRasterStatistics Interface
  5. 【362】python 正则表达式
  6. 加速业务交付,从 GKE 上使用 Kubernetes 和 Istio 开始
  7. samba登陆密码不正确
  8. 本地模式运行spark streaming程序(win7安装nc命令通信)
  9. 在Spring boot 配置过滤器(filter)
  10. win2008修改远程端口