martedì 27 dicembre 2016

Autenticazione Firebase con Android

Esempio di autenticazione basata su email/password su Firebase usando un client Android (ripreso dal GitHub ufficiale)
Per prima cosa dalla Consolle di Firebase si deve abilitare l'autenticazione mail/password



e si aggiunge un utente




build.gradle (progetto)
--------------
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
--------------

build.gradle (app)
--------------
apply plugin: 'com.android.application'
android {
    compileSdkVersion 25    buildToolsVersion "23.0.1"    defaultConfig {
        applicationId "com.luca_innocenti.dbfirebase"        minSdkVersion 19        targetSdkVersion 25        versionCode 1        versionName "1.0"        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"    }
    buildTypes {
        release {
            minifyEnabled false            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }
    }
}

dependencies {
    compile  'com.google.firebase:firebase-core:10.0.0'
    compile  'com.google.firebase:firebase-auth:10.0.0'

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'    })
    compile 'com.android.support:appcompat-v7:25.1.0'    compile 'com.android.support:design:25.1.0'    testCompile 'junit:junit:4.12'}
apply plugin: 'com.google.gms.google-services'
--------------


--------------
package com.luca_innocenti.dbfirebase;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.w3c.dom.Text;
import java.util.HashMap;import java.util.Map;
public class MainActivity extends AppCompatActivity {

    TextView mConditionTextView;
    Button mButton;
    Button mLogin;
    Button mInsert;

    DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference mConditionRef = mRootRef.child("condition");
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private static final String TAG = "EmailPassword";


    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mConditionTextView = (TextView) findViewById(R.id.textView2);
        mButton = (Button) findViewById(R.id.button2);
        mInsert = (Button) findViewById(R.id.button5);
        mLogin = (Button) findViewById(R.id.button4);

        // [START initialize_auth]       
       //  Controlla se all'avvio l'utente e' gia' autenticato
                         mAuth = FirebaseAuth.getInstance();
        // [END initialize_auth]
        // [START auth_state_listener]        
                mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                    FirebaseUser user = firebaseAuth.getCurrentUser();
                            if (user != null) {
                                  // User is signed in                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                                  } else {
                                 // User is signed out                    Log.d(TAG, "onAuthStateChanged:signed_out");
                                 }
                      // [START_EXCLUDE]                // [END_EXCLUDE]            }
               };
        // [END auth_state_listener]


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }


    @Override    protected void onStart()
    {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);


        mConditionRef.addValueEventListener(new ValueEventListener() {
            @Override            public void onDataChange(DataSnapshot dataSnapshot) {
                String text = dataSnapshot.getValue(String.class);
                mConditionTextView.setText(text);
            }

            @Override            public void onCancelled(DatabaseError databaseError) {

            }
        });
        mButton.setOnClickListener(new View.OnClickListener(){
            @Override            public void onClick(View view) {
              mConditionRef.setValue("Update");
            }

        });

        mInsert.setOnClickListener(new View.OnClickListener(){
            private DatabaseReference usersRef;

            public void onClick(View view) {
                usersRef = mRootRef.child("condition");

                Map<String,Object> nick = new HashMap<String, Object>();
                nick.put("nome","Luca");
                usersRef.setValue(nick);
                Log.d(TAG,"inserimento");

            }

        });
         

       //se si clicca il pulsante viene richiamata la procedura di autenticazione
      // per semplicita' username e password sono statici
        mLogin.setOnClickListener(new View.OnClickListener(){
            @Override            public void onClick(View view) {
                signIn("lucainnoc@gmail.com","xxxxxxxx");
            }

        });


    }

    @Override    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

//Funzione di autenticazione 
    private void signIn(String email, String password) {
        Log.d(TAG, "signIn:" + email);


        // [START sign_in_with_email]        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());

                        // If sign in fails, display a message to the user. If sign in succeeds                        
                       // the auth state listener will be notified and logic to handle the                      
                      // signed in user can be handled in the listener.                       
                       if (!task.isSuccessful()) {
                            Log.d(TAG, "signInWithEmail:failed", task.getException());
                            Toast.makeText(getApplicationContext(), "Fallito",Toast.LENGTH_SHORT).show();
                        }

                        // [START_EXCLUDE]                        if (!task.isSuccessful()) {
                            Log.d(TAG, "signInWithEmail:successo");
                            Toast.makeText(getApplicationContext(), "Riuscito",Toast.LENGTH_SHORT).show();

                        }
                        // [END_EXCLUDE]                    }
                });
        // [END sign_in_with_email]    }


    @Override    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will        
// automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();

        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
-------------