使用Firebase Auth(带有REST),并具有一个单独的firebase数据库,用于存储无法存储在auth中的其他用户信息。注册或登录后,我需要将状态设置为当前用户。
我设法使其正常运行,但是只能通过从数据库中获取所有用户,然后一直循环直到Firebase Auth的Uid匹配。然后提交突变以设置用户。这似乎很笨拙。有更好的方法吗?
import Vuex from 'vuex'
import axios from '@/axios-auth'
import globalAxios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
idToken: null,
userId: null,
user: null
},
mutations: {
authUser(state, userData) {
state.idToken = userData.token
state.userId = userData.userId
},
SET_USER(state, payload) {
state.user = payload
}
},
actions: {
signUp({ commit, dispatch }, authData) {
axios
.post('/signupNewUser?key=[API KEY]', {
email: authData.email,
password: authData.password,
returnSecureToken: true
})
.then(res => {
console.log(res)
commit('authUser', {
token: res.data.idToken,
userId: res.data.localId
})
dispatch('storeUser', authData)
})
.catch(error => console.log(error))
},
storeUser({ commit, state }, userData) {
console.log(userData)
if (!state.idToken) {
return
}
globalAxios.post('/users.json' + '?auth=' + state.idToken, {
name: userData.name,
email: userData.email,
username: userData.username,
userId: state.userId
})
commit('SET_USER', { user: userData })
},
login({ commit, dispatch }, authData) {
axios
.post('/verifyPassword?key=[API KEY]', {
email: authData.email,
password: authData.password,
returnSecureToken: true
})
.then(res => {
console.log(res)
commit('authUser', {
token: res.data.idToken,
userId: res.data.localId
})
dispatch('fetchUser', authData)
})
.catch(error => console.log(error))
},
fetchUser({ commit, state }, payload) {
globalAxios.get('/users.json?auth=' + state.idToken).then(res => {
const data = res.data
const users = []
let cuser = {}
for (let key in data) {
const user = data[key]
if (user.userId === state.userId) {
cuser = user
}
user.id = key
users.push(user)
}
commit('SET_USER', { user: cuser })
})
}
},
getters: {}
})```