成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

使用Firebase構(gòu)建云端應(yīng)用:創(chuàng)建項目和用戶管理

smartlion / 3695人閱讀

摘要:今天第一期創(chuàng)建項目和用戶管理。我將使用端開發(fā)一個無后端的筆記應(yīng)用。用戶大多數(shù)應(yīng)用都需要了解用戶的身份。也可以使用屬性獲取當(dāng)前已登錄的用戶。如果使用觀察程序跟蹤用戶登錄狀態(tài),則無需處理該情況。

在構(gòu)建自己的在線云工具應(yīng)用時,我使用 Firebase 為自己的“無后端項目”提供服務(wù),把在開發(fā)期間接觸到的一些內(nèi)容整理在一起,制成系列筆記。這個過程有兩個好處:鞏固知識點,整理開發(fā)過程的思路。因為前端開發(fā)是自己所熟悉的領(lǐng)域,所以先從 Firebase 入手,將后端的一些知識點提前梳理理順,避免后續(xù)的學(xué)習(xí)過程中的卡殼而導(dǎo)致無法堅持。今天第一期:創(chuàng)建項目和用戶管理。

什么是 Firebase

Firebase 原本是一家實時后端數(shù)據(jù)庫創(chuàng)業(yè)公司,為提供一個實時響應(yīng)的數(shù)據(jù)服務(wù)。后被 Google 收購,該平臺適用在IOS、Android、web前端等各種跨平臺上,對于沒有數(shù)據(jù)庫處理經(jīng)驗的開發(fā)者,只需使用自己熟悉的語言將數(shù)據(jù)放在Firebase上,再通過Firebase提供的API即可實現(xiàn)實時數(shù)據(jù)同步。同時 Google 在新版的 Firebase 中包含開發(fā)、成長與營收三階段,并整合分析工具,不過分析工具目前只針對移動 App,網(wǎng)頁的話可以繼續(xù)使用 Google Analytics。

何謂“實時數(shù)據(jù)庫”?簡單粗暴的理解就是,數(shù)據(jù)庫中數(shù)據(jù)的變動會互動通知到客戶端。同一賬號在客戶端 A出操作,客戶端 B 會收到相應(yīng)的通知。根據(jù)我在瀏覽器中的調(diào)試,發(fā)現(xiàn)在 Web 端 原來是用的 WebSocket??紤]到寫數(shù)據(jù)時遇到的無網(wǎng)絡(luò)連接問題,F(xiàn)irebase的數(shù)據(jù)庫API使用了本地緩存,使得在離線狀態(tài)下也能保持讀寫不失敗,并且會在網(wǎng)絡(luò)恢復(fù)連接時和服務(wù)器進行同步。

Firebase 提供了四種 SDK: Android,IOS, Web 和 C++。我將使用 Web 端 SDK 開發(fā)一個無后端的筆記應(yīng)用。

關(guān)聯(lián)應(yīng)用

在使用 Firebase 作為后端數(shù)據(jù)庫之前,需要登錄 Firebase 的控制臺,添加一個 Firebase 的網(wǎng)絡(luò)應(yīng)用。你可選擇新建一個應(yīng)用,或者導(dǎo)入一個現(xiàn)有的 Google 項目。

創(chuàng)建完應(yīng)用之后,進入應(yīng)用的控制面板,在 ‘https://console.firebase.goog...’ 中可以看到碩大的綁定入口“將 Firebase 添加到您的網(wǎng)頁應(yīng)用”,點擊之后,將給處的 JavaScript 添加到 HTML 文件中。

 
  

當(dāng)然也可通過 npm 安裝 Firebase 的 SDK npm link,然后通過 Webpack 等工具打包。

npm install --save firebase

引入 Firebase

let firebase = require("firebase");
let app = firebase.initializeApp({ ... });

完整的 Firebase 客戶端包包含了Firebase 的 Authentication, Realtime Database, Storage 和 Cloud Messaging。上面的代碼將會把這些功能全部引入。可以將這些功能以獨立組件的形式引入,減少代碼量。

firebase-app 核心代碼(必需)

firebase-auth Authentication(可選)

firebase-database Realtime Database(可選)

firebase-storage Storage(可選)

firebase-messaging Cloud Messagin(可選)

在這個案例中目前 Storage暫時沒有使用的計劃,Cloud Messaging 針對的是移動端,所以這兩個組件不引入。

let firebase = require("firebase/app");
require("firebase/auth");
require("firebase/database");
 
let app = firebase.initializeApp({ ... });
// ...

完成上述步驟之后,你已經(jīng)可以在環(huán)境中使用 firebase 提供的各種接口了。

用戶

大多數(shù)應(yīng)用都需要了解用戶的身份。知道用戶的身份可以讓應(yīng)用將用戶數(shù)據(jù)安全地保存在云中并跨所有用戶設(shè)備提供相同的個性化體驗。
Firebase Authentication 提供后端服務(wù)、易用 SDK 和現(xiàn)成 UI 庫來向應(yīng)用驗證用戶的身份。它支持使用密碼、深受歡迎的聯(lián)合用戶身份提供商(如 Google、Facebook 和 Twitter)等方法進行身份驗證。

本次案例使用第三方登錄,不使用 Firebase 提供的 UI庫,有興趣的朋友可以自己去試試 https://github.com/firebase/FirebaseUI-Web。

在添加了 Firebase應(yīng)用之后,打開console的 Authentication,在登錄方法中開啟需要的登錄提供商。這里我選擇了“電子郵件地址/密碼”和“Github“兩種方式。

創(chuàng)建基于密碼的帳戶

在用戶填寫表單注冊時,完成所需的任何新帳戶驗證步驟,例如驗證新帳號密碼鍵入正確,或者檢查賬號是否已經(jīng)存在。然后
將郵件地址和密碼傳遞到 createUserWithEmailAndPassword 方法中來創(chuàng)建新帳戶:

firebase.auth().signInWithEmailAndPassword(email, password).catch((error) => {
  // Handle Errors here.
  let errorCode = error.code;
  let errorMessage = error.message;
  // ...
});

用戶首次登錄后,便會建立一個新用戶帳戶并鏈接至該用戶登錄時使用的憑據(jù),即用戶名和密碼,或身份驗證提供程序信息。此新帳戶存儲在 Firebase 項目中,可用于跨項目中的每個應(yīng)用識別用戶,無論該用戶如何登錄。

使用 Github 賬號登錄

在console 中的登錄方式中啟用 github 登錄之后,需要添加從 GitHub 獲得的 OAuth 2.0 客戶端 ID 和客戶端密鑰。同時將你的 Github 應(yīng)用的授權(quán)回調(diào)地址設(shè)置為 Firebase OAuth 重定向 URI(例如 my-app-12345.firebaseapp.com/__/auth/handler)。Github 的應(yīng)用配置

上述前期工作準(zhǔn)備就緒之后,可以開始使用 Firebase SDK 來使用登錄流程。

先創(chuàng)建一個 GitHub 提供程序?qū)ο蟮膶嵗?/p>

let provider = new firebase.auth.GithubAuthProvider();

然后是一個可選的步驟:從身份驗證提供程序中指定您想請求的其他 OAuth 2.0 范圍。調(diào)用 Provider 實例的 addScope方法來添加范圍。例如:

provider.addScope("repo");

詳細參數(shù)可以參考身份驗證提供程序文檔。

接下來,使用 GitHub 提供程序?qū)ο筮M行 Firebase 身份驗證??梢蕴崾居脩簦屍渫ㄟ^打開彈出式窗口或重定向登錄頁面的方法以自己的 GitHub account 登錄。移動設(shè)備最好使用重定向方法。要用彈出式窗口的方法登錄,調(diào)用 signInWithPopup:

firebase.auth().signInWithPopup(provider).then(function(result) {
  // This gives you a GitHub Access Token. You can use it to access the GitHub API.
  let token = result.credential.accessToken;
  // The signed-in user info.
  let user = result.user;
  // ...
}).catch(function(error) {
  // Handle Errors here.
  let errorCode = error.code;
  let errorMessage = error.message;
  // The email of the user"s account used.
  let email = error.email;
  // The firebase.auth.AuthCredential type that was used.
  let credential = error.credential;
  // ...
});

你可以檢索 GitHub 提供程序的 OAuth 令牌,使用該令牌可通過 GitHub API 提取額外數(shù)據(jù)。
還可以通過這種方法捕獲并處理錯誤。獲取錯誤代碼列表。

如果要用重定向登錄頁面的方法登錄,則調(diào)用 signInWithRedirect:

firebase.auth().signInWithRedirect(provider);

不僅如此,你還可以在頁面加載時通過調(diào)用 getRedirectResult 檢索 GitHub 提供程序的 OAuth 令牌:

