Letsdoit
@Letsdoit
Компьютерный гик.

Как добавить возможность писать имя при авторизации Firebase + Vue как в социальных сетях?

Делаю твиттер клон для портфолио, теперь передо мной стоит такая задача.
Как внедрить возможность писать человеку свой ник при регистрации с помощью Firebase? Чтобы при дальнейшем, другие зарегистрировавщиеся пользователи могли найти его в поиске и чтобы его имя было на его твитах.
Пример на скрине: 600b68e2b5ed8975753351.jpeg
Все что я сделал сейчас => добавил возможность авторизации Firebase.

Часть кода который я написал:
Vuex store actions.js
login(context, payload) {
    return context.dispatch("auth", {
      ...payload,
      mode: "login",
    });
  },
  signup(context, payload) {
    return context.dispatch("auth", {
      ...payload,
      mode: "signup",
    });
  },
  async auth(context, payload) {
    const mode = payload.mode;

    let url =
      "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyCCNSAOmTiMf6O_eWsGNdH5NqEimYhfiWI";

    if (mode === "signup")
      url =
        "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyCCNSAOmTiMf6O_eWsGNdH5NqEimYhfiWI";

    const response = await fetch(url, {
      method: "POST",
      body: JSON.stringify({
        email: payload.email,
        password: payload.password,
        returnSecureToken: true,
      }),
    });

    const responseData = await response.json();

    if (!response.ok) {
      const error = new Error(
        responseData.message || "Failed to authenticate. Check your login data."
      );
      throw error;
    }
    context.commit("setUser", {
      userId: responseData.localId,
      token: responseData.idToken,
    });
  },


Vue component UserAuth.vue
<template>
  <base-dialog :show="!!error" title="An occured error" @close="handleError">
    {{ error }}
  </base-dialog>
  <base-card>
    <form @submit.prevent="authorization">
      <div class="form-control">
        <label for="email">E-Mail</label>
        <input type="email" id="email" v-model.trim="email" />
      </div>
      <div class="form-control">
        <label for="password">Password</label>
        <input type="password" id="password" v-model.trim="password" />
      </div>
      <p v-if="!inputIsValid">
        Please enter a valid email and password (must be at least 6 characters
        long).
      </p>
      <div class="form-control">
        <base-button>{{ submitButtonCaption }}</base-button>
        <base-button type="button" mode="outline" @click="switchAuthMode">{{
          switchModeButtonCaption
        }}</base-button>
      </div>
    </form>
  </base-card>
</template>

<script>
export default {
  data() {
    return {
      email: "",
      password: "",
      mode: "login",
      inputIsValid: true,
      error: null,
    };
  },
  computed: {
    submitButtonCaption() {
      return this.mode === "login" ? "Login" : "Signup";
    },
    switchModeButtonCaption() {
      return this.mode === "login" ? "Signup instead" : "Login instead";
    },
  },
  methods: {
    async authorization() {
      this.inputIsValid = true;
      if (
        this.email === "" ||
        !this.email.includes("@") ||
        this.password.length < 6
      ) {
        this.inputIsValid = false;
        return;
      }

      const actionPayload = {
        email: this.email,
        password: this.password,
      };

      try {
        if (this.mode === "login") {
          await this.$store.dispatch("login", actionPayload);
        } else {
          await this.$store.dispatch("signup", actionPayload);
        }
        this.$router.replace("/home");
      } catch (err) {
        this.error = err.message || "Failed to authenticate, try later.";
      }
    },
    switchAuthMode() {
      this.mode = this.mode === "login" ? "signup" : "login";
    },
    handleError() {
      this.error = null;
    },
  },
};
</script>
  • Вопрос задан
  • 184 просмотра
Пригласить эксперта
Ответы на вопрос 1
morto
@morto
вечный ученик
Можно при регистрации добавить инпут с именем пользователя, при удачной регистрации брать uid пользователя и создать в базе данных что-то на подобии /users/${uid}/info и добавлять туда имя пользователя.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы