lunes, 23 de octubre de 2017

Firebase de Google, creando una primera aplicación

Para describir las funcionalidades que nos permite la Plataforma de Firebase de Google, hace falta todo una nueva reseña. por el momento solo haremos una fast aplication.
 
No vamos al buscador y damos Firebase

- Entramos a la página de firebase y nos logeamos con cuenta de google.
- Agregamos un proyecto, le ponemos nombre y nos da un id del proyecto.
- En este caso agragaremos firebase a nuesttro proyecto de web, esto es tendremos un folder en nuestra computadora donde crearemos archivos web, en este caso index.html, styles.css y app.js

index.html
 <!DOCTYPE html>
<html>
  <head>
    <title>Mi Aplicacion Firebase</title>
  </head>
  <body>
      v1.002
      <h1>Iniciar sesión</h1>
      <button id="login">Inicia con Google</button>
      <div id="root"></div>
      <button id="guardar">Guardar</button>
    
      <script src="https://code.jquery.com/jquery-3.2.1.min.js"
    integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
    crossorigin="anonymous"></script>
      
   
        <script src="https://www.gstatic.com/firebasejs/4.6.0/firebase.js"></script>
        <script>
          // Initialize Firebase
          var config = {
            apiKey: "AIzaSBLABLALBALBLA-LAQUEDEFIREBASEMUOGoROFU7w",
            authDomain: "arrancafirebase.firebaseapp.com",
            databaseURL: "https://arrancafirebase.firebaseio.com",
            projectId: "arrancafirebase",
            storageBucket: "arrancafirebase.appspot.com",
            messagingSenderId: "496630684549"
          };
          firebase.initializeApp(config);
        </script> 
        <script src="app.js"></script>
  </body>
</html>

app.js
var provider=new firebase.auth.GoogleAuthProvider();
$('#login').click(function(){
   firebase.auth()
           .signInWithPopup(provider)
           .then(function(result) {
               console.log(result.user);
               guardaDatos(result.user);
               $('#login').hide();
               $('#root').append("<img width='100px' src='"+result.user.photoURL+"' />")
           });
});

//esta funcion guarda los datos automaticamente
function guardaDatos(user){
    var usuario = {
        uid:user.uid,
        nombre:user.displayName,
        email:user.email,
        phoneNumber:user.phoneNumber,
        foto:user.photoURL
    }
    //firebase.database().ref("telmex")
    //        .push(usuario)
    firebase.database().ref("telmex/" + user.uid)
            .set(usuario)
           
}

//escribir en la base de datos
$('#guardar').click(function(){
    firebase.database().ref("telmex")
            .set({
                nombre:"Bliss",
                edad:"15",
                sexo:"mucho"
            })
});

//aqui estoy leyendo de la base de datos
firebase.database().ref("telmex")
        .on("child_added", function(s){
            var user = s.val();
            $('#root').append("<img width='100px' src='"+user.foto+"' />");
            $('#root').append(user.email)
        })



- Click al botón que dice </>Agregar Firebase a tu app we, nos desplegará un scriptlet que agragaremos a nuestro archivo index.html

 - En el menú izquierdo damos Autenticación -> Configurar el Método de Acceso
  aquí podemos elegir entre correo, telefono, google, facebook, twitter, github... cada uno tiene sus datos que nos pedira para permitirnos el acceso, como id de apps.
- En Database nos permitirá accesar a una base en tiempo real donde guardaremos nuestros datos.
  Damos Database->Comenzar
  Ahora en la pestaña superior damos click en REGLAS
- cambiamos auth != null a true en ambos renglones, el read y write.
- En menú izquierdo damos Click en Hosting.
  Aquí deberemos instalar node.js en nuentra máquina, esto para poder ejecutar comandos de firebase

$ npm install -g firebase-tools

despues accedemos a google
$ firebase login
inicializamos el proyecto

$ firebase init


     ######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

You're about to initialize a Firebase project in this directory:

  C:\Users\Bext\Desktop\HTML5Application\public_html

? Are you ready to proceed? Yes
? Which Firebase CLI features do you want to setup for this folder? Press Space to select features, then Enter to confi
rm your choices.
 ( ) Database: Deploy Firebase Realtime Database Rules
 ( ) Firestore: Deploy rules and create indexes for Firestore
 ( ) Functions: Configure and deploy Cloud Functions
>(*) Hosting: Configure and deploy Firebase Hosting sites

 ( ) Storage: Deploy Cloud Storage security rules

? Which Firebase CLI features do you want to setup for this folder? Press Space to select features, then Enter to confi
rm your choices. Hosting: Configure and deploy Firebase Hosting sites

=== Project Setup

First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add,
but for now we'll just set up a default project.