firebase.auth().getRedirectResult().then(function(result) {
  if (result.credential) {
    // This gives you a GitHub Access Token. You can use it to access the GitHub API.
    let token = result.credential.accessToken;
    // ...
  }
  // The signed-in user info.
  let user = result.user;
}).catch(function(error) {
  // Handle Errors here.
  let errorCode = error.code;
  let errorMessage = error.message;
  // The email of the user"s account used.
  let email = error.email;
  // The firebase.auth.AuthCredential type that was used.
  let credential = error.credential;
  // ...
});

當(dāng)然,你也可以手動處理登錄流程。 在 GitHub 登錄流程結(jié)束后,你會收到一個 OAuth 2.0 訪問令牌。在用戶使用 GitHub 成功登錄之后,先使用 OAuth 2.0 訪問令牌換取 Firebase 憑據(jù):

let credential = firebase.auth.GithubAuthProvider.credential(token);

然后使用 Firebase 憑據(jù)進行 Firebase 身份驗證:

firebase.auth().signInWithCredential(credential).catch(function(error) {
  // Handle Errors here.
  let errorCode = error.code;
  let errorMessage = error.message;
  // The email of the user"s account used.
  let email = error.email;
  // The firebase.auth.AuthCredential type that was used.
  let credential = error.credential;
  // ...
});

除了前面提到的郵箱密碼驗證,第三方 OAuth 驗證之外,F(xiàn)irebase 還支持自定義身份認證系統(tǒng)和匿名身份驗證,這里不講,有興趣和需求的朋友可以自己去了解。

其他用戶管理操作的支持

要注銷用戶,調(diào)用 signOut:

firebase.auth().signOut().then(() => {
  // Sign-out successful.
}, function(error) {
  // An error happened.
});

除此之外,SDK 還提供了一系列用戶管理的方法。

獲取當(dāng)前登錄的用戶

獲取當(dāng)前用戶的推薦方法是在 Auth 對象上調(diào)用onAuthStateChanged方法,這可確保在您獲取當(dāng)前用戶時,Auth 對象不會處于中間狀態(tài),例如初始化。既要么未登錄,要么已登錄。

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

也可以使用 currentUser 屬性獲取當(dāng)前已登錄的用戶。 如果用戶沒有登錄,currentUser 則為 null:

let user = firebase.auth().currentUser;

if (user) {
  // User is signed in.
} else {
  // No user is signed in.
}

不過有一點要注意,currentUser 還可能由于 auth 對象尚未完成初始化而為 null。 如果使用觀察程序跟蹤用戶登錄狀態(tài),則無需處理該情況。
當(dāng)獲取到用戶對象的實例之后,可以訪問實例上的一些屬性,以及調(diào)用實例上的一些方法對用戶進行一些操作,比如:

要獲取用戶的個人資料信息:

let user = firebase.auth().currentUser;
let name, email, photoUrl, uid;

if (user != null) {
  name = user.displayName;
  email = user.email;
  photoUrl = user.photoURL;
  uid = user.uid;  // The user"s ID, unique to the Firebase project. Do NOT use
                   // this value to authenticate with your backend server, if
                   // you have one. Use User.getToken() instead.
}

獲取用戶的特定于提供程序的個人資料信息(登錄提供程序中獲取檢索到的個人資料信息)

let user = firebase.auth().currentUser;

if (user != null) {
  user.providerData.forEach(function (profile) {
    console.log("Sign-in provider: "+profile.providerId);
    console.log("  Provider-specific UID: "+profile.uid);
    console.log("  Name: "+profile.displayName);
    console.log("  Email: "+profile.email);
    console.log("  Photo URL: "+profile.photoURL);
  });
}

更新用戶個人資料(顯示名稱和頭像地址)

let user = firebase.auth().currentUser;

