簡體   English   中英

雲 Function 更新用戶配置文件,但阻止用戶使用相同的用戶名

[英]Cloud Function updating user profile, but prevents users having same username

我目前正在編輯配置文件雲 function。 我有一個 where 子句,查看我的 users 集合中的用戶名是否與 req.body.username 相同,如果是,則阻止請求。 問題是; 但是,我收到如下所示的錯誤:> 錯誤:參數“值”的值不是有效的查詢約束。“未定義”值僅在 object 屬性中被忽略。

 at Object.validateUserInput (/Users/robterrell/Desktop/safespace/functions/node_modules/@google-cloud/firestore/build/src/serializer.js:265:19) at validateQueryValue (/Users/robterrell/Desktop/safespace/functions/node_modules/@google-cloud/firestore/build/src/reference.js:2135:18) at CollectionReference.where (/Users/robterrell/Desktop/safespace/functions/node_modules/@google-cloud/firestore/build/src/reference.js:1033:9) at exports.profileUpdate (/Users/robterrell/Desktop/safespace/functions/api/users.js:216:6) at Layer.handle [as handle_request] (/Users/robterrell/Desktop/safespace/functions/node_modules/express/lib/router/layer.js:95:5) at next (/Users/robterrell/Desktop/safespace/functions/node_modules/express/lib/router/route.js:137:13) at /Users/robterrell/Desktop/safespace/functions/util/auth.js:30:14 at processTicksAndRejections (internal/process/task_queues.js:85:5)"

如果我發送的請求中的用戶名也已在我的用戶集合中使用,那么 where 子句似乎沒有出現。 我不確定我目前做錯了什么。 我通過 postman 發送一個發布請求來調用這個 function。 我的 function 看起來像這樣:

exports.profileUpdate = (req, res) => {
  if (req.user.email) {
    admin.auth().updateUser(req.user.uid, { email: req.body.email })
  }

  let document = db
    .collection('users')
    .where('username', '==', req.body.username)
  document
    .get()
    .then(snapshot => {
      if (snapshot.empty) {
        snapshot.forEach(doc => {
          const data = doc.id
          db.collection('users').doc(data).update(req.body)
        })
        return res.json({ message: 'Updated Successfully' })
      } else {
        return res
          .status(400)
          .json({ username: 'this username is already taken' })
      }
    })
    .catch(error => {
      console.error(error)
      return res.status(400).json({
        message: 'Cannot Update the value'
      })
    })
}

我將 formData(detailsToUpdate) 傳遞給我的 function,這是通過使用 express 命中端點來觸發的。 function 看起來像這樣:

import React, { useState } from 'react'
import { Text, Input, Icon } from '@ui-kitten/components'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import { View, StyleSheet, TouchableOpacity, Image } from 'react-native'
import AsyncStorage from '@react-native-community/async-storage'
import axios from 'axios'

const updateUsername = ({ navigation, route }) => {
  const [errorMessage, setErrorMessage] = useState('')
  const { user } = route.params
  const [detailsToUpdate, setDetailsToUpdate] = useState({
    username: user.username,
    userId: user.userId
  })

  const handleProfileUpdate = async () => {
    try {
      const token = await AsyncStorage.getItem('FBIdToken')
      console.log('im running')
      const response = await axios({
        method: 'POST',
        url:
          'http://localhost:5000/safe-space-dev/us-central1/api/users/update',
        headers: { Authorization: `Bearer ${token}` },
        data: detailsToUpdate
      })
      // merges the current user data in storage w/ updated details.
      await AsyncStorage.mergeItem(
        'userDetails',
        JSON.stringify(detailsToUpdate)
      )
      alert(response.data.message)
    } catch (error) {
      setErrorMessage(error)
    }
  }

  return (
    <KeyboardAwareScrollView
      extraScrollHeight={20}
      enableOnAndroid={true}
      keyboardShouldPersistTaps='handled'
      style={{ backgroundColor: '#fff' }}
    >
      <View>
        <View
          style={{
            paddingRight: 20,
            paddingLeft: 20
          }}
        >
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',

              marginTop: 20
            }}
          >
            <TouchableOpacity
              onPress={() => {
                /* 1. Navigate to the Details route with params */
                navigation.navigate('EditProfile')
              }}
            >
              <Icon
                style={{ height: 28, width: 28 }}
                name='chevron-left'
                fill='black'
              />
            </TouchableOpacity>
            <TouchableOpacity onPress={handleProfileUpdate}>
              <Text>Done</Text>
            </TouchableOpacity>
          </View>

          <View
            style={{
              marginTop: 20,
              paddingRight: 20,
              paddingLeft: 20
            }}
          ></View>
          <View
            style={{
              height: 75
            }}
          >
            <Text category='p1' appearance='hint' style={{ fontSize: 12 }}>
              Username
            </Text>

            <Input
              value={detailsToUpdate.username}
              autoCapitalize='none'
              autoComplete={false}
              onChangeText={value =>
                setDetailsToUpdate({ ...detailsToUpdate, username: value })
              }
            />
          </View>
        </View>
      </View>
    </KeyboardAwareScrollView>
  )
}

export default updateUsername

然后是快速路由的中間件:

const { admin, db } = require('./admin')

module.exports = (request, response, next) => {
  let idToken
  if (
    request.headers.authorization &&
    request.headers.authorization.startsWith('Bearer ')
  ) {
    idToken = request.headers.authorization.split('Bearer ')[1]
  } else {
    console.error('No token found')
    return response.status(403).json({ error: 'Unauthorized' })
  }
  admin
    .auth()
    .verifyIdToken(idToken)
    .then(decodedToken => {
      request.user = decodedToken
      return db
        .collection('users')
        .where('userId', '==', request.user.uid)
        .limit(1)
        .get()
    })
    .then(data => {
      request.user.username = data.docs[0].data().username
      request.user.imageUrl = data.docs[0].data().imageUrl
      request.user.dob = data.docs[0].data().dob
      request.user.userId = data.docs[0].data().userId
      return next()
    })
    .catch(err => {
      console.error('Error while verifying token', err)
      return response.status(403).json(err)
    })
}

根據錯誤消息, req.body.usernameundefined 驗證您在請求中發送了正確的正文,或者它沒有在其他中間件中被刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM