Simples App Realtime 2020 Parte 4

Tela de perfil

Nesse vídeo vamos reunir tudo que fizemos nos outros e com isso criar uma tela de perfil, definindo um fluxo criando um usuário, gravando sua imagem de avatar no Cloud Storage, depois gravando os dados na Realtime Dtabase e por fim recuperando esses dados e mostrando na telinha de perfil =D
#firebase

Código construído até agora

<html>
  <head>
    <!-- The core Firebase JS SDK is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-app.js"></script>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
      integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
      crossorigin="anonymous"
    />
    <!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->
    <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-analytics.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-database.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-storage.js"></script>

    <script>
      // Your web app's Firebase configuration
      var firebaseConfig = {
        apiKey: '*********',
        authDomain: '*********',
        databaseURL: '*********',
        projectId: '*********',
        storageBucket: '*********',
        messagingSenderId: '*********',
        appId: '*********',
        measurementId: '*********',
      };
      // Initialize Firebase
      const app = firebase.initializeApp(firebaseConfig);
      const auth = firebase.auth();
      const db = firebase.database();
      const storageRef = firebase.storage().ref();
//auth.signOut();
      //   firebase.analytics();
      // app.auth().signInAnonymously().then(user=>{

      //     // app.database().ref('informacoes').on('value',snapshot=>{
      //     //     console.log(snapshot.val())
      //     // } )
      // })
    </script>
    <style>
      html,
      body {
        width: 100%;
        height: 100%;
        margin: 0%;
        padding: 0%;
      }
      .container {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .cara-de-dentro {
        width: 300px;
        height: 200px;
        display: flex;
        flex-direction: column;
      }
      input[type='file'] {
        display: none;
      }
      .perfil {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
      }
      .avatar {
        width: 200px;
        border-radius: 50%;
        border: 4px solid silver;
        display: none;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="cara-de-dentro form-group">
        <div class="perfil">
          <img class="avatar" src="" />
          <h3></h3>
          <h6></h6>
        </div>
        <input
          type="text"
          class="form-control m-2"
          id="nome"
          placeholder="nome"
        />
        <input
          type="email"
          class="form-control m-2"
          id="email"
          placeholder="email"
        />
        <input
          type="password"
          class="form-control m-2"
          id="senha"
          placeholder="senha"
        />
        <button id="btnImagem" class="btn btn-primary btn-block m-2">
          Selecionar Imagem
        </button>
        <small></small>
        <button id="btnGravar" class="btn btn-primary btn-block m-2">
          Gravar
        </button>

        <input type="file" />
      </div>
    </div>
  </body>
</html>

<script>
  document.querySelector('#btnImagem').addEventListener('click', () => {
    document.querySelector('input[type=file]').click();
  });

  let file = null;
  document.querySelector('input[type=file]').addEventListener('change', (e) => {
    file = e.target.files[0];
    document.querySelector('small').innerHTML = file.name;
     
  });

  function enviarImagem(uid) {
    const uploadTask = storageRef.child('imagens/' + uid).put(file);
    uploadTask.on(
      'state_changed',
      (snapshot) => {
        const progress =
          (snapshot.bytesTransferred / snapshot.totalBytes) * 100;

        console.log('Upload is ' + progress + '% done');
      },
      (erro) => {},
      () => {
        uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {
          gravarUsuarioNaBase(uid, downloadURL);
          console.log('File available at', downloadURL);
        });
      }
    );
  }

  let email = '';
  let senha = '';
  let nome = '';

  document.querySelector('#btnGravar').addEventListener('click', () => {
    email = document.querySelector('input[type=email]').value;
    senha = document.querySelector('input[type=password]').value;
    nome = document.querySelector('input[type=text]').value;

    if (auth.currentUser) {
      const credenciais = obterCredenciais(email, senha);
      linkarUsuario(credenciais);
    } else {
      auth.createUserWithEmailAndPassword(email, senha).then((credentials) => {
        console.log(credentials.user.uid);
        enviarImagem(credentials.user.uid);
      });
    }
  });

  function obterCredenciais(email, senha) {
    return firebase.auth.EmailAuthProvider.credential(email, senha);
  }

  function linkarUsuario(credenciais) {
    auth.currentUser
      .linkWithCredential(credenciais)
      .then((cred) => {
        const user = cred.user;
        enviarImagem(user.uid);
      })
      .catch((error) => {
        console.log(error);
      });
  }

  function gravarUsuarioNaBase(uid, url) {
    db.ref('usuarios')
      .child(uid)
      .set({ id: uid, nome, email, avatarUrl: url })
      .then(() => {
        pegarUsuario(uid);
      });
  }

  function pegarUsuario(uid){
    db.ref('usuarios/' + uid).on('value', (snapshot) => {
          document.querySelector('img').src = snapshot.val().avatarUrl;
          document.querySelector('img').style.display = 'block';
          document.querySelector('h3').innerHTML = snapshot.val().nome;
          document.querySelector('h6').innerHTML = snapshot.val().email;
        });
  }
</script>
1

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *