Android Studio Firebase Authentication İşlemleri

Firebase Kütüphanesinin sunmuş olduğu bir çok özellikten biri olan Firebase Authentication(Kimlik Doğrulama) uygulamamıza bir çok şekilde(Facebook,Eposta,Twitter) kimlik doğrulama olanağı sağlar. Bu makalemizde de Eposta ile kimlik doğrulama işlemini anlatmaya çalıştım. Öncelikle projemize Firebase Kütüphanesini tanıtmamız gerekiyor.
Üst pencereden Firebase>>Tools sekmesini açıyoruz ve aşağıdaki resimlerde numaralı yerleri aktif hale getiriyoruz.
En son hali aşağıdaki resim gibi olması gerekiyor.
Bu adımlardan sonra buraya tıklayarak açılan pencerede projeye verdiğimiz isim hangisi ise onu seçiyoruz(Ben deneme123 vermiştim).Aşağıdaki adımları uyguluyoruz.
Böylelikle Firebase Console’dan Eposta ile giriş yapmayı aktif hale getirdik artık kodlama kısmına geçebiliriz.
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.esatgozcu.firebaseauthenticationislemleri2.MainActivity"> <ScrollView android:layout_width="368dp" android:layout_height="495dp" tools:layout_editor_absoluteX="8dp" tools:layout_editor_absoluteY="8dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="150dp" app:srcCompat="@drawable/chat" /> <EditText android:id="@+id/kullaniciadi" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Kullanıcı Adı" android:inputType="textPersonName" /> <EditText android:id="@+id/sifre" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Şifre" android:inputType="textPersonName" /> <Button android:id="@+id/girisbuton" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/holo_red_dark" android:text="GİRİŞ" android:textColor="@android:color/white" /> <Button android:id="@+id/kayitbuton" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/white" android:text="KAYIT OL" android:textColor="@android:color/black" tools:background="@android:color/white" /> </LinearLayout> </ScrollView> </android.support.constraint.ConstraintLayout> |
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
package com.example.esatgozcu.firebaseauthenticationislemleri2; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; 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; public class MainActivity extends AppCompatActivity { private EditText kullaniciadi; private EditText sifre; private Button girisbuton; private Button kayitbuton; private FirebaseAuth mAuth; private FirebaseUser firebaseUser; private String userName; private String userPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); kullaniciadi=(EditText)findViewById(R.id.kullaniciadi); sifre=(EditText)findViewById(R.id.sifre); girisbuton=(Button)findViewById(R.id.girisbuton); kayitbuton=(Button)findViewById(R.id.kayitbuton); //Oturum açık olup olmadığını anlamak için firebaseUser değişkenine değer döndürüyoruz mAuth = FirebaseAuth.getInstance(); firebaseUser = mAuth.getCurrentUser(); //Session açık olup olmadığını kontrol ediyor if(firebaseUser != null){ //Açıksa ProfilSayfasına gidiyor Intent i = new Intent(MainActivity.this,ProfilSayfasi.class); startActivity(i); finish(); } girisbuton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { userName = kullaniciadi.getText().toString(); userPassword = sifre.getText().toString(); if(userName.isEmpty() || userPassword.isEmpty()){ //Kullanıcı Adı ve Şifre alanlarının girilip girilimediği kontrol ediliyor Toast.makeText(getApplicationContext(),"Boş Alan Bırakmayınız!",Toast.LENGTH_SHORT).show(); }else{ Giris(); } } }); kayitbuton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,KayitSayfasi.class); startActivity(intent); } }); } private void Giris() { mAuth.signInWithEmailAndPassword(userName,userPassword).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ //Kayıt başarılı olursa profil sayfasına gidiyoruz Intent i = new Intent(MainActivity.this,ProfilSayfasi.class); startActivity(i); finish(); } else{ // Eğer Hata ile karşılaşırsak hata mesajını bastırıyoruz Toast.makeText(getApplicationContext(),task.getException().getMessage(),Toast.LENGTH_SHORT).show(); } } }); } } |
kayit_sayfasi.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="70dp" android:orientation="vertical"> <ImageView android:id="@+id/imageView2" app:srcCompat="@drawable/kayitsayfasi" android:layout_width="150dp" android:layout_height="150dp" android:layout_marginLeft="120dp" /> <EditText android:id="@+id/kayitkullaniciadi" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Kullanıcı Adı" android:inputType="textPersonName" /> <EditText android:id="@+id/kayitsifre" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Şifre" android:inputType="textPersonName" /> <Button android:id="@+id/kayitbuton" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/holo_blue_light" android:text="KAYIT OL" android:textColor="@android:color/white" /> </LinearLayout> </LinearLayout> |
KayitSayfasi.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
package com.example.esatgozcu.firebaseauthenticationislemleri2; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task;import android.content.Intent; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; public class KayitSayfasi extends AppCompatActivity { private EditText kayitkullaniciadi; private EditText kayitsifre; private Button kayitbuton; private FirebaseAuth mAuth; private String userName; private String userPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.kayit_sayfasi); kayitkullaniciadi=(EditText)findViewById(R.id.kayitkullaniciadi); kayitsifre=(EditText)findViewById(R.id.kayitsifre); kayitbuton=(Button)findViewById(R.id.kayitbuton); //Firabase kimlik doğrulama refaransını oluşturuyoruz mAuth = FirebaseAuth.getInstance(); //Kayıt ol butonuna tıklanınca.. kayitbuton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { userName = kayitkullaniciadi.getText().toString(); userPassword = kayitsifre.getText().toString(); if(userName.isEmpty() || userPassword.isEmpty()){ //Eğer boş alan bıraktıysa hatayı yazdırıyoruz Toast.makeText(getApplicationContext(),"Boş Alan Bırakmayınız !",Toast.LENGTH_SHORT).show(); }else{ kayıt(); } } }); } private void kayıt() { // addOnCompleteListener ile işlemin başarılı olup olmadığını kontrol ediyoruz mAuth.createUserWithEmailAndPassword(userName,userPassword) .addOnCompleteListener(KayitSayfasi.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(Task<AuthResult> task) { if(task.isSuccessful()){ //Bağlantı başarılı olursa MainActivity sayfasına yönlendiriyor Intent i = new Intent(KayitSayfasi.this,MainActivity.class); startActivity(i); finish(); } else{ //Her hangi bir hata olursa hatayı yazdırıyoruz Toast.makeText(getApplicationContext(),task.getException().getMessage(),Toast.LENGTH_SHORT).show(); } } }); } } |
Şimdi uygulamamızı açıp kayıt olduktan sonra giriş yapalım. Giriş yaptıktan sonra bizi aşağıdaki gibi bir sayfa bekliyor. Profil sayfası için aşağıdaki gibi kodlarımız düzenleyelim.
profil_sayfasi.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="~~HOŞGELDİNİZ~~" android:textAlignment="center" android:textColor="@android:color/black" android:textSize="36sp" /> <TextView android:id="@+id/kullaniciaditxt" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:text="kullanıcı" android:textAlignment="center" android:textColor="@android:color/black" android:textSize="24sp" /> <Button android:id="@+id/sifredegistir" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="80dp" android:layout_marginRight="80dp" android:layout_marginTop="80dp" android:background="@android:color/white" android:text="Şifre Değiştir" android:textColor="@android:color/holo_red_dark" /> <Button android:id="@+id/maildegistir" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="80dp" android:layout_marginRight="80dp" android:layout_marginTop="10dp" android:background="@android:color/white" android:shadowDx="5" android:shadowDy="5" android:text="Mail Değiştir" android:textColor="@android:color/holo_red_dark" /> <Button android:id="@+id/cikisyap" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="80dp" android:layout_marginRight="80dp" android:layout_marginTop="10dp" android:background="@android:color/holo_red_dark" android:text="Çıkış Yap" android:textColor="@android:color/white" /> </LinearLayout> </LinearLayout> |
ProfilSayfasi.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 |
package com.example.esatgozcu.firebaseauthenticationislemleri2; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.InputType; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; 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.FirebaseUser; import com.google.firebase.auth.FirebaseAuth; public class ProfilSayfasi extends AppCompatActivity { private TextView kullaniciaditxt; private Button maildegistir; private Button sifredegistir; private Button cikisyap; private FirebaseAuth auth; private FirebaseUser firebaseUser; private FirebaseAuth.AuthStateListener authListener; private String str; @Override public void onBackPressed() { //Telefondan geri tuşu basıldığında.. Toast.makeText(ProfilSayfasi.this, "Geri Tuşu Pasif Hale Getirildi", Toast.LENGTH_LONG).show(); } @Override public void onStart() { super.onStart(); auth.addAuthStateListener(authListener); } @Override public void onStop() { super.onStop(); if (authListener != null) { auth.removeAuthStateListener(authListener); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.profil_sayfasi); //FirebaseAuth nesnesini getInstance ile çağırıyoruz auth = FirebaseAuth.getInstance(); //Giriş yapmış kullanıcıları çağırıyoruz firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); //Değişiklik yapılıp yapılmadığı dinleniyor authListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user == null) { //Değişiklik olduğunuda finish(); } } }; kullaniciaditxt = (TextView) findViewById(R.id.kullaniciaditxt); maildegistir = (Button) findViewById(R.id.maildegistir); sifredegistir = (Button) findViewById(R.id.sifredegistir); cikisyap = (Button) findViewById(R.id.cikisyap); //Textview'e giriş yapan kullanıcının mail adresini yazdırıyoruz kullaniciaditxt.setText(auth.getCurrentUser().getEmail()); cikisyap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { signOutFunc(); } }); maildegistir.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { str = "Lütfen yeni e-posta adresini giriniz."; changeEmailOrPasswordFunc(str, true); } }); sifredegistir.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { str = "Lütfen yeni şifreyi giriniz."; changeEmailOrPasswordFunc(str, false); } }); } private void signOutFunc() { //Session(oturum) kapatılıyor uygulama yeniden başladığında tekrardan giriş yapılması gerekecek auth.signOut(); } private void changeEmailOrPasswordFunc(String title, final boolean option) { //Anlamakta zorlanıyorsanız AlertDialog ile ilgili makaleme göz atabilirsiniz AlertDialog.Builder builder = new AlertDialog.Builder( ProfilSayfasi.this); final EditText edit = new EditText(ProfilSayfasi.this); builder.setPositiveButton(getString(R.string.change_txt), null); builder.setNegativeButton(getString(R.string.close_txt), null); //LayoutParams layoutların özelliklerini (en,boy,yazının konumu vb.) kod üzerinde değişiklik yapma imkanı sağlar LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); edit.setLayoutParams(lp); //Fonksiyonun ikinci parametresi true veya false olmasına göre textin tipini değiştiriyoruz //True ise birinci kısım çalışıyor ve normal yazılar görünür şekilde yazılıyor //False ise ikinci kısım çalışıyor ve şifre olduğu için yazılar nokta şeklinde gözükecek if (!option) { edit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } builder.setTitle(title); builder.setView(edit); final AlertDialog mAlertDialog = builder.create(); mAlertDialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { Button b = mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (edit.getText().toString().isEmpty()) { edit.setError("Lütfen ilgili alanı doldurunuz!"); } else { //İkinci parametre true ise if (option) { //Mail değişiyor changeEmail(); //İkinci parametre false ise } else { //Şifre değişiyor changePassword(); } } } }); } private void changePassword() { //updatePassword methodu ile şifreyi güncelliyoruz firebaseUser.updatePassword(edit.getText().toString()) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { //Başarılı ise Toast.makeText(ProfilSayfasi.this, "Şifre değiştirildi.", Toast.LENGTH_LONG).show(); signOutFunc(); } else { //Başarısız olursa hatayı bastırıyoruz edit.setText(""); Toast.makeText(ProfilSayfasi.this, task.getException().getMessage(), Toast.LENGTH_LONG).show(); } } }); } private void changeEmail() { //updateEmail methodu ile mail adresiniz güncelliyoruz firebaseUser.updateEmail(edit.getText().toString().trim()) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(Task<Void> task) { //Başarılı olursa if (task.isSuccessful()) { Toast.makeText(ProfilSayfasi.this, "E-posta değiştirildi.", Toast.LENGTH_LONG).show(); signOutFunc(); } else { //Başarısız olursa hata mesajını bastırıyoruz edit.setText(""); Toast.makeText(ProfilSayfasi.this, task.getException().getMessage(), Toast.LENGTH_LONG).show(); } } }); } }); mAlertDialog.show(); } } |
AndroidManifest.xml dosyamızı aşağıdaki gibi düzenliyoruz.
AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.esatgozcu.firebaseauthenticationislemleri2"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".KayitSayfasi"> <intent-filter> <action android:name="android.intent.action.Kayıt" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name=".ProfilSayfasi"> <intent-filter> <action android:name="android.intent.action.Profil" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> </application> </manifest> |
Böylelikle Firebase Kütüphanesi ile bir uygulama yazdığımız zaman Authentication işlemlerini nasıl yapabileceğimizi girdiğimiz bilgileri nasıl güncelleyebileceğimizi görmüş olduk.
Projenin kaynak kodlarını buraya tıklayarak indirebilirsiniz.