? Select a default Firebase project for this directory:
  [don't setup a default project]
  Firebase Demo Project (fir-demo-project)
> ArrancaFireBase (arrancafirebase)
  web-Quickstart (web-quickstart-79934)

  [create a new project]

? What do you want to use as your public directory? (public) .
? Configure as a single-page app (rewrite all urls to /index.html)? No
+  Wrote ./404.html
? File ./index.html already exists. Overwrite? No
i  Skipping write of ./index.html

i  Writing configuration info to firebase.json...
i  Writing project information to .firebaserc...


+  Firebase initialization complete!

lo deployamos
$ firebase deploy
C:\Users\Bext\Desktop\HTML5Application\public_html>firebase deploy

=== Deploying to 'arrancafirebase'...

i  deploying hosting
i  hosting: preparing . directory for upload...
+  hosting: 30 files uploaded successfully

+  Deploy complete!

Project Console: https://console.firebase.google.com/project/arrancafirebase/overview
Hosting URL: https://arrancafirebase.firebaseapp.com

C:\Users\Bext\Desktop\HTML5Application\public_html>firebase open
? What link would you like to open?
  Storage: Files
  Storage: Rules
  Hosting
> Hosting: Deployed Site
  Remote Config
  Remote Config: Conditions
  Test Lab
(Move up and down to reveal more choices)

? What link would you like to open? Hosting: Deployed Site
Tip: You can also run firebase open hosting:site

Opening Hosting: Deployed Site link in your default browser:
https://arrancafirebase.firebaseapp.com

Es recomendable respaldar el contenido del directorio de nuestro proyecto de la máquina local, ya que al momento de init, nos hace algunas preguntas sobre reescribir index.html y con un descuido se nos perderá nuestro trabajo.
 
Directorio de C:\Users\Bext\Desktop\HTML5Application\public_html

19/10/2017  08:21 p. m.    <DIR>          .
19/10/2017  08:21 p. m.    <DIR>          ..
20/10/2017  09:51 a. m.             1,261 app.js
20/10/2017  10:57 a. m.               924 comandline
20/10/2017  09:35 a. m.             1,341 index.html
19/10/2017  07:32 p. m.               246 styles.css
               4 archivos          3,772 bytes
               2 dirs  52,328,300,544 bytes libres

C:\Users\Bext\Desktop\HTML5Application\public_html>firebase init

Error: Command requires authentication, please run firebase login

C:\Users\Bext\Desktop\HTML5Application\public_html>firebase login
? Allow Firebase to collect anonymous CLI usage and error reporting information? Yes

Visit this URL on any device to log in:
https://accounts.google.com/o/oauth2/auth?client_id=563584335869-fgrhgmd47bqnekij5i8b5pr03ho849e6.apps.googleusercontent.com&scope=email%20openid%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloudplatformprojects.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Ffirebase%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform&response_type=code&state=575973706&redirect_uri=http%3A%2F%2Flocalhost%3A9005

Waiting for authentication...

+  Success! Logged in as jalbertomr@yahoo.com

C:\Users\Bext\Desktop\HTML5Application\public_html>firebase init

     ######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

You're about to initialize a Firebase project in this directory:

  C:\Users\Bext\Desktop\HTML5Application\public_html

? Are you ready to proceed? Yes
? Which Firebase CLI features do you want to setup for this folder? Press Space to select features, then Enter to confi
rm your choices. Hosting: Configure and deploy Firebase Hosting sites

=== Project Setup

First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add,
but for now we'll just set up a default project.

? Select a default Firebase project for this directory: ArrancaFireBase (arrancafirebase)

=== Hosting Setup

Your public directory is the folder (relative to your project directory) that
will contain Hosting assets to be uploaded with firebase deploy. If you
have a build process for your assets, use your build's output directory.

? What do you want to use as your public directory ? .   <-aqui le damos punto


 ? Configure as a single-page app (rewrite all urls to /index.html)? No
+  Wrote public/404.html
+  Wrote public/index.html

i  Writing configuration info to firebase.json...
i  Writing project information to .firebaserc...

+  Firebase initialization complete!

C:\Users\Bext\Desktop\HTML5Application\public_html>firebase deploy
1

=== Deploying to 'arrancafirebase'...

i  deploying hosting
i  hosting: preparing public directory for upload...
+  hosting: 2 files uploaded successfully

+  Deploy complete!

Project Console: https://console.firebase.google.com/project/arrancafirebase/overview
Hosting URL: https://arrancafirebase.firebaseapp.com


Y ya tenemos lista nuestra aplicación, damos el url que nos muestra arriba, nos logramos por google y nos data nuestar foto y email.






Referencias:
  Telmexhub fixter aplicación con firebase en tiempo record.

1 comentario:

  1. Hola, tengo este error: Uncaught TypeError: Cannot read property 'GoogleAuthProvider' me lo marca en el archivo app.js

    ResponderEliminar