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 ID和Secret均應填寫。 至于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安裝AngularFire和Firebase 。 我們需要兩個軟件包才能與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
方法,以便通過重定向到登錄頁面進行登錄。 基于密碼的帳戶創建用于電子郵件登錄提供程序createUserWithEmailAndPassword
和signInWithEmailAndPassword
是負責創建和登錄用戶帳戶的方法。
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。 在官方文檔頁面上查看Realtime和Cloud firestore之間的區別。
AngularFireDatabase
and AngularFireList
services are used in the Portfolio app to retrieve, save and remove data easily.
AngularFireDatabase
和AngularFireList
組合應用程序中使用服務來輕松檢索,保存和刪除數據。
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 對象,稍后將由我們的igxGrid
, igxList
和igxCard
組件使用。
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-colu
mn> 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。 像處理程序updateRow
和deleteRow
正在實施類似的附加邏輯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
- Open
, High
, Low
, Close
, Volume
列或前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