user.updateProfile({
  displayName: "Jane Q. User",
  photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(function() {
  // Update successful.
}, function(error) {
  // An error happened.
});

設(shè)置電子郵件地址

let user = firebase.auth().currentUser;

user.updateEmail("[email protected]").then(function() {
  // Update successful.
}, function(error) {
  // An error happened.
});

要設(shè)置用戶的電子郵件地址,該用戶必須最近登錄過。在 Firebase 控制臺的"Authentication"的"Email Templates"頁面中允許自定義使用的電子郵件模板。

設(shè)置用戶密碼

let user = firebase.auth().currentUser;
let newPassword = getASecureRandomPassword();

user.updatePassword(newPassword).then(function() {
  // Update successful.
}, function(error) {
  // An error happened.
});

刪除用戶

也可以在控制臺中手動刪除用戶

let user = firebase.auth().currentUser;

user.delete().then(function() {
  // User deleted.
}, function(error) {
  // An error happened.
});

有些安全敏感性操作,比如刪除帳戶、設(shè)置主電子郵件地址和更改密碼,需要用戶最近登錄過才能執(zhí)行。如果要執(zhí)行這些操作中的某一項,而用戶只是在很久以前登錄過,操作便出錯。發(fā)生這種錯誤時,需要從用戶獲取新登錄憑據(jù),將該憑據(jù)傳給 reauthenticate ,對該用戶重新進行身份驗證。

let user = firebase.auth().currentUser;
let credential;

// Prompt the user to re-provide their sign-in credentials

user.reauthenticate(credential).then(function() {
  // User re-authenticated.
}, function(error) {
  // An error happened.
});
結(jié)束

如此一來,我的應(yīng)用已經(jīng)可以支持郵箱密碼登錄,github 賬號登錄。而且用戶的管理操作也有很直接明了的方法。當(dāng)用戶添加之后,接下來就可以圍繞用戶設(shè)計出需要的數(shù)據(jù)結(jié)構(gòu)了。下回:數(shù)據(jù)結(jié)構(gòu)的定義及數(shù)據(jù)的操作,敬請期待

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/86486.html

相關(guān)文章

  • 2019 - Web開發(fā)技術(shù)指南趨勢

    摘要:以下內(nèi)容來自我特別喜歡的一個頻道這是一個年你成為前端,后端或全棧開發(fā)者的進階指南你不需要學(xué)習(xí)所有的技術(shù)成為一個開發(fā)者這個指南只是通過簡單分類列出了技術(shù)選項我將從我的經(jīng)驗和參考中給出建議首選我們會介紹通用的知識最后介紹年的的一些趨勢基礎(chǔ)前端開 以下內(nèi)容來自我特別喜歡的一個Youtube頻道: Traversy Media 這是一個2019年你成為前端,后端或全棧開發(fā)者的進階指南: 你...

    sourcenode 評論0 收藏0
  • Vuex + Firebase 構(gòu)建 Notes App

    摘要:前幾天翻譯了基于這篇博客的文章用構(gòu)建一個筆記應(yīng)用。概述如果熟悉的使用,可以放心地跳過這一段。存的數(shù)據(jù)都是對象。修改的邏輯簡單來說就是在思路上要完成從數(shù)組到對象的轉(zhuǎn)換。把以上各條添加到里面。 前幾天翻譯了基于這篇博客的文章:用 Vuex 構(gòu)建一個筆記應(yīng)用。在此基礎(chǔ)上我對它做了一些更新: 把數(shù)據(jù)同步到 Firebase 上,不會每次關(guān)掉瀏覽器就丟失數(shù)據(jù)。 加了筆記檢索功能 為保證代碼整潔...

    Invoker 評論0 收藏0
  • 模型,保存數(shù)據(jù)到數(shù)據(jù)庫

    摘要:文章來源模型,保存數(shù)據(jù)到數(shù)據(jù)庫環(huán)境搭建以及使用創(chuàng)建第一個靜態(tài)頁面引入計算屬性動態(tài)內(nèi)容繼續(xù)為讀者介紹如何使用構(gòu)建一個完整的復(fù)雜的項目。 文章來源:模型,保存數(shù)據(jù)到數(shù)據(jù)庫 環(huán)境搭建以及使用Ember.js創(chuàng)建第一個靜態(tài)頁面 引入計算屬性、action、動態(tài)內(nèi)容 繼續(xù)為讀者介紹如何使用Ember構(gòu)建一個完整的、復(fù)雜的項目。 第一個Ember.js模型 在前面兩篇中實現(xiàn)了如何獲取界面輸入的...

    paulli3 評論0 收藏0
  • 云服務(wù)搭臺,AI唱戲,這是一場不遜于I/O的Google科技大會

    摘要:當(dāng)?shù)貢r間月日,在結(jié)束的一個半月后,名開發(fā)者再度聚首舊金山。截止到,公司資本支出為億美元,相當(dāng)于去年同期的億美元的兩倍。即使是自認為對 Google 非常熟悉的人們,也可能沒有聽過 Cloud Next 大會的名字。這是 Google I/O 以外,這家公司又一個吸粉無數(shù)的開發(fā)者盛會。當(dāng)?shù)貢r間 7 月 24 日,在 I/O 結(jié)束的一個半月后,25000 名 Google Cloud 開發(fā)者再度...

    stonezhu 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<