使用firebase RESTful API
在完成第一個作品集以後拿到一個面試機會...不過對方詢問有沒有用RESTful API的經驗,當時想著firebase應該沒這功能吧..?沒想到還真的有,所以這邊就記錄一下各種document的位置還有修改方式。
Note:我的專案是用vue寫的,所以有些語法會有ref或是value...可以依照自己的需求修改!
RESTful API
- 網址
- 請求方式
- header
- body
帳戶相關(Authentication)
登入
首先用RESTful API必須要拿到token,而這邊要注意firebase本身就有提供很多種登入情勢,用不同的登入形式的話網址都會不一樣,像我的專案中統一只用帳號密碼登入,在文件中就對應到這裡。
然後可以看到文件的說明如下
curl 'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY]' \
-H 'Content-Type: application/json' \
--data-binary '{"email":"[user@example.com]","password":"[PASSWORD]","returnSecureToken":true}'
-H:header
--data-binary: body
const apiKey= `這裡放上申請的apiKey`
const userInfo = ref(null)
const login = async (loginmail,loginpw) => {
try {
const response = await
fetch(`https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${apiKey}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: loginmail,
password: loginpw,
returnSecureToken: true
})
});
//如果回應200 OK
if (response.ok) {
//開始解析回應的json格式,取得idToken
userInfo.value = await response.json()
console.log(userInfo.value)
localStorage.setItem('idToken', userInfo.value.idToken);
}
}
catch (error) {
handleAuthError(response.error)
console.log(response.error)
}
}
註冊
帳號密碼註冊
curl 'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY]' \
-H 'Content-Type: application/json' \
--data-binary '{"email":"[user@example.com]","password":"[PASSWORD]","returnSecureToken":true}'
匿名註冊
curl 'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY]' \
-H 'Content-Type: application/json' --data-binary '{"returnSecureToken":true}'
返回的內容email值為空
{
"idToken": "[ID_TOKEN]",
"email": "",
"refreshToken": "[REFRESH_TOKEN]",
"expiresIn": "3600",
"localId": "Jws4SVjpT..."
}
獲取當前用戶數據
curl 'https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=[API_KEY]' \
-H 'Content-Type: application/json' --data-binary '{"idToken":"[FIREBASE_ID_TOKEN]"}'
對應到fetchCurrentUser
const getUserInfo = async () => {
try {
//先拿取idToken,並判斷是否存在
const idToken = localStorage.getItem('idToken');
if (idToken) {
const userInfoResponse = await fetch(`https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=${apiKey}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
idToken: idToken
})
});
//解析response,拿取user,displayName,email...等資訊
userData.value = await userInfoResponse.json()
if (userInfoResponse.ok) {
user.value = userData.value.users[0]
displayName.value = userData.value.users[0].displayName
email.value = userData.value.users[0].email
userId.value = userData.value.users[0].localId
if (email.value.length<0) {
//用email長度判斷是否匿名
isAnonymous.value = ture
}
}
}
}
catch (error) {
//如果錯誤就直接刪除idToken
console.log(userData.value)
user.value = null
displayName.value = null
email.value = null
localStorage.removeItem('idToken');
}
}
更新個人資料
curl 'https://identitytoolkit.googleapis.com/v1/accounts:update?key=[API_KEY]' \
-H 'Content-Type: application/json' \
--data-binary \
'{"idToken":"[ID_TOKEN]","email":"[user@example.com]","password":"[PASS]","returnSecureToken":true}'
和使用SDK的時候一樣,再修改密碼的時候要重新驗證一次,否則會跳出"CREDENTIAL_TOO_OLD_LOGIN_AGAIN"的錯誤。
發送重置密碼信件
curl 'https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=[API_KEY]' \
-H 'Content-Type: application/json' \
--data-binary '{"requestType":"PASSWORD_RESET","email":"[user@example.com]"}'
連結當前idToken
curl 'https://identitytoolkit.googleapis.com/v1/accounts:update?key=[API_KEY]' \
-H 'Content-Type: application/json' \
--data-binary \
'{"idToken":"[ID_TOKEN]","email":"[user@example.com]","password":"[PASS]","returnSecureToken":true}'
錯誤訊息響應
出現錯誤時一樣會以json的形式回傳
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalid",
"message": "CREDENTIAL_TOO_OLD_LOGIN_AGAIN"
}
],
"code": 400,
"message": "CREDENTIAL_TOO_OLD_LOGIN_AGAIN"
}
}
資料相關(FireStore)
新增、更改與刪除資料
我到這邊決定先擱置..當初專案設計的資料格式要修改好像有點困難,打算第二個專案再重來!
Comments